# Stripe pack: REST, Python, TypeScript and MCP examples

The examples that ship inside the [Stripe Customer Operations pack](/docs/packs/stripe-customer-operations) (the same text
as the Templates tab of the pack in the app), included here from the pack's files. Each is checked against the API's
routes and request models and against the client source, and the REST and Python ones are run as written in the test
suite. They show one workflow each; the action record of the other workflows is on its page.

## REST: record an action, push the facts only your systems hold, read the verdict

Stripe, Shopify and the help desk are read by their connectors; nothing below pushes evidence for them. Your own
systems (order management, messaging) push what only they know, with an **evidence key** (`facts:write` and read
scopes, never `actions:record`): a fact pushed by a key that can also record actions is classed `agent_self_report` and
never satisfies an effect that needs shared or independent evidence.

An API key goes in the `X-API-Key` header. Create both keys in the app under Settings, API keys: one with the
`recorder` preset, one with the `evidence` preset bound to the sources it pushes (here `messaging`).

```bash
export COMMITLAYER_API="https://api.commitlayer.ai"
export RECORDER_KEY="paste-your-recorder-key"
export EVIDENCE_KEY="paste-your-evidence-key"
```

### 1. Read the contract version the install pinned

```bash
curl -sS "$COMMITLAYER_API/v1/packs/stripe_customer_operations/recorder-mapping" \
  -H "X-API-Key: $RECORDER_KEY"
```

Every rule under `tools` carries `contract_version`: the draft the install created for that contract (`1` on a
first install). Use that number below. A version the workspace does not have answers `404 unknown_contract`;
a draft nobody has selected yet answers `409 contract_not_active`, so activate the contract first.

### 2. Record the action (recorder key, `actions:record`)

```bash
curl -sS -X POST "$COMMITLAYER_API/v1/actions" \
  -H "X-API-Key: $RECORDER_KEY" -H "Content-Type: application/json" \
  -d '{
    "action_id": "cancel:sub_8Kq2",
    "contract_id": "scop_cancel_subscription",
    "contract_version": 1,
    "subject_id": "sub_8Kq2",
    "subject_kind": "subscription",
    "params": {
      "subscription_id": "sub_8Kq2",
      "customer_reference": "cus_Nf1",
      "cancel_at_period_end": true,
      "support_case_id": "zendesk_ticket_4411",
      "reason": "customer_request"
    }
  }'
```

`201` with `{action, verification, allowance}`. `requested_at` is when the agent acted (ISO-8601, UTC); the body
above leaves it out, so it is the moment of the call. An effect counts only at or after that time and inside the
contract's window, so record before the tool runs (or send the time it started as `requested_at`), and the fact
below carries the time of its own push. `cancel_at_period_end` is required: the contract compares it
with what Stripe shows, and an action that leaves it out is UNKNOWN on the policy lens
(`param_missing:cancel_at_period_end`) where it would have passed. Amounts in `params` are in major units (`30.0`
for thirty dollars); only a call that arrives through the MCP recorder is converted from the minor unit.

Recording the same `action_id` again with the same action is a no-op that returns the first record: a retried
call stays one action. The same `action_id` with another subject, another contract or another value for a
parameter both records carry answers `409 conflict` and changes nothing.

### 3. Push what your systems know (evidence key, `facts:write`)

```bash
curl -sS -X POST "$COMMITLAYER_API/v1/facts" \
  -H "X-API-Key: $EVIDENCE_KEY" -H "Content-Type: application/json" \
  -d '{
    "facts": [
      {
        "source": "messaging",
        "subject_id": "sub_8Kq2",
        "subject_kind": "subscription",
        "fact_type": "customer_notified",
        "occurred_at": "'"$(date -u +%Y-%m-%dT%H:%M:%SZ)"'",
        "attributes": {"channel": "email", "template": "subscription-cancelled"}
      }
    ],
    "links": [
      {
        "subject_id": "sub_8Kq2",
        "source": "stripe",
        "linked_subject_id": "zendesk_ticket_4411",
        "linked_source": "zendesk",
        "link_type": "ticket_to_subscription"
      }
    ]
  }'
```

`201` with `{ingested, linked}`. `occurred_at` is when it happened in your system; the example sends the time of
the push. The link lets the ticket's `status_change` count for the subscription's action; the
Stripe connector links the subscription to its customer by itself. The key must be bound to the source it pushes
(`403 source_not_allowed` otherwise), and a source a connector already serves cannot be pushed at all
(`409 source_served_by_connector`).

A pushed record counts only once an Owner or Admin attests its source for the evidence key that sent it. Until
then (in the app: Connections, "Evidence pipeline", Attest `messaging`), the verdict reads
`effect_below_trust:messaging.customer_notified`.

### 4. Read the verdict

