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: Debugging · Diagnose failures. 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: Developers who can compare a request, a trace and an authoritative result.

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.

Debugging · Diagnose failures

Find the first wrong boundary using request and ledger evidence

Objectives of this level: Diagnose a valid foreign request and an ambiguous retry without conflating denial, conflict and business failure.

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.

Reproduce two failure inputs: order_id=order-b under tenant-a, and amount_minor=301 with the already committed refund-1 key. Keep the schema result, trusted Context, public error gate, current order version and effect count. The demo emits these observations as JSON; no production incident is being described.

For the foreign request, first show validate_shape returns None. Next compare the trusted tenant with the authority's resource owner inside the boundary. A shape-only guard would lose this distinction. The repair is a server-side object authorization check and a non-enumerating denial, followed by a rerun proving zero effects. A prompt telling the model to choose the correct tenant is not this repair.

For the changed retry, inspect the existing receipt and request fingerprint before considering the current resource version. The root cause is a reused operation identity for changed semantics. Correct the caller to preserve the old payload for reconciliation, or create a new reviewed business intent. Do not generate a fresh key just because the network response was missing.

Finally run the reopen and two-connection tests. They close the caller after local commit and deliver one intent through two SQLite connections. The observed single ledger row supports these local schedules. It does not test a process killed mid-COMMIT, storage failure, or an external payment provider. Expand the separate idempotency recovery lesson when the effect crosses services.

A complete worked run

from tool_contract_deep_dive import Executor, Context, request, validate_shape
e = Executor()
ctx = Context('tenant-a', 'user-a')
bad = request(order_id='order-b')
assert validate_shape(bad) is None
assert e.execute(ctx, bad)['gate'] == 'authorization'
assert e.state()['effect_count'] == 0
assert e.execute(ctx, request())['status'] == 'committed'
assert e.execute(ctx, request(amount_minor=301))['gate'] == 'idempotency_conflict'
assert e.execute(ctx, request())['status'] == 'replayed'
print(e.state()['remaining_minor'], e.state()['effect_count'])
e.close()

Actual rerun output: 700 1. These checks expose distinct authorization and identity failures before accepting the repaired receipt.

Exact diagnosis start

The worked diagnostic script creates a fresh e and runs all calls in that one instance. The foreign request happens before any refund, so its effect_count=0 is meaningful. The changed retry happens only after refund-1 committed; it must leave one effect. These are two different schedules, not two edits to a persisted module output.

For a repair exercise, copy tool_contract_deep_dive.py to tool_contract_learner.py. In that copy only, temporarily remove the row[0] != context.tenant ownership condition. Run a fresh Executor with the valid order-b request: the foreign write is now wrongly allowed. Restore the ownership condition and rerun exactly that input to show authorization and zero effects. Keep both outputs and the changed source. This is a local fault injection; never disable an authorization check in a real service.

For the injected-fault script import from the learner copy explicitly: from tool_contract_learner import Executor, Context, request. The worked reference script above imports the original module and remains unchanged. Use a fresh instance for both before/after runs so an earlier effect cannot contaminate the comparison.

A decision-specific contract from an actual failure

The complete repair separates the evidence needed to create a proposal from evidence sufficient to route an actual battery exception to review. The runtime reconstructs the same explicit contract shown to the model. A review label without a real trigger is rejected; a prose citation and an unsafe proposal missing proof remain invalid. Complete candidates stay in the audit, while only selected context text is delivered. The article provides the tested full patch and recorded-output comparison; replay is not a new generation test.

Follow the battery failure without replacing its output

Visual guide · A corrected citation exposed the next wrong rule

A corrected citation exposed the next wrong rule

The first two candidates came from real provider runs. Acceptance after contract repair is literal old-output replay, with zero new provider requests. Select the figure to open it at full size.

Start with live-20261030-battery, whose authorized order is o-battery, kind="battery", age_days=5, quantity 1. The model returned decision="manual_review", but its citation was the full battery policy sentence followed by (Policy ID: d-battery). JSON Schema permitted a string; the runtime's exact membership test against d-battery, d-general, d-proof raised citation_outside_actual_context. The answer remained unsaved.

