Skip to content
Agent Field Notes
Course contentsExpand a topic to choose a lesson.

SYSTEMATIC LEARNING / FOUR-LEVEL COURSE

Tool contracts: from a valid request to an authorized business effect

Build a refund boundary, inject valid-but-unauthorized and stale requests, then change the contract and the authority boundary.

Learning objectives: Explain and implement separate shape, business, authority, state and receipt checks; identify which guarantees survive retries and service separation.

Content checked: 2026-11-03 · Each level has independent explanations, tasks and inspections

Choose a starting point based on your familiarity with this topic. Current level: Design · Explain the trade-offs. After completing the task, continue to the next level. Reading and self-checks alone do not establish mastery.

On this level

Review the prerequisites

Suitable for: Engineers choosing guarantees across services, time and failure boundaries.

Schema
A contract describing field shapes, types, and constraints. Valid fields do not establish that the caller is authorized to perform the action.
Trusted context
Identity and tenant information obtained through server-side authentication. Do not directly trust identity values supplied by the model.
Side effect
A write to the external world, such as a payment, publication, or deletion.
State version
The version of a resource's current state, used to detect changes since the check.

How does the mechanism work?

Tool calls: trust boundaries from proposal to receipt
  1. 1
    Model

    Proposes a tool name, arguments, and call_id. All are candidate inputs.

  2. 2
    Runtime

    Checks the allowlist, completeness, shared budget, and arguments. A failed check stops the action.

  3. 3
    Business service

    Reads identity from a trusted session; checks resource ownership and current permissions, then state at the commit boundary.

  4. 4
    Tool adapter

    Correlates success, failure, or unknown receipts by call_id and preserves facts that already occurred.

  5. 5
    Acceptance

    Adds the receipt to the next input; checks the final answer against facts before reporting business completion.

Valid structure grants no permission. call_id correlates a call in this turn; it cannot replace a business operation key across recovery.

Step-by-step explanation
  1. Candidate parameters

    The model proposes actions and parameters.

  2. Structure and semantics

    Check fields, types, units, and constraints relating them.

  3. Identity and state

    Check actual permissions and the current business state.

  4. Execution and receipt

    Execute conditionally and verify the results and business evidence.

Design · Explain the trade-offs

Change units, versions and the business authority boundary

Objectives of this level: Design a compatible upgrade and a remote-write protocol without silently weakening action semantics.

Visual guide · Fresh effects pass separate gates

Fresh effects pass separate gates

This is the fresh-action path. Authorized receipt replay is checked before new resource preconditions; the local transaction does not include remote payments. Select the figure to open it at full size.

Change two constraints. Old tasks carry v1 amount_cents with USD implicit; new tasks require v2 amount_minor plus currency. Also move the refund ledger to a remote provider that cannot share the orchestrator's transaction.

Pin the request and result contract version in durable intent state. A v1 adapter may map integer USD cents to integer v2 USD minor units only because this mapping preserves the unit and currency. It must reject an unsupported currency or fractional amount, and it must not reinterpret v1 amount=3 as three dollars. Reconstruct all defaults before displaying an approval. An adapter that changes the actual target or amount invalidates the old approval. Result evolution also matters: a new status pending_settlement is neither success nor safely retryable failure.

For a remote authority supporting idempotency, persist intent and payload hash before dispatch, reuse its operation key, and query/replay the provider's receipt after uncertainty. This adds reconciliation latency and retention requirements. For a query-only provider, preserve unknown until visibility and correlation rules can distinguish absent from not-yet-visible; do not promise at-most-one effect from a preflight query alone. Without idempotency or a reliable query, restrict automatic retries and require review of unknown effects.

Compare a pinned v1 implementation, a semantics-preserving adapter and explicit migration. Pinning simplifies old-task behavior but extends maintenance; adapters reduce implementations but need contract fixtures; migration can retire v1 but must record intent transformation and renew affected approvals. Test result versions and rollback while in-flight v1 tasks still exist. These are design proposals; the local lab does not execute a remote provider.

One concrete changed-constraint decision

Assume the provider retains idempotency keys for 24 hours, its read API can identify an operation by the original key, and the caller resumes after a 36-hour outage. Local uniqueness still holds, but the provider's deduplication promise has expired. Preserve the original intent as unknown, query that operation's authoritative result and require manual reconciliation if the query cannot distinguish an absent effect from a delayed one. A new key would weaken the guarantee even though the local database contains only one intent.

Your matrix must therefore include key retention and status visibility as inputs, alongside units/version/result enums. The output is a versioned recovery decision with its evidence and owner, not a universal “retry three times” setting.

Run experiments and observe counterexamples

Authored requests; actual local SQLite shape/authority/state/receipt checks. No model or external payment execution.

Python 3.10+ · Runs by default using only the standard library · Runs on your computer

  1. Run the module and identify each gate in events.
  2. Run ToolContractTests, including reopen and duplicate connections.
  3. Compare business state and stored receipts, then state the remote-service boundary.