```bash
curl -sS "$COMMITLAYER_API/v1/actions/cancel:sub_8Kq2/wait?timeout=30" \
  -H "X-API-Key: $RECORDER_KEY"
```

Holds for up to `timeout` seconds (60 at most), evaluates the evidence that has arrived on every poll, and returns
the verification with `timed_out`. This is the read to use after a push or a sync. The plain read answers at once
and evaluates nothing:

```bash
curl -sS "$COMMITLAYER_API/v1/actions/cancel:sub_8Kq2" -H "X-API-Key: $RECORDER_KEY"
```

`status` is `pending` while the window is open and an expected effect is still missing, and after it until Stripe
has synced past it; then it is `settled`, and `lenses.outcome.verdict` and `lenses.policy.verdict` read `PASS`, `FAIL` or `UNKNOWN`, each with
`reason_codes` such as `expected_effect_missing:stripe.subscription_canceled` or
`effect_attr_mismatch:stripe.subscription_canceled.cancel_at_period_end`. A pending view shows the provisional
verdict of the evidence so far.

The plain read returns the verdict as it was last stored: when the action was recorded, then by a wait that saw it
settle, by `POST /v1/actions/verify`, or by the re-check that runs when the window closes. Until one of those, its
`lenses` are the ones from the moment of recording, while `status`, `checks` and `summary` are rebuilt from the facts stored now, so the
headline can read PASS above lenses that still read UNKNOWN or FAIL. Read through the wait (`timeout=0` answers at
once) when you need the lenses to be current.

## Python SDK: record the action around the tool call, push facts from the systems that hold them

```bash
pip install commitlayer
```

Everything below works with the published package (`commitlayer` 0.1.1 on PyPI): `Client`, `record_action`,
`push_facts`, `get_action`, `wait_for_settlement` and `request`.

```python
import os

from commitlayer import Client

cl = Client(api_key=os.environ["COMMITLAYER_RECORDER_KEY"])  # a key with the recorder preset

invoice_id = "in_1PxYz"        # the Stripe invoice the agent is about to credit
customer_id = "cus_Nf1"
ticket_id = "4411"

# The contract versions the install pinned, per tool.
mapping = cl.request("GET", "/v1/packs/stripe_customer_operations/recorder-mapping")

# Before the agent's tool call: say what was approved.
cl.record_action(
    "scop_issue_credit_note",
    invoice_id,                            # the subject: the Stripe invoice id, as the tool call names it
    action_id=f"credit:{invoice_id}",
    contract_version=mapping["tools"]["stripe.credit_notes_create"]["contract_version"],
    subject_kind="invoice",
    params={
        "amount": 30.0,                    # major units; Stripe's own call takes 3000
        "currency": "usd",
        "invoice_id": invoice_id,
        "customer_reference": customer_id,
        "support_case_id": f"zendesk_ticket_{ticket_id}",
        "reason": "order_change",
    },
)
```

Record before the tool runs: an effect counts only at or after the action's `requested_at`, which is the
moment of this call unless you pass `requested_at`. `amount` is required: the limit and the comparison with Stripe's credit note read it, and an action without it is
UNKNOWN on the policy lens (`param_missing:amount`) where it would have passed. The tool's response is context,
not evidence: the credit note is read from Stripe by the connector. What only your systems know is pushed by
them, with a separate evidence key:

```python
import os
from datetime import datetime, timezone

from commitlayer import Client

evidence = Client(api_key=os.environ["COMMITLAYER_EVIDENCE_KEY"])  # evidence preset, bound to `messaging`

invoice_id = "in_1PxYz"
ticket_id = "4411"
sent_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")

evidence.push_facts(
    [
        {
            "source": "messaging",
            "subject_id": invoice_id,
            "subject_kind": "invoice",
            "fact_type": "customer_notified",
            "occurred_at": sent_at,
            "attributes": {"channel": "email"},
        }
    ],
    links=[
        {
            "subject_id": invoice_id,
            "source": "stripe",
            "linked_subject_id": f"zendesk_ticket_{ticket_id}",
            "linked_source": "zendesk",
            "link_type": "ticket_to_invoice",
        }
    ],
)
```

Later, from anywhere:

```python
import os

from commitlayer import Client

# The API holds a wait for up to 60 seconds; the client's own HTTP timeout (20 by default) has to be longer.
cl = Client(api_key=os.environ["COMMITLAYER_RECORDER_KEY"], timeout=70)
v = cl.wait_for_settlement("credit:in_1PxYz", timeout=120)   # cl.get_action(...) returns the stored verdict, unevaluated
print(v["status"], v["lenses"]["outcome"]["verdict"], v["lenses"]["policy"]["reason_codes"])
```