The directed historical run appended an exact-ID instruction. Its first request changed only /instructions; later requests include newly generated call IDs and a changed retrieval query, so do not claim byte-identical whole conversations. After three additional provider requests, the new candidate used citations=["d-battery"] and still failed with missing_policy_evidence. The old validator reused proposal coverage for review: it demanded general+proof+battery although this candidate only routed a real battery case to human review and created no proposal.

Repair the decision contract, then replay the unchanged objects through both sources. after-sales-evidence-v1 derives battery_item from the authorized order, requires selected d-battery for that trigger, and sets proposal.allowed=false. The same exact-ID candidate changes from old failed to repaired answer_ready, with no proposal. This is a validator/interface repair observed by local replay, not evidence that a new generation obeyed the new prompt. All 12 historical provider requests were already consumed; this contract comparison used zero new provider requests.

Keep counterexamples beside the success: prose remains citation_outside_actual_context; the ordinary proposal omitting proof remains missing_policy_evidence; a synthetic ordinary manual_review is rejected with manual_review_not_supported even when battery text is present in context. The positive synthetic eligible fixture only reaches awaiting_approval. Both controls are authored fixtures, not provider successes. All replay cases have zero merchant approvals, receipts and returns.

Inspect original battery trace, directed battery trace, request diff, old/new replay ledger and live status. Replay source IDs are baseline and repaired; never merge them into the historical live ledger.

Diagnose from the first unsupported claim of success

In the evidence exercise, read selected context, candidate policy IDs and saved proposal receipt before changing a validator. If proof is missing from selected evidence, valid JSON does not authorize a proposal. In the forged-receipt exercise, compare task, order, quantity, proposal hash and operation key with the merchant ledger; a plausible JSON object cannot authorize settlement by itself.

After a dropped response, query the original receipt before new-write preconditions. Do not erase a valid committed history because the current worker or authority changed. Source-bound evidence separates accepted proposal, fixture approval, unknown result and completed effect; the original verifier stays unchanged throughout repair.

Continue the connected project article and inspect the executable entrypoint.

Diagnose citation identity, fact support and action authority separately

Explain the recorded correct decision with failed atomic eligibility attribution, then run the zero-call authored repair and nine negatives. Check schema, direct assertions, registered rule, premises and conclusion binding in order; models do not grant merchant authority. These two new decision checks execute no new MCP business write. A proved answer is not a completed return receipt.

See project section11, walkthrough and single contract definition.

Distinguish a valid historical answer from revoked-context reuse

Compare attempt18 gift/manual_review with its authorized historical snapshot, owner change to Bob and denied Alice read. The original can receive a scoped prose-pass reference; current reuse after revocation is an authored failing scenario. Do not rewrite the response or let prior access bypass current authority. The authored fake-receipt answer from attempt19 separately shows why proof success cannot replace effect verification.

See section12, review form and workflow.

Check source, version, quotations and authority in order

Read initial/adjudicated/revised records and stale-check errors in section 13. Check same order/base_candidate, explicit edit replay, 40 inherited files and 17 pinned sources. Correct new quotes/hashes do not establish current authority or human signatures. teaching_example is never converted into actual human origin and authorization stays false.

See section 13 and the walkthrough.

Trace prose to evidence and authority before choosing next steps

Section 14 requires the full base_candidate, current context, source pointers and authority changes alongside prose. Explain direct facts, derivations and missing evidence. Consult the separate teacher archive after submission; it is not an automatic grading input.

See section 14 and the learner instructions.

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 →

code example

Business state after authorization

On a fresh authority commit amount_minor=800. A new refund-2 with expected_version=2 and amount_minor=300 passes shape and authorization but fails business_state because only 200 remains. The ledger stays at one effect. This distinguishes insufficient remaining amount from a foreign-resource denial.

Acceptance task for this level

Reproduce foreign_order and changed_retry in the single-instance schedule above. In tool_contract_learner.py inject and repair the missing ownership guard. Save original input, failed-before/passed-after outputs, changed source and post-repair ledger. Rerun test_deep_dive.ToolContractTests for the unchanged reference. Continue evidence-v2 practice; preserve the original failure, your own repair and unchanged-checker results. Complete semantic-review practice, separating teaching references, declaration completeness and actual human signoff. Replay the same-task review cycle, preserving initial reviews, stale-binding rejection and fresh records. Complete three source review exercises, preserving submissions, revisions and manual comparisons.

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

After an HTTP timeout, a developer changes the operation ID so the retry will pass. What evidence is missing?

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.