Skip to content

SDKs

OpenDecuma is the application layer; a harness is a program that works on it: a bookkeeping script, an integration, an agent loop around a model. It reaches the instance through the same Commands and queries as the web app, with an API-Schlüssel, and through nothing else. The SDKs in sdk/ (Python, TypeScript, Rust; Apache-2.0, ADR 0033) are that access in three languages. Everything here is the same in all three; names follow the language (from_env, fromEnv, from_env).

Language Install First call
Python 3.11+ pip install "git+https://github.com/rapha-red/open-decuma#subdirectory=sdk/python" (no dependency) Decuma.from_env().journal_list({"per_page": 5})
TypeScript, Node 22.18+ from a checkout: (cd sdk/typescript && npm ci), then npm install <checkout>/sdk/typescript await Decuma.fromEnv().query('journal.list', { pro_seite: 5 })
Rust in Cargo.toml: decuma-sdk = { git = "https://github.com/rapha-red/open-decuma" } Client::from_env()?.journal_list(&params).await?

The SDKs are installed from the repository; they are not published to PyPI, npm or crates.io. From a local checkout instead: pip install ./sdk/python, decuma-sdk = { path = "<checkout>/sdk/rust" }. (scripts/release.sh can publish them to the registries; it is not run yet.)

The REST API under /v1, the CLI, the MCP tools and the SDKs follow Semantic Versioning: within a major version a Command, query, field or error code is only added, never renamed or removed, and a new optional field never changes what an existing call does. A breaking change comes with a new major version (and /v2 for the REST API); CHANGELOG.md lists every release. The three SDKs carry the version of the OpenAPI document they are generated from.

