# retailcrm-mcp [Health: Active]

**Category:** 👤 Customer Data Platforms  
**Repository:** https://github.com/theYahia/retailcrm-mcp  
**GitHub Stars:** 2  
**npm Downloads (last month):** 198  
**Views:** 3  
**Installs:** 0  
**Upvotes:** 0  
**Directory Page:** https://allmcps.com/mcp/retailcrm-mcp

## Description
MCP server for RetailCRM — orders, customers management via API v5.

## Tools
Capabilities this server exposes over MCP:

- **list_orders** — List orders with filters by status, customer name, number, and created-date range. Returns (summary): pagination + array of {id, number, status, total, customer, phone, itemCount, createdAt}. Use detail:'full' for line items/delivery/payments, raw:true for the untouched payload.
- **get_order** — Get a single order by RetailCRM id or externalId. Returns a shaped order; detail:'full' adds items, delivery, payments, comments.
- **create_order** — Create an order with line items and delivery. Link an existing customer via customer_id/customer_external_id, or pass first_name (+phone/email) to create one inline. Returns {success, id, order?}.
- **update_order** — Update an order (status, customer, delivery, comments). Only the fields you pass are sent. Returns {success}.
- **orders_history** — Order change history incl. status transitions; supports incremental sync via filter_since_id and a date window. Returns {history[], pagination}.
- **list_customers** — List/search customers by name, email, phone, created-date. Returns (summary): pagination + array of {id, name, email, phone, ordersCount, totalSpent}. detail:'full' adds address/externalId/all phones.
- **get_customer** — Get a single customer by id or externalId. Returns a shaped customer; detail:'full' adds address and contact details.
- **create_customer** — Create a customer with name, contacts, address, optional externalId. Returns {success, id}.
- **update_customer** — Edit an existing customer (name, email, phones, address) by id or externalId. Only the fields you pass are sent. Returns {success}.
- **merge_customers** — Merge duplicate customers into a target; merged records are DELETED. Returns {success}.
- **customers_history** — Customer field-change log for growth/churn signals and incremental sync. Returns {history[], pagination}.
- **list_products** — List catalog products with filters by name, active, group, price range. Returns pagination + array of {id, name, article, active, url, groups, offers}.
- **list_product_groups** — List product groups (category tree). Returns {productGroup[], pagination}.
- **store_inventories** — Stock levels (and cost prices) per offer/warehouse. Use details:true for the per-store breakdown. Returns {offers[], pagination}.
- **order_payment_create** — Record a payment against an order (amount, type, status, paid_at). Returns {success, id}.
- **order_payment_edit** — Edit an existing order payment (amount/status/paid_at). Returns {success}.
- **order_payment_delete** — Delete an order payment by id. Returns {success}.
- **customer_notes_list** — List free-text notes attached to customers. Returns {notes[], pagination}.
- **customer_notes_create** — Add a note to a customer (by id or externalId). Returns {success, id}.
- **customer_notes_delete** — Delete a customer note by id. Returns {success}.
- **tasks_list** — List follow-up tasks/reminders, filterable by status/performer/customer. Returns {tasks[], pagination}.
- **tasks_create** — Create a task (text, due datetime, performer, linked order/customer). Returns {success, id}.
- **tasks_edit** — Edit a task or mark it complete. Returns {success}.
- **list_segments** — List customer segments (RFM/marketing cohorts). Returns {segments[], pagination}.
- **list_costs** — List expense records (for margin/profit analytics) by date and cost group. Returns {costs[], pagination}.
- **create_cost** — Create an expense record, optionally attributed to an order. Returns {success, id}.
- **files_list** — List files attached to orders/customers. Returns {files[], pagination}.
- **files_get** — Get a file's metadata by id. Returns {file}.
- **files_upload** — Upload a file (UTF-8 text or base64 binary). Returns {success, file}.
- **list_statuses** — All order statuses (codes, names, groups, ordering). Call before filtering/updating orders by status.
- **list_delivery_types** — All delivery types with codes, names, default costs.
- **list_payment_types** — All payment types with codes and names.
- **list_stores** — All warehouses/stores (codes, names, types).
- **list_sites** — All sites/stores the API key can act on — use the returned code as the `site` param on multi-site create/edit.
- **list_countries** — Valid country ISO codes for addresses/delivery.
- **list_order_types** — All order types (codes/names) — valid values for create_order's order_type.
- **list_order_methods** — All order methods (acquisition channels).
- **get_orders_summary** — Period-scoped order summary: exact totalCount for the date range plus revenue, average order value, and status distribution aggregated over up to max_pages×100 orders (partial:true if the window exceeds that).
- **get_customers_summary** — Period-scoped new-customer count for a date range. Returns {period, newCustomers}.

