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

# Agent Tools & Security

> Reference for Commerce Engine WebMCP tools, capability gating, cart semantics, session behavior, diagnostics, custom modules, and safety boundaries.

`@commercengine/ai` is designed around explicit capabilities and a narrow commerce safety boundary. The agent gets structured tools instead of DOM access, and each tool exposes only the data needed for that operation.

## WebMCP status

WebMCP is an evolving browser capability. Commerce Engine prefers `document.modelContext` and retains compatibility where browser implementations differ.

In unsupported browsers:

```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
const registration = await registerCommerceWebMcp(config);
// null
```

That is an ordinary capability outcome. The storefront continues to function without agent tools.

Development environments should always enable diagnostics so unsupported capability can be distinguished from registration code that never mounted.

## Default tool inventory

### Catalog

| Tool              | Read-only | Purpose                                |
| ----------------- | --------- | -------------------------------------- |
| `search_products` | yes       | search the Commerce Engine catalog     |
| `get_product`     | yes       | retrieve authoritative product details |
| `browse_store`    | yes       | browse categories and products         |
| `get_variant`     | yes       | inspect a specific product variant     |

### Session and cart

These are included when the storefront exposes a browser session client. Registration can happen before that session is bootstrapped; calls return a retryable not-ready failure until the session is usable.

| Tool                     | Read-only | Purpose                                                                                  |
| ------------------------ | --------- | ---------------------------------------------------------------------------------------- |
| `get_session_state`      | yes       | report anonymous/logged-in state and available UI capabilities without exposing identity |
| `get_cart`               | yes       | return a safe cart projection                                                            |
| `add_to_cart`            | no        | add one or more product/variant quantities                                               |
| `set_cart_item_quantity` | no        | set the paid quantity on an existing line                                                |
| `remove_from_cart`       | no        | explicitly remove a removable cart line                                                  |

### Navigation / UI bridges

| Tool                            | Requires                             | Purpose                                      |
| ------------------------------- | ------------------------------------ | -------------------------------------------- |
| `open_product`                  | `navigation`                         | open the resolved product URL                |
| `manage_orders`                 | `navigation.ordersUrl`               | open the application's order-history route   |
| `open_cart`                     | checkout bridge                      | open existing cart UI                        |
| `open_checkout`                 | checkout bridge                      | hand control to the shopper's checkout UI    |
| `open_login`                    | checkout bridge exposing `openLogin` | open login UI; does not accept credentials   |
| `search_shop_policies_and_faqs` | `shopContent`                        | search a merchant-provided policy/FAQ source |

## No autonomous purchase completion

Commerce Engine deliberately does **not** provide tools for:

* entering passwords or OTPs
* selecting saved payment instruments
* typing card/bank details
* entering addresses on behalf of the user
* placing an order
* confirming payment

An agent may prepare the cart and open checkout. The shopper completes the transaction in the normal checkout experience.

## Safe cart projection

`get_cart` and mutation results return an allow-listed representation. That boundary matters because the canonical Commerce Engine cart can evolve over time; new API fields must not silently become agent-visible.

The agent-facing projection includes commerce fields such as:

* cart ID
* line ID
* product/variant identifiers
* names/SKUs necessary to identify the line
* paid quantity, free quantity, total quantity
* pricing/currency/totals
* availability and order-quantity constraints
* whether a line is removable

It excludes tokens, customer identity, addresses, payment state, and arbitrary metadata unless a future package version explicitly adds a reviewed field.

## Cart mutation rules

### `add_to_cart`

Adds to the existing paid quantity. It can accept a small batch of items in one invocation.

For an existing cart, additions are applied sequentially. If a later line fails, the tool reports the lines already applied rather than pretending the whole request was atomic.

### `set_cart_item_quantity`

Sets an absolute paid quantity for one existing line.

* positive values must satisfy `minOrderQuantity`, `maxOrderQuantity`, and `incrementalQuantity`
* `0` means removal only when the line is removable
* malformed values such as `null`, `false`, empty strings, or fractional numbers are rejected rather than coerced into a removal signal

### Promotional/free quantities

A free promotion line or free units attached to a paid line cannot be treated as shopper-selected quantity.

```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
quantity       paid units controlled by cart tools
freeQuantity   promotion-granted units
 totalQuantity  quantity + freeQuantity
removable      false for a completely promotional line
```

The model matches Hosted Checkout behavior so an agent cannot remove a line the shopper could not remove manually.