The examples in sdk/*/examples/ run from the checkout without installing. A local instance to call: decuma dev --seed muster-gmbh prints address and api-key (Demo instance).

What Python TypeScript Rust
Client Decuma(url, token=, mandant=, language=, timeout=) new Decuma(url, {token, mandant, language, timeout}) Client::new(url).token(..).mandant(..).language(..).timeout(..)
From the environment Decuma.from_env() Decuma.fromEnv() Client::from_env()
Sign a person in d.sign_in(email, password, code=None) await d.sign_in(email, password, code?) client.sign_in(email, password, code).await?

from_env reads DECUMA_URL (default http://127.0.0.1:8080) and DECUMA_API_KEY, as the CLI does.

Two kinds of credential, both sent as Authorization: Bearer:

  • API-Schlüssel: for a harness. Bound to one Mandant (no Decuma-Mandant), limited to the Freigabeklassen it was created with (without any it only reads: queries and exports, no other Command; ADR 0047), never able to do what is for a human only. A person creates it (api_key.create, second factor required) and sees the secret once.
  • Session: for a person. sign_in keeps the token; a session works on every Mandant of the person, so set mandant (Decuma-Mandant) before a Mandant call. Use a session to set a harness up (create the key, set the Freigaberichtlinie), not to run it.

language (de or en) chooses the language of detail, next_step and warning texts.

Every change is a Command, every read a query; both are called by their name, or through a generated method (buchung_post, command_check) in Python and Rust. Payloads and results are typed from the OpenAPI document: TypedDicts in Python, structs in Rust, openapi-typescript types in TypeScript. Money is a decimal string ("119.00"), never a float; in Python results parse to Decimal, in Rust to rust_decimal::Decimal.

Every schema of the document has an explicit, stable name (BefehlPruefung, JournalGebucht, ListeEreigniszeile; a test refuses a name the generator would number). On top, per operation: <Operation>Payload and <Operation>Output in Python and Rust (CommandCheckPayload, CommandCheckOutput), and CommandPayload<'name'>, CommandResult<'name'>, QueryPayload<'name'>, QueryResult<'name'> in TypeScript. Where every field of a payload is optional it may be left out.

The result of a Command or query carries warnings ({code, text, next_command?}) when there are any; they never block, and next_command names the Command the text points to, the same in every language. In Rust every method returns Outcome<T> (value and warnings).

Options of a Command call: rationale (why; stored in the Command-Log), idempotency_key (idempotencyKey in TypeScript, Opts in Rust) and origin {kind, id, display_name}: what the call comes from beyond the credential (an automation, an integration), stored with the entry, shown in the Verlauf as the subtitle of the real Actor and a filter of history.list (origin_kind, origin_id; REST).

Tools: what may I call, would this call work

Section titled “Tools: what may I call, would this call work”
  • access.tools (query): the Commands and queries this credential can use on its Mandant, filtered like access.commands, and the installation’s reference queries (category.list, steuerschluessel.valid, event.types, form_definition.get, …), which MCP offers as tools too. Per tool: name, art (command or query), beschreibung, payload_schema and output_schema (JSON Schema 2020-12, inlined, so a model can be given them as they are), freigabeklasse, nur_mensch (a human only), idempotent, begruendung_pflicht. Names contain a dot; a model API that allows no dot in tool names needs a name map on your side.

  • command.check (query): a dry run of one Command with a payload and Begründung, and optionally the origin it would be executed with (checked as executing checks it; the Freigaberichtlinie decides with it as it would then). It runs the checks of execution before the handler (payload shape, “human only”, second factor, Freigaberichtlinie, Begründung) and answers ergebnis:

    • ausfuehrbar: it would execute now, without anyone’s confirmation.
    • braucht_menschen: a human must give or confirm it (code needs_human).
    • abgelehnt: refused, with code, detail and next_step.

    With idempotency_key, the key the call would carry, a replay is checked as one.

    Nothing changes, nothing is logged. The handler’s own refusals (a closed period, a missing Beleg) show in the dry run of the Command itself (next item).

  • dry_run: true in the body of any Command (REST {"payload": ..., "rationale": ..., "dry_run": true}, the MCP argument dry_run, --dry-run in the CLI, dryRun / dry_run in the SDKs): first the checks of command.check, then, unless one of them refuses, the Command’s handler in a transaction that is always rolled back. The answer is a BefehlPruefung as above (HTTP 200) with output: what executing would return now, its warnings inside. A refusal of the handler (a Buchung dated in a locked year, a closed Bankkonto) is abgelehnt with its code, detail and next_step; when the Freigaberichtlinie asks a person, the handler does not run and the answer is braucht_menschen with where to confirm, without output. Nothing stays: no row, no Command-Log entry, no Event or webhook, no confirmation, no attempt; the idempotency key is not used up (a key used before answers its first result). Ports with an outside effect do not act: mail is accepted and not sent, a transmission is handed over as by hand and not sent, and every other port or service the dry run does not know to be safe (reading, decision, Hinweise, bank, USt-IdNr. confirmation, push) is absent, so the handler answers as on an installation without it. A secret the handler makes (a key, a link) is shown as [secret]: it never existed. Failed sign-in counts stay counted; Commands without sign-in, installation Commands and read-only Commands such as check.export and datev.export (what they return is their result) have no dry run (validation). A query takes no dry_run.

  • command.basis (query): what in the Mandant’s own records already stands behind a proposed Command, with {command, payload} as for command.check. It answers {rule, precedent, bank_match}, each null when there is none:

    • rule {rule_id, name}: an active Regel that would issue exactly this Command with this payload (its action filled with the payload’s own values is the payload, and its condition holds for them).
    • precedent {seq, time, buchung_id} (buchung.record only): the latest capture a person booked or confirmed with the same Geschäftspartner (else Aussteller), the same Kategorien and Steuersätze, not reversed; seq is its entry for history.get.
    • bank_match {candidates, single_match, proposal_matches} (bank_transaction.assign only): the number of candidates the deterministic Abgleich has for the Bankumsatz, the only candidate when its amount equals the Bankumsatz (what bank_transaction.assign_matching links), and whether the proposal links exactly it.

    Read only, with the rights of running the Command: a team member is refused what their capabilities do not include (a payroll Command without “Sieht Lohn” is not_allowed), a payload naming a payroll row is not_found, and without “Sieht Lohn” no payroll row is a precedent, a candidate or a covering Regel. It decides nothing; what the caller does with the answer (propose, ask, execute) is its own policy.

A Command marked RUN_BY other than Anyone is no tool of a program: Person (the year lock and its Berichtigung, ADR 0042: the handler answers needs_human to any program) and Installation (the installation’s own consumers, such as case.propose_category). They are left out of access.commands, access.tools and MCP tools/list for programs; command.check answers braucht_menschen for a Person Command.

A Command marked BOOKS_BELEGE (Entry::books_belege in the registry) can book a capture or Belege: its handler can reach the booking of a capture, a Buchung by hand with Belege, a recurring expense’s rate (its contract is the Beleg), the booking that waited for an exchange rate or an open case’s Buchung, also through a Command it runs as the Regel; or it makes a document the evidence of what is booked later (recurring_expense.create). An installation that embeds the crates and adds a step of its own to the policy (checking the invoice of every case a Command books before an automated Actor executes it) reads this mark to know which Commands it must look at; a path from an unmarked Command to such a booking fails the tests of this repository.

attention.list (query) answers “what do I do next” for the Mandant in one call, most urgent first (dated items by their day, overdue ones first; then the queues and the Hinweise). Per item: kind (release, filing, frist, year_end, question, beleg, bank_transaction, notice), text, reference (the Meldung, the year, the code of a Hinweis), due_on, overdue, amount, count (a queue), source (where a Hinweis comes from), next_command with next_payload where the item knows it, needs_person (true when a person takes or answers the step, e.g. the Freigabe) with person_reason and the app’s href. Items also carry frist, state and step for Meldungen. A loop reads it, calls next_command, and stops when only needs_person items and notices remain. horizon_days (default 30, up to 400) sets how far ahead a Frist that cannot be acted on yet is listed (kind frist). Each source runs only when the caller may run its query directly, so a team member without “Sieht Lohn” gets no payroll item (ADR 0050).

Parity: everything the web app does is a tool for a key with the Freigabeklasse it needs, except what is a person’s by design (the person’s own Account and sessions, credentials and rights, the Freigabe of a filing bound to its hash). The guard test every_operation_of_the_app_is_open_to_an_api_schluessel_or_human_by_design (crates/decuma-server/tests/surfaces.rs) holds that list with a reason per entry and fails when the app uses anything else a key cannot. scripts/agent-month.py works one month of a GmbH over MCP only against decuma dev.

A refusal is a Problem: status, code (a string, so a code of a later instance still arrives), detail, next_step (both in language), needs_human, and the whole body (body). Nothing was executed.

code status What a harness does
validation 422 Read detail and next_step, correct the payload, propose again
not_authenticated 401 The key is missing, revoked or expired: stop, a person creates a new one
not_allowed 403 The credential may not do this: stop or choose another way
needs_human 403 A human must decide: stop and hand over; do not retry, do not look for a way around
second_factor_required 403 A person must set up or give the second factor
unknown_command, not_found 404 Wrong name or id: list the tools again
conflict 409 The state does not allow it; next_step says what to do first
idempotency_conflict 409 The same key was used with another payload: use a new key for new work
busy 503 Nothing was done, another Command of this Mandant runs: the same call again after Retry-After, with the same idempotency key
internal 500 Retry later with the same idempotency key

A network failure is not a Problem: it is the language’s own error (URLError, a rejected fetch, Error::Transport). Calls time out after 30 seconds by default (timeout). The SDKs do not retry by themselves; retry a Command only with an idempotency key.

idempotency_key makes a Command safe to repeat. The same key with the same payload returns the first result unchanged and runs nothing; the result then carries the warning dublette. The same key with another payload is idempotency_conflict. A repeat passes a limit of the installation that the first call used up, and uses none of it; your rights are checked as on the first call (ADR 0054). Derive the key from the work (a Beleg hash, a bank transaction id), not from the attempt, so that a restarted harness repeats the key.

Over plain REST the key is the header Idempotency-Key: 1 to 255 visible ASCII characters, for example a UUID. Every Command a signed-in caller sends takes one (its entry in the OpenAPI document lists the parameter Idempotency-Key). A key on a call without sign-in or on an installation Command, and an empty, too long or non-ASCII key, is refused with validation (422) before anything runs; detail says which of these it is. Queries ignore the header. POST /v1/files takes it too; the MCP tools take no key, so a repeated MCP call is a new call. A key is scoped to the Mandant, the Command and the caller. The first result comes back as it was logged: a secret it held (a new API-Schlüssel, a link shown once) reads [secret], and a Command that deletes its own Command-Log (mandant.delete, account.delete) keeps no key.

Every Command an Agent issues needs a non-empty Begründung (validation otherwise); the MCP server requires it of every tool. With an API-Schlüssel over REST it is optional, but send it: it is stored with the Command in the Command-Log (GoBD evidence of who did what and why) and shows in history.list.

Every list query takes the same Listenabfrage (text, von, bis, filter, sortierung, seite, pro_seite up to 500, format) and answers one page: rows, gesamt (after the filters), alle, seite, pro_seite. To read all rows of a list use the iterator, which asks page after page:

  • Python: for zeile in d.rows("journal.list", {"filter": {...}})
  • TypeScript: for await (const zeile of d.rows('journal.list', {...}))
  • Rust: let rows: Vec<types::Buchung> = client.rows("journal.list", &params).await?

The format values csv, xlsx and pdf return the file in datei (dateiname, media_type, content) for one query as it is, not per page.

upload_path(path) (uploadPath, upload_path) stores one file unchanged in the Belegablage and returns its SHA-256 hash. The media type follows the extension (.pdf, .jpg, .png, .webp, .heic, .xml) unless passed; the instance checks that the content is what it claims. upload(bytes, media_type) is the same for bytes in memory. Then beleg.deliver {seiten: [hash, ...]} turns the stored pages into a Beleg, and datei(hash) returns a stored file or an export (the download_url of mandant.export ends in its reference).

Every change leaves Events in the outbox. event.types lists the types with their fields, event.list the Events of the Mandant with the state of their deliveries. A harness that is reachable by URL subscribes with webhook.create {url, ereignisse: [typ]}; the signing secret is shown once.

A delivery is POST <url> with the body {id, typ, at, daten} and the header Decuma-Signatur: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>.<body>")>. Check it with the SDK on the raw bytes you received, before parsing anything else:

  • Python: ereignis = verify_webhook(secret, header, body) raises ValueError
  • TypeScript: const ereignis = await verifyWebhook(secret, header, body) rejects
  • Rust: verify_webhook(secret, header, body, now) returns Err(WebhookError)

A wrong signature, a changed body and a delivery more than five minutes old (replay) are refused. The result is the Event; typ stays a string, so an Event type a later version adds, such as the usage report of a reading provider (reading.usage), arrives like any other: route on typ, ignore what you do not know. Answer with a 2xx within 10 seconds; a failed delivery is retried with a growing delay and a webhook that fails three times in a row is paused (webhook.paused). Delivery is at least once: deduplicate on id.

A harness behind a firewall has no URL to subscribe with. It pulls the same Events with the query event.poll {nach, typen, anzahl}: the Events of its Mandant after the cursor nach, oldest first, each with the body a webhook receives ({id, typ, at, daten}), at most anzahl (1 to 500, default 100). The answer is {ereignisse, cursor, mehr}: keep cursor and pass it as nach next time (store it, so a restart goes on where it stopped); mehr says more are waiting, so call again at once instead of sleeping. typen narrows the types (from event.types); the cursor still moves past the other types. Delivery is at least once: a harness that stops between handling an Event and storing the cursor sees it again, so deduplicate on id.

Python:

cursor = gespeichert() or 0
while True:
antwort = d.event_poll({"nach": cursor, "types": ["buchung.posted"]})
for e in antwort["events"]:
verarbeiten(e) # route on e["type"]; dedupe on e["id"]
cursor = antwort["cursor"]
speichern(cursor)
if not antwort["more"]:
time.sleep(30)

TypeScript:

let cursor = gespeichert() ?? 0
for (;;) {
const antwort = await d.query('event.poll', { nach: cursor, typen: ['buchung.posted'] })
for (const e of antwort.ereignisse) await verarbeiten(e)
cursor = antwort.cursor
speichern(cursor)
if (!antwort.mehr) await new Promise((r) => setTimeout(r, 30_000))
}

Rust:

let mut cursor = gespeichert().unwrap_or(0);
loop {
let antwort = client
.event_poll(&types::EreignisHolenPayload { nach: Some(cursor), typen: Some(vec!["buchung.posted".into()]), anzahl: None })
.await?;
for e in &antwort.ereignisse {
verarbeiten(e).await?;
}
cursor = antwort.cursor;
speichern(cursor)?;
if !antwort.mehr {
tokio::time::sleep(std::time::Duration::from_secs(30)).await;
}
}

sdk/python/examples/ereignisse.py runs this loop against decuma dev --seed muster-gmbh (part of scripts/sdk.sh test). event.list is the list for people (with the state of webhook deliveries, newest first); a program reads event.poll.

sdk/python/examples/agent.py, sdk/typescript/examples/agent.ts and sdk/rust/examples/agent.rs are one loop in three languages, against decuma dev --seed muster-gmbh:

  1. The Inhaber (a person, signed in) lets the API-Schlüssel of the seed book alone up to 1000.00 (approval_policy.set_cell).
  2. The harness, with the key only, lists its tools (access.tools).
  3. For each proposal (a fixed list here; a model in a real harness) it dry-runs the Command (command.check): abgelehnt is reported with code, detail and next_step so the proposer can correct it; ausfuehrbar is executed with a Begründung and an idempotency key; braucht_menschen stops the loop and hands over.
  4. It checks the result in the Journal, not in the answer it was given.
Terminal window
cargo build -p decuma-server --bin decuma
DECUMA_DEV_POSTGRES_URL=postgres://... target/debug/decuma dev --seed muster-gmbh # prints address and api-key
DECUMA_URL=http://127.0.0.1:<port> DECUMA_API_KEY=<api-key> python3 sdk/python/examples/agent.py

scripts/sdk.sh test starts the instance, passes the printed address and key, and runs the three examples; each asserts its own outcomes (one refused proposal, one executed, one stop at needs_human, one Buchung in the Journal even after a second run) and exits non-zero otherwise.

A reading or decision provider of your own plugs in the same way or as a port: Ports and hooks.

What the loop leaves to you: where proposals come from, how a tool result and a Problem are shown to the model, how long a human may take. Those are the harness; the application layer only guarantees that nothing a harness does bypasses the Freigaberichtlinie, the Begründung, the idempotency or the log.