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

# Your First Operation

> Create an order and inventory fixture, answer an operational question, and give an AI agent the same database with a verifiable result.

**First task: inspect an order and decide whether stock can cover another request.** You will
create ten mugs in inventory, reserve two for an order, and check whether a new request for
nine mugs can be filled. Run the checks yourself, then let an AI agent inspect the same records.

This walkthrough uses **`@stateset/embedded` 1.35.1** locally. You need Node.js **20.20.0+** and
npm **10+**. You do not need a hosted StateSet key. The optional agent step needs an MCP-capable
host with its own model connection.

<Note>
  This is a local practice workflow. It creates commerce records and reserves stock in your
  database. It does not connect a store, charge a card, or ship goods. If your first task is
  customer support, use the [ResponseCX quickstart](/quickstart); for existing business systems,
  start with the [service directory](/api-reference/introduction).
</Note>

## 1. Create a project

Use a new directory so the fixture is separate from existing commerce data:

```bash theme={null}
mkdir stateset-first-operation
cd stateset-first-operation
npm init -y
npm install @stateset/embedded@1.35.1
```

If the native module cannot load, use the [SDK installation checks](/guides/sdk-installation).

## 2. Create the operational fixture

Save this as `setup-operation.mjs`:

```javascript theme={null}
import assert from 'node:assert/strict';
import { existsSync, writeFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { Commerce } from '@stateset/embedded';

const database = resolve('operations.db');
if (existsSync(database)) {
  throw new Error('operations.db already exists. Run inspect-operation.mjs, or use a new directory.');
}
const commerce = new Commerce(database);
const customer = await commerce.customers.create({
  email: 'ada@example.com', firstName: 'Ada', lastName: 'Lovelace',
});
const sku = 'MUG-001';
await commerce.inventory.createItem({ sku, name: 'Ceramic mug', initialQuantity: 10 });
const order = await commerce.orders.createExact({
  customerId: customer.id,
  currency: 'USD',
  stockPolicy: 'reject_if_insufficient',
  items: [{ sku, name: 'Ceramic mug', quantity: 2, unitPrice: '12.50' }],
});
assert.equal(order.status, 'pending');
assert.equal(order.totalAmountExact, '25.00');
const stock = await commerce.inventory.getStock(sku);
assert.equal(stock.totalAllocated, '2');
assert.equal(stock.totalAvailable, '8');

writeFileSync('operation.json', JSON.stringify({ database, orderId: order.id, sku }, null, 2));
const mcpConfig = {
  mcpServers: {
    'stateset-commerce': {
      command: 'npx',
      args: ['-y', '-p', '@stateset/cli@1.35.1', 'stateset-mcp',
        '--db', database, '--profile', 'core'],
    },
  },
};
writeFileSync('mcp-config.json', JSON.stringify(mcpConfig, null, 2));
const prompt = `Use the stateset-commerce read tools to inspect order ${order.id}
and inventory for SKU ${sku}. Report the order ID, status, total and currency;
stock on hand, allocated and available; and whether the available stock can cover
an additional request for 9 mugs right now. Identify the tool results behind your
answer. Do not create, reserve, update, cancel, charge, ship, or send anything.
If the records or tools are unavailable, report the blocker instead of guessing.`;
writeFileSync('agent-task.txt', prompt + '\n');
console.log(`Created order: ${order.id}`);
console.log(`Database: ${database}`);
console.log('Saved operation.json, mcp-config.json, and agent-task.txt');
```

```bash theme={null}
node setup-operation.mjs
```

**Success:** the program prints a real order ID and database path and saves the three handoff
files. It refuses to seed an existing `operations.db`, so an accidental second run does not
create another order. If setup fails partway through, keep the failure for diagnosis and start
again in a new directory rather than assuming the partial fixture is complete.

## 3. Verify the result independently

Save this as `inspect-operation.mjs`:

```javascript theme={null}
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { Commerce } from '@stateset/embedded';

const fixture = JSON.parse(readFileSync('operation.json', 'utf8'));
const commerce = new Commerce(fixture.database);
const order = await commerce.orders.get(fixture.orderId);
const stock = await commerce.inventory.getStock(fixture.sku);
assert.ok(order, 'Order is missing from the selected database');
assert.ok(stock, 'Inventory item is missing from the selected database');
assert.equal(order.status, 'pending');
assert.equal(order.totalAmountExact, '25.00');
assert.equal(order.currency, 'USD');
assert.deepEqual(
  [stock.totalOnHand, stock.totalAllocated, stock.totalAvailable],
  ['10', '2', '8'],
);
assert.equal(await commerce.orders.count(), 1);
console.log(`Order: ${order.id}`);
console.log('Status: pending; total: 25.00 USD');
console.log('Stock: on hand=10, allocated=2, available=8');
console.log('Additional request for 9: insufficient available stock');
```

```bash theme={null}
node inspect-operation.mjs
```

**Success:** the assertions pass and the printed order ID matches setup. This is a second
process reading the saved database, so the result does not depend on the setup program staying
open. You have completed the first operational check without an AI agent.

