Skip to main content
Glama
farranfox

shop-database

by farranfox

Shop database MCP server

Что делает этот MCP

Это MCP-сервер для безопасного анализа локальной SQLite-базы интернет-магазина. Он работает через стандартные потоки ввода/вывода (stdio), не поднимает HTTP-сервер и предоставляет AI-агенту доступ только для чтения.

Сервер открывает SQLite в режиме read-only и дополнительно разрешает только один запрос SELECT или WITH ... SELECT. Изменение данных, PRAGMA, транзакции, подключение других баз и несколько SQL-выражений блокируются. В базе нет поля страны, поэтому аналитика по странам недоступна.

Основные сущности: customers, products, orders и order_items. Связи: заказ ссылается на клиента, а строка заказа — на заказ и товар. Для исторической выручки по товарам используйте order_items.quantity * order_items.unit_price.

Related MCP server: shop

Требования и запуск

Нужен Node.js 24.2+ LTS — стабильная версия с нужным API node:sqlite. Проект использует официальный MCP TypeScript SDK, Zod, TypeScript и Vitest.

npm install
npm run build
npm test
npm run start

Для разработки используйте npm run dev, для строгой проверки типов — npm run lint. Протокол MCP пишется только в stdout; диагностика — только в stderr.

Как подключить MCP

Сначала соберите проект:

npm run build

Добавьте сервер в конфигурацию вашего MCP-клиента, заменив абсолютные пути на свои:

{
  "mcpServers": {
    "shop-database": {
      "command": "node",
      "args": ["/absolute/path/to/shop-mcp/dist/index.js"],
      "env": {
        "SHOP_DB_PATH": "/absolute/path/to/shop-mcp/data/shop.db"
      }
    }
  }
}

Переменная SHOP_DB_PATH необязательна. Если её не задать, сервер использует data/shop.db относительно собранного файла dist/index.js.

# .env — опционально
SHOP_DB_PATH=/absolute/path/to/shop.db

Tools

Tool

Входные данные и результат

Когда использовать

get_database_schema

Пустой объект. Возвращает бизнес-таблицы, их поля, типы, ключи, значения по умолчанию, внешние ключи и индексы. Внутренние таблицы SQLite скрыты.

Перед составлением незнакомого SQL-запроса.

query_database

Обязательный sql; необязательные массив parameters, page (по умолчанию 1) и pageSize (по умолчанию 50, максимум 100). Возвращает columns, rows, page, pageSize, returnedRowCount, hasMore.

Для фильтрации, JOIN, агрегаций и произвольной аналитики.

При получении нескольких страниц обязательно добавляйте стабильный ORDER BY. Пагинация применяется сервером; он получает не более pageSize + 1 строк. Значения для ? передавайте в parameters, а не подставляйте в SQL-строку.

{"sql":"SELECT id, name, stock_quantity FROM products ORDER BY id","page":2,"pageSize":25}

Пять тестовых промптов

После подключения перезапустите или обновите MCP-клиент, чтобы он обнаружил shop-database. Скопируйте любой из этих запросов в чат с включённым MCP:

  1. «Сначала вызови get_database_schema, затем перечисли таблицы, их ключевые поля и связи между ними.»

  2. «Найди клиента, который потратил больше всех. Верни полное имя, email и сумму всех заказов.»

  3. «Покажи 5 самых продаваемых товаров: название, суммарное число проданных единиц и выручку по исторической цене из order_items

  4. «Рассчитай выручку за 2025 год по полю orders.total_amount. Используй параметры для границ дат.»

  5. «Покажи помесячные число заказов и выручку, отсортированные по месяцу. Используй page: 1, pageSize: 12 и стабильный ORDER BY

Безопасность и ошибки

Допускается ровно один SELECT либо WITH-запрос с итоговым SELECT. Сервер отклоняет DELETE FROM orders, UPDATE products, PRAGMA, ATTACH, INSERT, DDL-команды, загрузку расширений и несколько выражений в одном запросе. Read-only подключение к SQLite является второй линией защиты.

Некорректные параметры и SQL возвращают короткие понятные ошибки без путей к файлам, переменных окружения и stack trace. Если база не найдена или недоступна, проверьте SHOP_DB_PATH либо наличие data/shop.db. Если не устанавливаются зависимости — выполните npm install; если сервер не запускается — проверьте версию Node.js.

Для ручной проверки stdio выполните npm run build, затем node dist/index.js из MCP-клиента: в stdout должны попадать только сообщения MCP-протокола.

Available Tools

2 tools
get_database_schemaGet database schemaA

Returns user-facing business tables, columns, constraints, indexes, and relationships. The database is read-only and has no country field, so country analytics are unavailable.

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

Output Schema

ParametersJSON Schema
NameRequiredDescription

No output parameters

TDQS