While the action is pending the wait returns after its `timeout` with `status: pending` and the provisional
verdict; it does not raise. The client is built with `timeout=70` because `commitlayer` 0.1.1 gives every HTTP
call 20 seconds by default and the API holds a wait for up to 60, so the default ends the first call of a wait on
a pending action with `TimeoutError`.

The `cl.packs` helpers (`list`, `get`, `configure`, `dry_run`, `install`, `coverage`, `recorder_mapping`) are in
the client repository from `commitlayer` 0.1.3, which is not on PyPI yet; with 0.1.1 call the same routes through
`cl.request("GET", "/v1/packs/...")` as above. They never activate a contract.

## TypeScript SDK: record the action around the tool call, push facts from the systems that hold them

```bash
npm install commitlayer
```

Everything below works with the published package (`commitlayer` 0.1.2 on npm): `Client`, `recordAction`,
`pushFacts`, `getAction`, `waitForSettlement` and `request`.

```ts
import { Client } from "commitlayer";

const cl = new Client({ apiKey: process.env.COMMITLAYER_RECORDER_KEY! }); // a key with the recorder preset

const subscriptionId = "sub_3Jm7"; // the Stripe subscription the agent is about to cancel
const customerId = "cus_Nf1";
const ticketId = "4411";

// The contract versions the install pinned, per tool.
const mapping = (await cl.request("GET", "/v1/packs/stripe_customer_operations/recorder-mapping")) as {
  tools: Record<string, { contract_version?: number }>;
};

// Before the agent's tool call: say what was approved.
await cl.recordAction("scop_cancel_subscription", subscriptionId, {
  actionId: `cancel:${subscriptionId}`,
  contractVersion: mapping.tools["stripe.subscriptions_cancel"].contract_version,
  subjectKind: "subscription",
  params: {
    subscription_id: subscriptionId,
    customer_reference: customerId,
    cancel_at_period_end: true, // required: the contract compares it with what Stripe shows
    support_case_id: `zendesk_ticket_${ticketId}`,
    reason: "customer_request",
  },
});
```

Record before the tool runs: an effect counts only at or after the action's `requestedAt`, which is the moment
of this call unless you pass it. The tool's response is context, not evidence: the cancellation is read from
Stripe by the connector. What only
your systems know is pushed by them, with a separate evidence key:

```ts
import { Client } from "commitlayer";

const evidence = new Client({ apiKey: process.env.COMMITLAYER_EVIDENCE_KEY! }); // evidence preset, bound to `messaging`

const subscriptionId = "sub_3Jm7";
const ticketId = "4411";

await evidence.pushFacts(
  [
    {
      source: "messaging",
      subject_id: subscriptionId,
      subject_kind: "subscription",
      fact_type: "customer_notified",
      occurred_at: new Date().toISOString(),
      attributes: { channel: "email" },
    },
  ],
  {
    links: [
      {
        subject_id: subscriptionId,
        source: "stripe",
        linked_subject_id: `zendesk_ticket_${ticketId}`,
        linked_source: "zendesk",
        link_type: "ticket_to_subscription",
      },
    ],
  },
);
```

Later, from anywhere:

```ts
import { Client } from "commitlayer";

// The API holds a wait for up to 60 seconds; the client's own HTTP timeout (20 by default) has to be longer.
const cl = new Client({ apiKey: process.env.COMMITLAYER_RECORDER_KEY!, timeoutMs: 70_000 });
const v = (await cl.waitForSettlement("cancel:sub_3Jm7", { timeoutMs: 120_000 })) as {
  status: string;
  lenses: { outcome: { verdict: string }; policy: { verdict: string; reason_codes: string[] } };
};
console.log(v.status, v.lenses.outcome.verdict, v.lenses.policy.reason_codes);
```

`cl.getAction(ref)` returns the verdict as last stored, without evaluating what has arrived since; wait for the
current one. While the action is pending the wait resolves after its `timeoutMs` with `status: pending` and the
provisional verdict; it does not throw. The client is built with `timeoutMs: 70_000` because `commitlayer` 0.1.2
gives every HTTP call 20 seconds by default and the API holds a wait for up to 60, so the default aborts the
first call of a wait on a pending action.

The `cl.packs` helpers (`list`, `get`,
`configure`, `dryRun`, `install`, `coverage`, `recorderMapping`) are in the client repository from `commitlayer`
0.1.4, which is not on npm yet; with 0.1.2 call the same routes through `cl.request("GET", "/v1/packs/...")` as
above. They never activate a contract.

## MCP: record from the tool call itself

With the MCP recorder in front of the agent's tool server, no code records the action: the mapped tool call does. The
command line, the mapping, what to change in it and its limits are on the [recorder and OpenTelemetry
setup](/docs/packs/stripe-customer-operations/recorder-and-opentelemetry) page.
