> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agentcard.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Agentcard is for companies whose agent buys for their users. Pick one path: the opencommerce SDK (@agent-cards/commerce-sdk) gives your agent one buy tool that finds the product, builds the cart, gets the user's approval and places the order at real stores; the Agentcard SDK (@agent-cards/sdk) pays with the user's own card when your agent already shops in a browser (Browser Use, Kernel, Browserbase, Anchor or Notte); the Purchase API (POST /buy) does the same purchase flow over plain HTTP in any language; Issuing gives the agent its own card.
> Start with `npx agent-cards init` in the app's folder (Node 22 or later). No invite is needed: it creates your Agentcard account if you don't have one, installs the opencommerce SDK and puts the credentials in the env file, kept out of git. From a coding agent, run `npx agent-cards init --print --categories all --implementation tool --wallet vault --skip-install` to get the setup steps to apply yourself.
> Vault is by invitation: request it at https://agentcard.com/get-started?utm_source=docs&utm_medium=llms&utm_campaign=agent-instructions. opencommerce needs no invite.
> Never ask a user for a card number, expiry date or CVV in chat. Send them the Vault link; they add their card on Agentcard's page, and the agent never sees the number.
> Every purchase is approved by the user, with a passkey or Face ID, or by an auto-approval they granted. An approval covers one merchant and one exact total. If the total changes, ask again. When a result says the user already said yes, don't ask again.
> `init` writes PRODUCTION credentials, which place real orders, so test in sandbox first. For opencommerce, run `npx agent-cards credentials --mode sandbox` and put the two lines it prints in place of the production ones in the env file `init` wrote, because that command only prints them; sandbox then runs the whole flow against real stores and stops before payment, so no order is placed and nobody is charged. For Vault and Issuing, sandbox credentials issue test cards that no real merchant accepts; try the checkout against shop.agentcard.sh, a test store on Stripe test mode.
> Tell the user an order is placed only after Agentcard reports it placed.
> Vault is free up to 5,000 users (https://agentcard.com/pricing). opencommerce takes 1% of each completed order. Full docs in one file: https://docs.agentcard.com/llms-full.txt

# Answer each shopper message

> Send each shopper message on its own, so a second message never mixes its products and replies with the first.

A shopper can send a second message before the first is answered. Send each message to Agentcard on its own, the moment it arrives, and show each answer beside the message it answers. Each message then keeps its own products, its own cart and its own reply, and the shopper never sees the first message's products beside the second message's reply.

## Send one call per message

Send the shopper's words as they wrote them, one message per call. Two messages joined into one call read as one request, and the shopper gets one answer for both.

A conversation is one purchase. Every answer names its conversation, and every message about the same purchase goes back to it. The answer's reply, its products, its cart and any link it carries, such as the page where the shopper approves the payment, belong to the message you sent. Show them under that message, never under a later one.

> [tab] SDK
>
> Build the buy tool once for each shopper, and open a turn from it for each message with `buy.turn`. A turn is the tool for one message: it has the same name, schema and methods, so give it to your model in place of the tool.
>
> ```ts chat.ts theme={null}
> const buy = buyTool({ agentcard, externalUserId: shopper.id }); // one for each shopper, kept
> let runs: Promise<unknown> = Promise.resolve(); // this shopper's model runs, one after another
>
> async function onShopperMessage(message: string) {
>   const turn = buy.turn(message, { onReaction: (emoji) => reactToShopperMessage(shopper.id, emoji) }); // your code
>   const run = runs.then(async () => {
>     const runner = new Anthropic().beta.messages.toolRunner({
>       model: 'claude-opus-5-5',
>       max_tokens: 16000,
>       tools: [turn],
>       messages: turn.messages(history), // read inside the run, so it holds the run before it
>     });
>     const answer = await runner;
>     history = runner.params.messages;
>     return answer;
>   });
>   runs = run.catch(() => {}); // a run that throws never holds up the next one
>   const answer = await run;
>   return { answer, links: turn.links, carts: turn.results.at(-1)?.carts ?? [] };
> }
> ```
>
> `history` stands for the shopper's earlier messages. `turn.messages(history)` is the history, then what Agentcard told the shopper that the history does not hold yet, then the message. The turn opens the moment the message arrives, while the model runs go one after another, so a second message never writes the first one's exchange out of the history.
>
> Every call the model makes through the turn belongs to that message alone:
>
> * `turn.links` holds each link the turn's calls handed over, in order. Send them with the reply, or pass `sendLink` to `buy.turn` to send each one the moment the tool hands it over.
> * `turn.results` holds the whole answer of each call, and an `onResult` passed to `buy.turn` hears each one.
> * An `onProgress` passed to `buy.turn` hears only that turn's stages.
> * `turn.agentcardMessages` holds each message Agentcard posted into this shopper's chat that the model has not read yet.
>
> A callback you leave out of `buy.turn` falls back to the one the tool was built with. Pass the turn to every framework the way you pass `buy`: `tools: [turn]` for Anthropic, `tools: { buy: turn }` for the Vercel AI SDK, `tools: [turn.openai]` with `turn.handle` for OpenAI and OpenRouter chat, and `toOpenRouterTool(turn, { tool, z })` for OpenRouter's agent SDK.
>
> The turns share the shopper's conversation, so a card the shopper already holds from an earlier turn is not sent again. A tool built for every message buys the same way, but it sends the same product links again each time Agentcard shows the same products.

> [tab] MCP
>
> Call [`buy`](https://docs.agentcard.com/commerce-mcp/tools/buy) once for each message, with the shopper's words in `ask`. Every call carries the same `shopper_id` and `thread_id`, set on your server as [Set the shopper and chat ids](https://docs.agentcard.com/commerce-mcp/index.md#set-the-shopper-and-chat-ids) shows.
>
> ```json theme={null}
> {
>   "tool": "buy",
>   "arguments": {
>     "shopper_id": "user-42",
>     "thread_id": "dm-user-42",
>     "ask": "a stainless steel french press from target",
>     "confirm": false,
>     "new_order": false,
>     "product_id": null,
>     "store_id": null
>   }
> }
> ```
>
> One `buy` call runs at a time for each shopper and chat. A second call while the first runs returns this error, and nothing is sent:
>
> ```json theme={null}
> { "error": { "code": "busy", "message": "...", "retryable": false } }
> ```
>
> Wait for the first call's result, read [`get_conversation`](https://docs.agentcard.com/commerce-mcp/tools/get_conversation), then send the newer message.

> [tab] API
>
> Send the shopper's words as `ask`, with the `conversation_id` the last answer gave you:
>
> ```bash theme={null}
> curl https://api.agentcard.sh/buy \
>   -H "Authorization: Bearer $AGENTCARD_TOKEN" \
>   -H "Content-Type: application/json" \
>   -d '{
>     "conversation_id": "conv_b7d9af02bf8b117109c33de5",
>     "external_user_id": "user-42",
>     "ask": "a stainless steel french press from target"
>   }'
> ```
>
> The answer's `reply`, its products in `catalog`, its `cart` and any link such as `approval_url` belong to this message.

## Keep one purchase per chat

A shopper who writes to your app in several chats, such as a private chat and a group, keeps a purchase in each. Send your own id for the chat on every call. Agentcard keeps one open purchase for each shopper and chat, so two chats never share a cart, a question or an approval.

> [tab] SDK
>
> Build one tool for each shopper and chat, with the chat's id:
>
> ```ts chat.ts theme={null}
> const buy = buyTool({ agentcard, externalUserId: shopper.id, threadId: chat.id });
> ```
>
> Leave `threadId` out for an app with one chat per shopper.

> [tab] MCP
>
> `thread_id` is required on every `buy` call. Fill it in on your server, not in the model: a model that changes `thread_id` partway through a chat splits a purchase in two.

> [tab] API
>
> Send `thread_id`, with `resume: true` in place of `conversation_id`:
>
> ```bash theme={null}
> curl https://api.agentcard.sh/buy \
>   -H "Authorization: Bearer $AGENTCARD_TOKEN" \
>   -H "Content-Type: application/json" \
>   -d '{
>     "thread_id": "dm-user-42",
>     "resume": true,
>     "external_user_id": "user-42",
>     "ask": "the gooseneck one"
>   }'
> ```
>
> Agentcard continues the shopper's open purchase in that chat, if a message reached it in the last 24 hours, and starts a new one when there is none. Your app then never has to store a `conversation_id`. Send `new_order: true` instead when the shopper drops what they were buying and starts over.
>
> A `conversation_id` sent with another chat's `thread_id` is refused, and nothing runs:
>
> ```text theme={null}
> 409
> {
>   "error": "This conversation belongs to another thread. Send the conversation_id that thread was answered with, or resume: true with this thread_id.",
>   "code": "thread_mismatch",
>   "conversation_id": "conv_b7d9af02bf8b117109c33de5"
> }
> ```
>
> Send the `conversation_id` that chat was answered with, or `resume: true` with the chat's `thread_id`.

## Send a newer message anytime

A shopper who changes their mind while Agentcard is still answering gets the answer to their newest message. Send the new message as soon as it arrives, in the same conversation. Agentcard stops working on the older message and answers the newer one. Products the older message already found stay in the conversation, so a later "the second one" still picks from them. When the shopper sends three messages quickly, the newest one answers and the two before it both stop.

A confirm, the call that pays for a cart, is never stopped. A message sent while a confirm runs waits for it.

> [tab] SDK
>
> `turn.stopped` reads `true` once a call of the turn was stopped by a newer message. Check it after each call: do not call your model again, show no error and save no history for that turn. The cards it already showed stay with the shopper.

> [tab] MCP
>
> The MCP server does not stop a running `buy` call for a newer message. The newer call returns `busy`, as [Send one call per message](#send-one-call-per-message) shows, so wait for the running call and send the newer message after it.

> [tab] API
>
> In this sandbox run, the shopper asked for a French press at Target, then 2.5 seconds later wrote "actually make it a pour over kettle instead". The sandbox is Agentcard's test mode, which charges nothing. The first call answered after 3.6 seconds with nothing to show:
>
> ```json theme={null}
> {
>   "status": "needs_input",
>   "conversation_id": "conv_b7d9af02bf8b117109c33de5",
>   "reply": "",
>   "messages": [],
>   "error_code": "turn_stopped",
>   "error": "A newer message from the shopper stopped this turn. The answer comes on that message's turn."
> }
> ```
>
> The second call answered with the kettles:
>
> ```json theme={null}
> {
>   "status": "needs_input",
>   "conversation_id": "conv_b7d9af02bf8b117109c33de5",
>   "reply": "Here are the pour over kettles I found at Target:\n\n1. Precision Pour Stainless Steel Electric Kettle, $89.99\n2. Coulee Coffee Co Pour Over Kettle, $74.99\n...\n\nWhich one would you like?",
>   "catalog": { "merchant_name": "Target", "items": [ ... ] }
> }
> ```
>
> Show nothing for an answer whose `error_code` is `turn_stopped`. A message that waits too long behind a running confirm is refused:
>
> ```text theme={null}
> 409
> {
>   "error": "A turn is already running on this conversation. Wait for it to finish (GET /buy/conversations/:id reports turn_in_progress), then send the next ask or confirm.",
>   "code": "turn_in_progress",
>   "conversation_id": "conv_b7d9af02bf8b117109c33de5"
> }
> ```
>
> Read the conversation until `turn_in_progress` reads `false`, then send the message again:
>
> ```bash theme={null}
> curl "https://api.agentcard.sh/buy/conversations/conv_b7d9af02bf8b117109c33de5?external_user_id=user-42" \
>   -H "Authorization: Bearer $AGENTCARD_TOKEN"
> ```
>
> ```json theme={null}
> {
>   "conversation_id": "conv_b7d9af02bf8b117109c33de5",
>   "status": "needs_input",
>   "turn_in_progress": false,
>   "cart_building": null,
>   ...
> }
> ```
>
> The same refusal names `cart_building` when a store's checkout is still building the cart from the message before. That cart arrives with its total in a message of its own, and the shopper's yes goes to that total.

## Let Agentcard answer shopping first

Send every shopper message to Agentcard before your own model, the AI that runs your chat, reads it. Agentcard answers four kinds of message itself: a request to buy or book, a pick of what it just showed (`the second one`, `1 and 3`), an answer to its question (an address, a size, a code), and a yes to a total. A shopper who types `Printer paper, one ream` reads Agentcard's list of printer paper with no call to your model.

Every other message comes back to you at once, with no search. `thanks!` came back in 0.28 seconds in a sandbox run. Hand it to your own model, which answers the shopper as it always did and can still shop through Agentcard.

> [tab] SDK
>
> Call `turn.handled()` once, and run your model only when it resolves `false`:
>
> ```ts chat.ts theme={null}
> const turn = buy.turn(message, {
>   onItem: (item) => (item.kind === 'text' ? sendText(shopper.id, item.text) : sendCard(shopper.id, item.link)), // your code
> });
> if (await turn.handled()) {
>   // Agentcard answered the shopper: keep the exchange, so your model reads it on the next message.
>   const said = turn.items.flatMap((item) => (item.kind === 'text' ? [item.text] : [])).join('\n\n');
>   history = [...turn.messages(history), { role: 'assistant', content: said }];
>   return;
> }
> // Your model answers, as before:
> const runner = new Anthropic().beta.messages.toolRunner({ model: 'claude-opus-5-5', max_tokens: 16000, tools: [turn], messages: turn.messages(history) });
> ```
>
> When Agentcard's reply only asks the shopper something, the turn sends it through `onItem`, after the cards and links, and `handled()` resolves `true`. An answer your model has to word, such as an order placed or a refusal, resolves `false`, and `turn.messages(history)` hands your model that answer beside the shopper's message. An app that never calls `handled()` works as before: nothing reaches Agentcard until your model calls the tool.

> [tab] MCP
>
> The `buy` tool always runs the message it gets, so your model decides which messages to send to it. There is no way to hand a message back.

> [tab] API
>
> Add `hand_back: true`, and fill `last_answer` from the last `POST /buy` answer so Agentcard can tell a pick or an answer from small talk:
>
> ```bash theme={null}
> curl https://api.agentcard.sh/buy \
>   -H "Authorization: Bearer $AGENTCARD_TOKEN" \
>   -H "Content-Type: application/json" \
>   -d '{
>     "thread_id": "dm-user-42",
>     "resume": true,
>     "external_user_id": "user-42",
>     "ask": "thanks!",
>     "hand_back": true,
>     "last_answer": { "answered": true, "asked": "Which one would you like?" }
>   }'
> ```
>
> ```json theme={null}
> { "status": "yours", "handed_back": true, "conversation_id": null, "reply": null, "messages": [] }
> ```
>
> `status: "yours"` means the message is yours to answer.
>
> | `last_answer` field | What to send |
> | - | - |
> | `answered` | `true` when that answer is the last thing the shopper read, with no reply from your own model since. |
> | `asked` | The question that answer's `reply` ended on, such as `Which one would you like?`. |
> | `next_action` | That answer's `next_action`, such as `confirm`. |
> | `products` | Each product it showed, as `{ "product_id": "...", "name": "..." }` from `catalog.items[]`. |
> | `stores` | Each store it showed, as `{ "store_id": "...", "name": "..." }` from `stores.items[]`. |
>
> A confirm, a `pick` and an ask sent without `hand_back` always get Agentcard's answer.

## Show the reply as written

Most answers only ask the shopper something: which product, which size, which store, or a yes to a total. Agentcard's reply already says that, so show it as written. A second call to your model that rewords it costs the shopper another wait and changes nothing.

Every list in the reply reads as lines that start with `• `, so the shopper sees choices as a list. A pick that asks which bread the shopper wants arrives like this:

```text theme={null}
before i add the Chicken Pesto Caprese, which bread do you want?

• Panini-pressed ciabatta, the chef's pick
• Sourdough
• Whole wheat
• Potato roll
• Gluten-free (+$2.46)
```

A link that finishes a step, such as the page to add a card, approve the payment or sign in to a store, goes out right after the message that asks the shopper to open it.

> [tab] SDK
>
> Pass `replyAsWritten: true`, to `buyTool` for every turn or to `buy.turn` for one. `turn.replyAsWritten` then holds Agentcard's reply, with every link taken out, whenever the turn's last answer only asks. Show it and end the turn without calling your model again:
>
> ```ts chat.ts theme={null}
> const turn = buy.turn(message, { replyAsWritten: true, onMessage: (text) => sendText(shopper.id, text) });
> const runner = new Anthropic().beta.messages.toolRunner({
>   model: 'claude-sonnet-5-5',
>   max_tokens: 16000,
>   tools: [turn],
>   messages: turn.messages(history),
>   stream: true,
> });
> let written: string | null = null;
> for await (const stream of runner) {
>   written = turn.replyAsWritten;
>   if (written !== null) {
>     stream.abort(); // the reply says it already: no second model call
>     break;
>   }
>   const paragraphs = turn.messageStream();
>   stream.on('text', (delta) => paragraphs.push(delta));
>   await stream.done();
>   await paragraphs.end();
> }
> if (written !== null) await turn.say(written);
> history = written !== null ? [...runner.params.messages, { role: 'assistant', content: written }] : runner.params.messages;
> ```
>
> Any other answer, such as an approval sent, an order placed, or a refusal, leaves `turn.replyAsWritten` null, and your model words it. The reply leaves out the products and stores whose cards the shopper holds, so the shopper never reads a card twice. An answer whose next step is a link reads as that step's fixed short line, such as `approve the payment to place your order (up to $19.02)`, as [Read the step lines](https://docs.agentcard.com/api-reference/commerce-sdk/buy-tool.md#read-the-step-lines) lists.
>
> Pass `textingStyle: true` beside `replyAsWritten: true` to also lowercase the start of each sentence and the word "I", and to drop markdown and spaced dashes. The bullets stay. [Show bullets and texting style](https://docs.agentcard.com/api-reference/commerce-sdk/buy-tool.md#show-bullets-and-texting-style) lists which lines count as a list.

> [tab] MCP
>
> The `buy` result carries `reply_as_written` when the reply only asks the shopper something. Show it as your whole answer. It reads `null` for any other answer, and your model words `reply` itself. Hand each link in `links` to the shopper verbatim, or say a link is waiting when your app shows links itself.

> [tab] API
>
> `reply` is written for the shopper, and `messages` holds the same words as the separate messages Agentcard wrote, in order. Show `messages` as they are. Send each link that finishes a step, such as `approval_url`, `add_card_url` or `store_login_url`, right after the message that asks for it.

## Show the answer as it arrives

A turn reaches the shopper as messages and links that interleave: a short line saying Agentcard is on it, the products a search found, then the words about them. Show each part below the one before it, in the order it arrives, and the shopper sees products long before the reply is finished.

> [tab] SDK
>
> Pass `onItem` to `buy.turn`, and the turn hands your app every part as one sequence, one item at a time:
>
> ```ts chat.ts theme={null}
> const turn = buy.turn(message, {
>   onItem: (item) => (item.kind === 'text' ? sendText(shopper.id, item.text) : sendCard(shopper.id, item.link)), // your code
>   onTyping: (typing) => showTyping(shopper.id, typing), // your code
> });
> const runner = new Anthropic().beta.messages.toolRunner({
>   model: 'claude-opus-5-5',
>   max_tokens: 16000,
>   tools: [turn],
>   messages: turn.messages(history),
>   stream: true,
> });
> for await (const stream of runner) {
>   const paragraphs = turn.messageStream();
>   stream.on('text', (delta) => paragraphs.push(delta));
>   await stream.done();
>   await paragraphs.end();
> }
> ```
>
> A `text` item is Agentcard's short line, or a message your model wrote through `turn.messageStream()` or `turn.say(text)`. A `link` item is each link the tool hands over, with the fields `sendLink` would get. `turn.items` holds every item that went out, in order.
>
> * Pass `pace: true` to space messages like someone texting: each waits 300 ms plus 12 ms a character, at most 1.5 seconds, after the item before it. Time your model spent writing counts toward the pause, and links never wait. `onTyping` hears `true` when a pause starts and `false` when its message goes out.
> * With `onItem`, the turn sends nothing to `sendLink` or `onWorking`. Passing `onItem` beside either to the same turn throws.
> * A step link, the `vault`, `approval` or `store_login` page, waits until your model's next message ends or `turn.say` is called, then goes out right after that message. A held link also goes out when the turn's next call starts, or after 20 seconds.
>
> Without `onItem`, pass `onMessage` beside `sendLink`. `toMessages(text)` cuts text at its blank lines into one message per paragraph, and keeps a list or a code block whole. `messageStream` does the same for a reply your model streams: push each piece, then call `end`. Start a new stream for each model message.

> [tab] MCP
>
> The `buy` tool answers once, with the whole result, within about 45 seconds. When `turn_continues` is `true`, Agentcard is still working: tell the shopper you're on it, and read [`get_conversation`](https://docs.agentcard.com/commerce-mcp/tools/get_conversation) or [`get_updates`](https://docs.agentcard.com/commerce-mcp/tools/get_updates) later. Never send the same `buy` again.

> [tab] API
>
> Add `?stream=1` for a streamed answer, which sends each part as soon as it is ready. The parts arrive as server-sent events, a standard format that browsers read with `EventSource`. Each event is an `event:` line naming it, a `data:` line carrying its JSON, and a blank line:
>
> ```text theme={null}
> event: ack
> data: {"text":"give me a sec, finding a men's linen shirt","conversation_id":"conv_143abb3d7b6735f1dabab870"}
> ```
>
> This sandbox run asked for "a men's linen shirt". Each event is shown on one line, with the milliseconds since the call started and its `data`:
>
> ```text theme={null}
> event: status      400 ms  {"conversation_id":"conv_143abb3d7b6735f1dabab870","step":"searching","text":"Searching stores…"}
> event: ack         991 ms  {"text":"give me a sec, finding a men's linen shirt","conversation_id":"conv_143abb3d7b6735f1dabab870"}
> event: catalog    2221 ms  {"conversation_id":"conv_143abb3d7b6735f1dabab870","catalog":{"merchant_name":"these stores","items":[ ... ]}}
> event: segment    5406 ms  {"text":"Here are a few men's linen shirts. The cards show each one.\n\n1. Linen Shirts For Men Short Sleeve Button Down, $21.99 at amazon.com ..."}
> event: envelope   5615 ms  {"http_status":200,"conversation_id":"conv_143abb3d7b6735f1dabab870","status":"needs_input","reply":"Here are a few men's linen shirts. ...", ... }
> ```
>
> | Event | What to do with it |
> | - | - |
> | `status` | Show the step as a passing line, such as "Searching stores…". |
> | `ack` | Show it as a message: a short line that says Agentcard is on it. |
> | `catalog` | Show the products as cards, before the reply is written. |
> | `segment` | Show it as one message of the reply. |
> | `envelope` | The whole answer, the same body a call without `?stream=1` returns. The stream ends after it. |
>
> Skip any event your app does not show, such as `group`, which this run also sent to group the cards. A stopped answer's stream ends with an `envelope` whose `error_code` is `turn_stopped`. A refusal that comes before Agentcard starts work, such as `thread_mismatch`, arrives as plain JSON with its HTTP status, not as a stream.

## Check it in the sandbox

1. As a test shopper, ask for "a stainless steel french press from target", and send "actually make it a pour over kettle instead" before the first answer arrives.
2. Check that the kettles answer the second message, and that the first shows nothing over the SDK and the API. Over MCP, the second call answers `busy` until the first returns.
3. Send "thanks!" through the SDK's `handled()` or the API's `hand_back: true`. Check that it comes back to your own model.
4. Ask for a sandwich and pick one that has a choice of bread. Check that the question arrives with each bread on its own line that starts with `• `.
5. Over the API, send the first chat's `conversation_id` with another chat's `thread_id`. Check that it is refused with `thread_mismatch`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.