A4.5/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the burden of explaining behavior. It states the database is read-only and flags the country-field limitation. Since this is a no-parameter schema retrieval tool, these details are sufficient and useful.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two concise sentences convey the full purpose and an important limitation without any filler. The output is front-loaded and every sentence adds value.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a tool with no parameters and an existing output schema, the description covers the essential behavior and the main caveat about country data. Nothing critical is missing.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The tool has zero parameters, so the baseline is 4. The description adds no parameter details, but none are needed given the empty input schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly specifies the verb 'Returns' and the resource: user-facing business tables, columns, constraints, indexes, and relationships. It distinguishes this metadata-focused tool from the sibling query_database, which is for data retrieval.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies this tool is for exploring schema rather than querying data, and it explicitly calls out the absence of a country field, warning against expecting country analytics. It does not explicitly name the sibling as an alternative for data queries, but the context is clear.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

query_databaseQuery databaseA

Executes exactly one read-only SELECT or WITH ... SELECT query. Data definition, data modification, transactions, attachments, PRAGMA, and multiple statements are refused. Pagination is server-applied and results include paging metadata; include stable ORDER BY when retrieving multiple pages.

ParametersJSON Schema
NameRequiredDescriptionDefault
sqlYesOne read-only SQLite SELECT query. CTEs beginning with WITH are allowed when their final statement is SELECT. Do not send multiple statements or PRAGMA. Use parameter placeholders for values supplied through parameters.
pageNoOne-based page number.
pageSizeNoMaximum rows returned for this page; server maximum is 100.
parametersNoOptional positional values bound to ? placeholders, in order.

Output Schema

ParametersJSON Schema
NameRequiredDescription

No output parameters

TDQS

A4.7/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full disclosure burden and handles it thoroughly. It reveals that pagination is server-applied, that results include paging metadata, that non-SELECT statements are refused, and that stable ORDER BY is required for multi-page consistency. This is substantial behavioral context beyond a simple 'run a query' statement.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two sentences contain the full contract: the permitted statement forms, the explicit exclusions, and the pagination caveat. Every sentence earns its place, and there is no repetition of schema details or filler.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the schema covers parameter syntax and an output schema exists, the description supplies the missing behavioral contract: allowed query types, refused constructs, server-applied pagination, and the stable ORDER BY requirement. An agent has enough information to call this tool correctly without ambiguity.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema already documents all four parameters with 100% coverage, giving a baseline of 3. The description adds meaningful operational semantics: placeholders should be used for values via the parameters array, and pagination is applied server-side, which directly informs how page/pageSize should be used. That elevates it above baseline.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description begins with an explicit scope: 'Executes exactly one read-only SELECT or WITH ... SELECT query.' It combines a clear verb, resource, and exact statement forms, and the constraints (no DDL, DML, transactions, PRAGMA, or multiple statements) make it easy to distinguish from the schema-retrieval sibling.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description clearly states what is allowed and what is refused, so an agent knows this is the tool for read-only queries rather than schema inspection or mutations. It also provides concrete guidance for pagination: include a stable ORDER BY when retrieving multiple pages. It stops short of explicitly naming the sibling as an alternative for schema retrieval, hence not a 5.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

TDQS

A4.6/5.0
Disambiguation5/5

The two tools have clearly distinct purposes: one exposes the database schema, the other executes read-only queries. There is no overlap in functionality, so an agent can easily choose the right tool.

Naming Consistency5/5

Both tool names follow the same verb_noun pattern in snake_case: get_database_schema and query_database. This is consistent and predictable.

Tool Count3/5

With only two tools, the server feels minimal but is reasonably scoped for a read-only database interface. It is on the thin side, but each tool serves a distinct and necessary purpose.

Completeness5/5

For a read-only database, schema introspection and querying cover the entire lifecycle. The server provides all operations needed to explore and retrieve data without creating dead ends.

Maintenance

ActivityMaintained
ResponsivenessNo issues

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

  • F
    license
    Not graded
    quality
    C
    maintenance
    Enables safe, read-only analysis of an online store's SQLite database, providing schema introspection, restricted SELECT queries, and specialized analytics tools through MCP.
  • F
    license
    A
    quality
    C
    maintenance
    Enables read-only interaction with an online store's SQLite database over MCP stdio, including table listing, schema inspection, safe read-only SQL execution, and sales analytics. It rejects mutating SQL operations to keep data intact.
    4
  • F
    license
    Not graded
    quality
    C
    maintenance
    Provides AI agents read-only analytical access to a SQLite database over stdio, with tools for listing tables, describing schemas, and running paginated SQL queries.
  • F
    license
    Not graded
    quality
    C
    maintenance
    Enables AI agents to read-only analyze a SQLite e-commerce database, exploring schema and running analytical SQL queries over stdio.

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/farranfox/shop-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server