Download the complete application experiment package (including data and dependent scripts) ↓
python3 -B tool_contract_deep_dive.py
View the entry-point script
"""Offline tool-boundary experiment. SQLite is the local business authority.

No model, payment API, network, or distributed exactly-once claim. Python 3.9+.
"""
import hashlib
import json
import sqlite3
from dataclasses import dataclass


@dataclass(frozen=True)
class Context:
    tenant: str
    actor: str
    scopes: tuple = ('refund:write',)


FIELDS = {'schema_version', 'operation_id', 'order_id', 'amount_minor', 'currency', 'expected_version'}


def validate_shape(request):
    if type(request) is not dict or set(request) != FIELDS:
        return 'shape_fields'
    if any(type(request[k]) is not int for k in ('schema_version', 'amount_minor', 'expected_version')):
        return 'shape_integer'  # bool is not an amount, even though isinstance(True, int).
    if any(type(request[k]) is not str or not 1 <= len(request[k]) <= 80 for k in ('operation_id', 'order_id', 'currency')):
        return 'shape_string'
    if request['schema_version'] != 2:
        return 'contract_version'
    return None


def fingerprint(context, request):
    envelope = {'domain': 'refund/v2', 'tenant': context.tenant, 'actor': context.actor, 'request': request}
    return hashlib.sha256(json.dumps(envelope, sort_keys=True, separators=(',', ':'), allow_nan=False).encode()).hexdigest()


class Executor:
    def __init__(self, path=':memory:'):
        self.db = sqlite3.connect(path, timeout=5, isolation_level=None)
        self.db.executescript('''
          CREATE TABLE IF NOT EXISTS orders(id TEXT PRIMARY KEY, tenant TEXT, remaining INTEGER, version INTEGER, currency TEXT);
          CREATE TABLE IF NOT EXISTS effects(tenant TEXT, operation_id TEXT, digest TEXT, result TEXT,
            PRIMARY KEY(tenant, operation_id));
          INSERT OR IGNORE INTO orders VALUES('order-a','tenant-a',1000,1,'USD');
          INSERT OR IGNORE INTO orders VALUES('order-b','tenant-b',1000,1,'USD');
        ''')

    def close(self):
        self.db.close()

    def execute(self, context, request):
        error = validate_shape(request)
        if error:
            return {'status': 'denied', 'gate': error}
        if not 0 < request['amount_minor'] <= 1000 or request['currency'] != 'USD' or request['expected_version'] < 1:
            return {'status': 'denied', 'gate': 'business_parameters'}
        digest = fingerprint(context, request)
        # __exit__ receives this block's outcome, not an exception currently
        # handled by the caller (e.g. a recovery inside except TimeoutError).
        with self.db:
            self.db.execute('BEGIN IMMEDIATE')
            row = self.db.execute('SELECT tenant,remaining,version,currency FROM orders WHERE id=?', (request['order_id'],)).fetchone()
            # Do not distinguish guessed foreign IDs from missing resources in the public error.
            if 'refund:write' not in context.scopes or not row or row[0] != context.tenant:
                return {'status': 'denied', 'gate': 'authorization'}
            prior = self.db.execute('SELECT digest,result FROM effects WHERE tenant=? AND operation_id=?',
                                    (context.tenant, request['operation_id'])).fetchone()
            if prior:
                if prior[0] != digest:
                    return {'status': 'denied', 'gate': 'idempotency_conflict'}
                return {'status': 'replayed', 'receipt': json.loads(prior[1])}
            if row[2] != request['expected_version']:
                return {'status': 'denied', 'gate': 'resource_version'}
            if row[1] < request['amount_minor'] or row[3] != request['currency']:
                return {'status': 'denied', 'gate': 'business_state'}
            cursor = self.db.execute('UPDATE orders SET remaining=remaining-?,version=version+1 WHERE id=? AND version=?',
                                     (request['amount_minor'], request['order_id'], request['expected_version']))
            if cursor.rowcount != 1:
                raise RuntimeError('state compare-and-swap failed')
            receipt = {'operation_id': request['operation_id'], 'amount_minor': request['amount_minor'],
                       'currency': request['currency'], 'resource_version': row[2] + 1}
            self.db.execute('INSERT INTO effects VALUES(?,?,?,?)',
                            (context.tenant, request['operation_id'], digest, json.dumps(receipt, sort_keys=True)))
            return {'status': 'committed', 'receipt': receipt}
        # The connection context commits effect and receipt on normal exits,
        # including return; exceptions from this transaction roll it back.

    def state(self):
        return {'remaining_minor': self.db.execute("SELECT remaining FROM orders WHERE id='order-a'").fetchone()[0],
                'effect_count': self.db.execute('SELECT COUNT(*) FROM effects').fetchone()[0]}


def request(**changes):
    return dict({'schema_version': 2, 'operation_id': 'refund-1', 'order_id': 'order-a',
                 'amount_minor': 300, 'currency': 'USD', 'expected_version': 1}, **changes)