## Cancellation and confirmed mutations

Tool execution may receive an `AbortSignal`. The package checks cancellation around asynchronous work, but the Commerce Engine SDK does not currently abort an already-started network request.

Therefore cancellation is **not rollback**.

If the server has already applied a mutation and returned the resulting cart, the tool returns that confirmed state even if cancellation arrived around the same time. This prevents an agent from retrying an already-applied add and duplicating quantity.

## Anonymous sessions

Anonymous shoppers have real Commerce Engine sessions. Cart tools do not require sign-in.

The same browser session can evolve from anonymous to authenticated, preserving the guest cart. This is not a cross-device cart-merge guarantee.

`get_session_state` reports status, not identity:

```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  ok: true,
  data: {
    anonymous: true,
    loggedIn: false,
    loginAvailable: true
  }
}
```

## Route trust

Public route shapes should be shared with `@commercengine/seo`:

```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
const { site, routes } = commerceSeo;

await registerCommerceWebMcp({
  storefront,
  siteUrl: site.url,
  routes,
});
```

Forward resolvers turn CE entities into public URLs. Inverse resolvers map CMS-owned public slugs back to CE product/category identifiers before catalog tools query Commerce Engine.

### External navigation

Navigation is same-origin unless an origin is explicitly allowed:

```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
navigation: {
  navigate,
  allowedExternalOrigins: ["https://support.acme.example"]
}
```

Do not derive this allow-list from catalog or CMS content.

## Untrusted merchant content

Catalog text and policy/FAQ results are data, not instructions. Commerce Engine marks appropriate tool results as untrusted content and keeps tool descriptions/schema package-authored.

This prevents a malicious product description from redefining what a tool does.

## Input constraints

Tool schemas use narrow types, bounded free-form strings, and `additionalProperties: false` where appropriate. Runtime validation is still defensive; safety does not depend on the calling model obeying JSON Schema perfectly.

## Diagnostics

Configure diagnostics during integration:

```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
await registerCommerceWebMcp({
  storefront,
  diagnostics: (event) => {
    console.info("[commerce-ai]", event.phase, event.code, event.message ?? "");
  },
});
```

Useful diagnostic phases include capability detection, registration, rollback, and unregistering.

A particularly useful distinction:

* diagnostic says **unsupported** → mount code ran; browser lacks WebMCP
* diagnostic says **registered** → package reached `modelContext.registerTool`
* no diagnostic at all → your registration block likely never executed

The starter repository enables development diagnostics in all supported framework integrations for this reason.

## Test the tool set without WebMCP

`createCommerceAiTools()` is DOM-free:

```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { createCommerceAiTools } from "@commercengine/ai";

const tools = createCommerceAiTools({
  storefront,
  siteUrl: site.url,
  routes,
});

expect(tools.map((tool) => tool.name)).toContain("search_products");
```

Use this for unit tests, introspection, and custom module composition.

## Extend the module set

Commerce AI tools are built from plain modules.

```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
const tools = createCommerceAiTools({
  storefront,
  extraModules: [myStoreLocatorModule],
});
```

Use `extraModules` to append merchant-specific tools. Use `modules` only when you intentionally want to replace the default module list.

A duplicate tool name is a composition error and should fail early rather than allow two implementations to compete.

## Policy/FAQ bridge

Merchant editorial content is intentionally an extension point rather than a CMS-specific dependency:

```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
shopContent: {
  searchPoliciesAndFaqs: async (query, signal) => {
    return cms.searchHelpContent(query, { signal });
  },
}
```

Return compact, authoritative results rather than dumping entire CMS documents into the agent context.

## Recommended review checklist

Before enabling agent tools in production:

* tools are registered only once per live browser document/runtime
* registration is aborted on component/runtime teardown
* diagnostics are visible in development
* public routes resolve to the same URLs as SEO
* external navigation allow-list is explicit
* no custom tool exposes tokens, addresses, raw customer objects, or payment data
* cart tools return the resulting cart after mutations
* checkout completion remains human-controlled
* custom CMS output is treated as untrusted content

<CardGroup cols={2}>
  <Card title="AI package" icon="wand-magic-sparkles" href="/docs/seo-ai/ai">
    Setup and common integration patterns.
  </Card>

  <Card title="Agent Skills" icon="robot" href="/docs/seo-ai/agent-skills">
    Teach coding agents the same contracts.
  </Card>
</CardGroup>