The stock conclusion is a snapshot. A real order must check and reserve stock when it is
created; a previous read is not a guarantee of availability. The
[orders quickstart](/guides/orders-quickstart) tests that rejection path.

## 4. Give an AI agent the same task

Open the generated `mcp-config.json`. Copy its `stateset-commerce` entry into your MCP host's
configuration, following that host's configuration format. Merge it with any existing servers.
The file already contains the absolute database path, so there is no example path to replace.

Restart or reconnect the server in the host, then paste the contents of `agent-task.txt` into
the conversation. The task includes the exact order ID created on your machine; you do not need
to give the agent filesystem access to read the handoff files.

The configuration selects the `core` profile and omits `--apply`. In CLI 1.35.1, write calls
remain preview-only; read tools can inspect the database. The
[MCP setup guide](/stateset-icommerce/stateset-icommerce-mcp) explains host executable paths,
profiles, and the separate trusted configuration required to enable writes.

## 5. Check the agent's evidence

| Observation            | Expected result                                        |
| ---------------------- | ------------------------------------------------------ |
| Tool activity          | The host shows actual order and inventory reads        |
| Order identity         | The same ID saved in `operation.json`                  |
| Order state and amount | `pending`, `25.00 USD`                                 |
| Stock quantities       | 10 on hand, 2 allocated, 8 available                   |
| New nine-unit request  | Insufficient available stock; no reservation attempted |
| Side effects           | No business write performed                            |

Run `node inspect-operation.mjs` again after the agent responds. Its assertions confirm that
the fixture's order count, order state, total, and stock quantities still match. They do not
audit every possible record or external system; inspect the host's tool trace as well.

A plausible answer without tool calls is not a successful connection test. An empty result is
not an invitation to create replacement data: compare the configured database path and order
ID first.

## Move from the example to your operation

Use [Connect Your Operation](/guides/connect-your-operation) to choose data owners, check
service access, and map real IDs before replacing this fixture with business data.

Choose one next outcome and the system that owns its data:

| Your next outcome                      | Continue here                                             | Verify before calling it complete                                                    |
| -------------------------------------- | --------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| Create or cancel an order              | [Orders](/guides/orders-quickstart)                       | Order state and stock allocation                                                     |
| Create a purchase order                | [Supplier and purchasing](/guides/supplier-quickstart)    | Approval transitions and separately verified supplier delivery                       |
| Record production progress             | [Manufacturing](/guides/manufacturing-quickstart)         | BOM components, batch quantities, and independent inventory verification             |
| Review a warranty claim                | [Warranty claims](/guides/warranties-quickstart)          | Coverage dates, claim decisions, and separate replacement fulfillment                |
| Track an outbound shipment             | [Fulfillment and shipping](/guides/commerce/fulfillment)  | Shipment state, application policy, and separately verified order and stock outcomes |
| Record an inbound delivery             | [Warehouse receiving](/guides/warehouse-quickstart)       | Received quantities, discrepancy handling, and separately verified inventory         |
| Receive and evaluate a return          | [Returns](/guides/returns-quickstart)                     | Return state, dispositions, and binding limitations                                  |
| Record a payment or refund             | [Payments](/guides/payments-quickstart)                   | Local record state and the separate provider result                                  |
| Answer customer questions              | [ResponseCX](/quickstart)                                 | Saved agent configuration, then the connected channel's behavior                     |
| Keep Shopify and NetSuite aligned      | [Sync](/guides/sync-shopify-to-netsuite)                  | Configured connectors, job result, and destination records                           |
| Run a multi-step operation durably     | [Temporal](/guides/temporal-first-durable-workflow)       | Workflow state and resulting records                                                 |
| Apply business policy before an action | [Verified decisions](/guides/nsr-first-verified-decision) | Decision and proof, followed separately by execution evidence                        |

For an existing business, identify the source of truth and how data reaches the selected
service before replacing fixture IDs with real ones. StateSet services have separate setup and
credentials; connecting one MCP server does not configure the others.

Use the [agent operating procedure](/getting-started-for-ai-agents) for task handoffs and the
[integration test plan](/guides/comprehensive-testing-guide) to verify the workflow as you expand it.

## Get unblocked

| Symptom                                | Next step                                                               |
| -------------------------------------- | ----------------------------------------------------------------------- |
| Setup says the database exists         | Use the inspection program, or start a new fixture in a new directory   |
| `operation.json` is missing            | Run setup successfully, then inspect from the same project directory    |
| The MCP host cannot launch `npx`       | Check the host's Node/npm environment and executable path               |
| The agent cannot find the order        | Compare the absolute database path and the exact ID in `agent-task.txt` |
| A requested tool is missing            | Inspect the server's available tool schemas and selected profile        |
| The agent returns a write preview      | No write was applied; this starter task calls only for reads            |
| Inspection fails after experimentation | The fixture changed; inspect the failed assertion and tool trace        |

Share the package version, failed step, and redacted error using the [support checklist](/support#report-an-api-problem).
