THAMER
Sovereign Bitcoin Wallet

WALLET AI BITCOIN

Your Bitcoin Wallet. Your Keys. Your Engine.

Self-hosted Bitcoin software built for developers, applications, and AI agents.

CREATE WALLET

Anthropic Claude Bitcoin Agent Integration: Handling tool_use content blocks

permalink THAMER
#ai-agents#anthropic-claude#bitcoin#python#wab-engine

Anthropic Claude Bitcoin Agent Integration: Handling tool_use content blocks

Research question

How can a developer use Anthropic Claude to select a Bitcoin operation without granting the hosted model direct access to wallet credentials? This study uses a single fixed Testnet SegWit balance query as a narrow experiment design. It is a reference implementation, not a tested integration or an official provider extension.

Protocol boundary

The application sends a tool definition and a fixed prompt to https://api.anthropic.com/v1/messages. The provider returns a proposed function invocation. The local Python process checks the response before contacting WAB ENGINE. The model cannot choose a URL, network, wallet type or credential. Handling tool_use content blocks is the specific protocol concern in this example.

Anthropic represents requests as tool_use content blocks with an input object and a tool-use ID. A continuation would use a tool_result block linked to that ID.

Source implementation

Python · 46 lines
1import json
2import os
3from urllib.request import Request, build_opener, ProxyHandler, HTTPRedirectHandler
4
5class NoRedirect(HTTPRedirectHandler):
6    def redirect_request(self, *args, **kwargs):
7        raise ValueError("Redirect refused")
8
9def post(url, payload, headers):
10    request = Request(url, json.dumps(payload).encode(),
11                      {"Content-Type": "application/json", **headers}, method="POST")
12    with build_opener(ProxyHandler({}), NoRedirect()).open(request, timeout=30) as response:
13        raw = response.read(1048577)
14    if len(raw) > 1048576:
15        raise ValueError("Response too large")
16    return json.loads(raw)
17
18def balance():
19    reply = post("http://127.0.0.1:7070/api/v5/btc/wallet/balance",
20                 {"net": "test", "type": "segwit"},
21                 {"X-BTC-KEY": os.environ["BTC_KEY"]})
22    if reply.get("ok") is not True:
23        raise ValueError("Engine rejected request")
24    sats = reply["result"]["balance_sat"]
25    if type(sats) is not int or sats < 0:
26        raise ValueError("Invalid balance")
27    return {"net": "test", "type": "segwit", "balance_sat": sats}
28
29SCHEMA = {"type": "object", "properties": {}, "additionalProperties": False}
30PROMPT = "Request the bitcoin_balance tool once. Do not estimate a balance."
31
32def main():
33    reply = post('https://api.anthropic.com/v1/messages', {"model": os.environ["ANTHROPIC_MODEL"],
34        "max_tokens": 512, "messages": [{"role": "user", "content": PROMPT}],
35        "tools": [{"name": "bitcoin_balance", "description": "Read Testnet SegWit balance", "input_schema": SCHEMA}]},
36        {"x-api-key": os.environ["ANTHROPIC_API_KEY"], "anthropic-version": "2023-06-01"})
37    calls = [b for b in reply["content"] if b.get("type") == "tool_use"]
38    if reply.get("stop_reason") != "tool_use" or len(calls) != 1:
39        raise ValueError("Expected one complete tool request")
40    call = calls[0]
41    if call["name"] != "bitcoin_balance" or call["input"] != {}:
42        raise ValueError("Unexpected tool request")
43    print(json.dumps({"tool_call_id": call["id"], "result": balance()}))
44
45if __name__ == "__main__":
46    main()

Developer setup

Use Python 3 and a locally restored Testnet wallet. Configure BTC_KEY, ANTHROPIC_API_KEY and ANTHROPIC_MODEL through a trusted local environment; select a model that supports function calling. Run python3 example.py only when you intend to make a potentially billable provider request and a local balance query. No SEND operation is exposed. The engine address is fixed to loopback; adapt deployment networking deliberately rather than accepting a model-supplied URL.

Evidence and failure handling

A provider response is a proposal, not proof of a wallet balance. The local process requires exactly one completed tool request, the expected name and empty arguments. It checks the engine success envelope and a nonnegative integer balance. Missing fields, timeouts and unsupported response formats stop execution. The printed JSON is local evidence, not a generated answer. No second model request is made, so wallet balance is not returned to the hosted model. Do not log secrets or automatically retry financial operations. The credential may authorize more than this example exposes; the tool restriction is application-level, not an engine-issued read-only credential.

Limitations and extension

No provider calls, engine calls or dependency compatibility tests were performed for this study. Endpoint and model availability may change; consult the provider documentation before use. The example is intentionally a single-turn protocol fragment, not a complete agent loop. A production application needs explicit user authorization, isolation, redacted errors, rate limits and a deliberate policy for disclosing wallet data. Payment tools require a separate approval and idempotency design; the engine's signed fee law remains unchanged.

References

  • Provider documentation: https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/overview
  • Engine API: https://thamer.org/api
  • Engine: https://thamer.org/engine
  • Source repository: https://thamer.org/repo/

Questions & Answers

Explore all questions →

Latest from the Lab

THAMER illustrated developer portrait and signature

ABOUT THE DEVELOPER

Independent Software Developer specializing in Bitcoin Script, Golang, and AI Agents.

Software engineering · Independent research · Open-source projects