## Claude Desktop Quick Installation
Install path detected from listing signals. Uses `npx` (confidence: high):

```json
"mcpServers": {
  "retailcrm-mcp": {
    "command": "npx",
    "args": ["-y","@theyahia/retailcrm-mcp"]
  }
}
```

## Documentation & README

# MCP-сервер для RetailCRM — заказы, клиенты и товары интернет-магазина через ИИ

Если вы искали, как подключить RetailCRM к нейросети, поднять заказ или карточку клиента и не собирать отчёты руками — это оно. 39 инструментов и 2 навыка поверх API v5: заказы, клиенты, товары, складские остатки, оплаты, задачи, справочники и аналитика. Спрашиваете «что с заказом 12345» — получаете статус, состав и оплату одним ответом.

> Промышленный MCP-сервер для e-commerce CRM **RetailCRM**. 39 инструментов + 2 навыка-промпта для работы с заказами, клиентами, товарами, остатками, оплатами, задачами, справочниками и аналитикой через API v5.

[![npm](https://img.shields.io/npm/v/@theyahia/retailcrm-mcp)](https://www.npmjs.com/package/@theyahia/retailcrm-mcp)
[![Smithery](https://smithery.ai/badge/@theyahia/retailcrm-mcp)](https://smithery.ai/server/@theyahia/retailcrm-mcp)

## Ответы экономят токены по умолчанию

Читающие инструменты возвращают **компактную структурированную сводку** только из тех полей, которые нужны агенту, а не весь ответ RetailCRM. Подробность настраивается на каждый вызов:

| Параметр | Что делает |
|-------|--------|
| _(по умолчанию)_ | `detail:"summary"` — ключевые поля + блок `pagination` |
| `detail:"full"` | Все структурированные поля (позиции, доставка, оплаты, адрес…) |
| `raw:true` | Нетронутый ответ RetailCRM (для отладки) |

> ⚠️ **v3 ломает совместимость** с v2: по умолчанию отдаётся структурированная сводка, а не сырой JSON. Передайте `raw:true`, чтобы вернуть прежний формат.

## Инструменты (39)

### Заказы
| Инструмент | Описание |
|------|-------------|
| `list_orders` | Список заказов по статусу, клиенту, номеру, периоду |
| `get_order` | Один заказ по ID или externalId |
| `create_order` | Создать заказ; привязать существующего клиента (`customer_id`/`customer_external_id`) или завести нового прямо в вызове |
| `update_order` | Изменить статус, клиента, доставку, комментарии |
| `orders_history` | История изменений заказов, включая смены статусов (инкрементальная синхронизация) |

### Клиенты
| Инструмент | Описание |
|------|-------------|
| `list_customers` | Поиск клиентов по имени, e-mail, телефону, дате |
| `get_customer` | Один клиент по ID или externalId |
| `create_customer` | Создать клиента |
| `update_customer` | Изменить существующего клиента |
| `merge_customers` | Объединить дубли (разрушающая операция) |
| `customers_history` | Лог изменений клиентов (прирост/отток, инкрементальная синхронизация) |

### Товары и остатки
| Инструмент | Описание |
|------|-------------|
| `list_products` | Товары каталога по названию, группе, активности, цене |
| `list_product_groups` | Дерево товарных категорий |
| `store_inventories` | Остатки и себестоимость по торговым предложениям и складам |

### Оплаты
| Инструмент | Описание |
|------|-------------|
| `order_payment_create` | Зафиксировать оплату по заказу |
| `order_payment_edit` | Изменить оплату |
| `order_payment_delete` | Удалить оплату (разрушающая операция) |

### Заметки и задачи
| Инструмент | Описание |
|------|-------------|
| `customer_notes_list` / `customer_notes_create` / `customer_notes_delete` | Произвольные заметки по клиенту |
| `tasks_list` / `tasks_create` / `tasks_edit` | Задачи и напоминания |

### Маркетинг и финансы
| Инструмент | Описание |
|------|-------------|
| `list_segments` | Сегменты клиентов (RFM и маркетинговые когорты) |
| `list_costs` / `create_cost` | Записи расходов для аналитики маржи |

### Файлы
| Инструмент | Описание |
|------|-------------|
| `files_list` / `files_get` / `files_upload` | Прикрепление и получение файлов (загрузка сырым octet-stream) |

### Справочники
| Инструмент | Описание |
|------|-------------|
| `list_statuses` / `list_delivery_types` / `list_payment_types` / `list_stores` | Справочники статусов, доставок, оплат и магазинов |
| `list_sites` | Сайты, доступные ключу API (для заполнения параметра `site`) |
| `list_countries` / `list_order_types` / `list_order_methods` | Справочники адресов и заказов |

### Аналитика
| Инструмент | Описание |
|------|-------------|
| `get_orders_summary` | Статистика заказов за период: точное количество и выручка, средний чек, распределение по статусам |
| `get_customers_summary` | Количество новых клиентов за период |

## Навыки-промпты (2)

| Навык | Описание |
|-------|-------------|
| `new-orders` | Быстрый ежедневный обзор сегодняшних заказов |
| `customer-search` | Найти клиента по имени, e-mail или телефону |

## Настройка

1. В RetailCRM откройте **Настройки → Интеграция → Ключи API**.
2. Создайте ключ API с нужными правами (заказы, клиенты, склад, справочники). Для **мультисайтового** ключа передавайте код `site` в инструментах создания и изменения (см. `list_sites`).
3. Запомните свой домен (часть `yourstore` из `yourstore.retailcrm.ru`).

## Переменные окружения

| Переменная | Обяз. | Описание |
|----------|----------|-------------|
| `RETAILCRM_DOMAIN` | да | Домен вашего RetailCRM (например, `yourstore.retailcrm.ru`) |
| `RETAILCRM_API_KEY` | да | Ключ API (передаётся в заголовке `X-API-KEY`) |
| `RETAILCRM_READONLY` | нет | `1` — оставить только читающие инструменты (скрыть create/update/merge/delete) |
| `RETAILCRM_RATE_LIMIT` | нет | Клиентское ограничение запросов в секунду (RetailCRM допускает ~10/с) |
| `PORT` / `HOST` | нет | Привязка HTTP-сервера (по умолчанию `3000` / `127.0.0.1`, только в режиме `--http`) |
| `RETAILCRM_HTTP_ALLOWED_HOSTS` | нет | Разрешённые значения `Host` через запятую для защиты от DNS-rebinding |
| `RETAILCRM_DNS_PROTECTION` | нет | `off` — отключить защиту от DNS-rebinding (HTTP-режим) |

> `RETAILCRM_URL` по-прежнему принимается как запасной вариант для `RETAILCRM_DOMAIN`.

## Подключение к Claude Desktop

```json
{
  "mcpServers": {
    "retailcrm": {
      "command": "npx",
      "args": ["-y", "@theyahia/retailcrm-mcp"],
      "env": {
        "RETAILCRM_DOMAIN": "yourstore.retailcrm.ru",
        "RETAILCRM_API_KEY": "your-api-key"
      }
    }
  }
}
```

## Режим Streamable HTTP

Запуск в виде HTTP-сервера вместо stdio:

```bash
RETAILCRM_DOMAIN=yourstore.retailcrm.ru \
RETAILCRM_API_KEY=your-key \
npx @theyahia/retailcrm-mcp --http
```

- `POST /mcp` — эндпоинт MCP Streamable HTTP (stateless: на каждый запрос создаётся новый сервер)
- `GET /health` — проверка состояния (JSON с версией и числом инструментов)
- `GET`/`DELETE /mcp` — `405` (в stateless-режиме не используются)
- Привязка по умолчанию: `127.0.0.1:3000`. Защита от DNS-rebinding для локальных привязок включена по умолчанию.

## Smithery

```bash
npx @smithery/cli install @theyahia/retailcrm-mcp
```

## Демо-промпты

**1. Обзор заказов за день:** «Покажи все заказы, созданные сегодня, в статусе „новый“. Дай итоговое количество и выручку.»

**2. Клиент и его история заказов:** «Найди клиента с почтой anna@example.com. Покажи полный профиль и последние заказы.»

**3. Проверка остатков:** «Есть ли товар с externalId SKU-42 в наличии и на каком складе?»

## Вебхуки и триггеры

RetailCRM не умеет создавать вебхуки через API. Используйте **Триггеры** в админке (Настройки → Триггеры), чтобы отправлять HTTP-запросы на внешние эндпоинты по событиям заказов и клиентов.

## Обработка ошибок

- **Лимиты запросов и 5xx:** автоматический повтор с экспоненциальной задержкой и джиттером (до 3 попыток).
- **Ошибки API:** детали ошибки RetailCRM разбираются и возвращаются модели как результат инструмента с `isError: true`, чтобы агент мог исправиться сам (например, повторить с `by:"externalId"`).
- **Таймауты:** 15 секунд на запрос с повтором.

## Разработка

```bash
npm install
npm test          # vitest (на моках; живой ключ API не нужен)
npm run lint      # eslint
npm run typecheck # tsc --noEmit
npm run dev       # dev-режим stdio (tsx)
npm run build     # очистка + сборка в dist/
```

## Лицензия

MIT

---

Часть [WWmcp](https://github.com/theYahia/WWmcp) · Telegram: [@vhodvai](https://t.me/vhodvai)