def demo():
    executor, context = Executor(), Context('tenant-a', 'user-a')
    foreign = request(order_id='order-b')
    events = [
        {'case': 'foreign_order', 'shape_valid': validate_shape(foreign) is None, 'result': executor.execute(context, foreign)},
        {'case': 'model_tenant', 'result': executor.execute(context, dict(request(), tenant_id='tenant-b'))},
        {'case': 'bool_amount', 'result': executor.execute(context, request(amount_minor=True))},
        {'case': 'too_large', 'result': executor.execute(context, request(amount_minor=1001))},
        {'case': 'invalid_version', 'result': executor.execute(context, request(expected_version=0))},
        {'case': 'valid', 'result': executor.execute(context, request())},
        {'case': 'retry', 'result': executor.execute(context, request())},
        {'case': 'changed_retry', 'result': executor.execute(context, request(amount_minor=301))},
        {'case': 'new_operation_old_version', 'result': executor.execute(context, request(operation_id='refund-2'))},
    ]
    result = {'origin': 'authored_requests_local_sqlite', 'events': events, 'final': executor.state(),
              'boundary': 'One local SQLite authority; a remote side effect needs its own idempotency and reconciliation protocol.'}
    executor.close()
    return result


if __name__ == '__main__':
    print(json.dumps(demo(), indent=2, sort_keys=True))

Expected output when running locally

{
  "boundary": "One local SQLite authority; a remote side effect needs its own idempotency and reconciliation protocol.",
  "events": [
    {
      "case": "foreign_order",
      "result": {
        "gate": "authorization",
        "status": "denied"
      },
      "shape_valid": true
    },
    {
      "case": "model_tenant",
      "result": {
        "gate": "shape_fields",
        "status": "denied"
      }
    },
    {
      "case": "bool_amount",
      "result": {
        "gate": "shape_integer",
        "status": "denied"
      }
    },
    {
      "case": "too_large",
      "result": {
        "gate": "business_parameters",
        "status": "denied"
      }
    },
    {
      "case": "invalid_version",
      "result": {
        "gate": "business_parameters",
        "status": "denied"
      }
    },
    {
      "case": "valid",
      "result": {
        "receipt": {
          "amount_minor": 300,
          "currency": "USD",
          "operation_id": "refund-1",
          "resource_version": 2
        },
        "status": "committed"
      }
    },
    {
      "case": "retry",
      "result": {
        "receipt": {
          "amount_minor": 300,
          "currency": "USD",
          "operation_id": "refund-1",
          "resource_version": 2
        },
        "status": "replayed"
      }
    },
    {
      "case": "changed_retry",
      "result": {
        "gate": "idempotency_conflict",
        "status": "denied"
      }
    },
    {
      "case": "new_operation_old_version",
      "result": {
        "gate": "resource_version",
        "status": "denied"
      }
    }
  ],
  "final": {
    "effect_count": 1,
    "remaining_minor": 700
  },
  "origin": "authored_requests_local_sqlite"
}
  • foreign_order passes shape and fails authorization.
  • valid commits 300; retry replays; changed_retry is denied.
  • Final remaining_minor=700 and effect_count=1.
View the running environment, output and verification records →

Continue to do advanced research experiments

Push the read-only tool boundary to the approval boundary

First observe whether business effects have been generated while waiting for approval, and then press README to check action binding and recovery.

Read full text and fault analysis → · Download experiment package ↓

python3 approval_cli.py submit
python3 approval_cli.py run
python3 approval_cli.py inspect
# 审查 draft 和 action_json 后,按 README 使用对应 binding_hash 批准并恢复

Keep evidence and check item by item

  • Status waiting_approval, no reports service has written yet.
  • Review actions, targets, scopes, inputs, and content summaries before approving the corresponding binding_hash.
  • Run tests to reject, cancel and modify content respectively to explain why old approvals cannot be reused.

Local approval fixture; --actor is not a login or production authentication. No network by default.

code example

A compatible-looking default that is not compatible

An upgrade adds a recipient default to an old request that never resolved a target. Even if integer units map exactly, the reviewed destination is unknown. Block execution and obtain a new normalized proposal/review. Correct field names cannot establish unchanged business semantics.

Acceptance task for this level

Write a v1-to-v2 request/result compatibility matrix and a remote-timeout state diagram for idempotent, query-only and non-queryable providers. Add one fixture that must be rejected and one pending result that must be reconciled.

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

Does a local unique operation_id plus a retry policy prove that a remote provider cannot write twice?

Further explanations and practice

When encountering unfamiliar principles, first read the implementation, continuous questioning and migration cases, and then independently explain the premise and boundaries. Answers and notes are saved to the original account record.

All linked explanations and exercises (3 )

Sources and verification scope

The principles are based on public information; the numbers, cases and tasks are the teaching design of this website. Offline experiments verify the range noted on this page, and the learning effect still needs to be judged through independent tasks and feedback.