Skip to main content
Glama

shop-mcp

인터넷 쇼핑몰의 shop.db SQLite 데이터베이스(고객, 상품, 주문, 주문 항목)를 대상으로 분석 도구를 노출하는 읽기 전용 Model Context Protocol 서버입니다. AI 에이전트에 연결되어 에이전트가 데이터를 절대 수정할 수 없으면서도 데이터에 대한 분석 질문에 답할 수 있도록 설계되었습니다.

서버는 stdio 위에서 MCP를 구동하고, 데이터베이스를 읽기 전용 모드로 열며, 도메인 규칙(어떤 주문 상태가 매출로 집계되는지, 고객의 국가가 어떻게 파생되는지, 돈이 어디서 오는지)을 설명에 포함한 소수의 특화된 매개변수형 도구를 노출합니다. 일반적인 SQL 도구나 쓰기 도구는 없으므로 "취소된 주문을 전부 삭제" 같은 파괴적인 프롬프트는 실행할 수 없습니다.

이 저장소의 MCP 서버 코드는 서버를 손으로 작성하지 말아야 한다는 과제 제약에 따라 AI 코딩 에이전트(Cursor)가 생성했습니다.

요구 사항

  • Python 3.11 이상

  • shop.db SQLite 데이터베이스(database/shop.db에 커밋됨)

  • uv (권장) — 전역 설치 없이 격리된 프로젝트 환경에서 서버를 실행합니다. brew install uv(macOS) 또는 curl -LsSf https://astral.sh/uv/install.sh | sh로 설치합니다.

Related MCP server: mcp-data-analyst

설치

uv 사용 시(권장) — 수동으로 venv나 pip를 만들 필요가 없습니다. uv가 첫 번째 실행에서 pyproject.toml을 참고해 프로젝트와 의존성을 해결합니다:

uv sync          # create / refresh the project's .venv from pyproject.toml

uv가 없을 때 — virtualenv를 만들고 패키지를 직접 설치합니다:

python3 -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install -e .

그러면 mcp SDK와 shop-mcp 패키지(python -m shop_mcp 엔트리 포인트와 shop-mcp 콘솔 스크립트 제공)가 설치됩니다.

구성

서버는 프로세스 작업 디렉터리(ProjectRoot) 기준 database/shop.db 데이터베이스를 엽니다. 환경 변수는 필요하지 않습니다.

uv --directory <project>(아래 클라이언트 구성 참고)로 실행하면 uv가 프로젝트 루트를 작업 디렉터리로 설정하므로 커밋된 데이터베이스를 자동으로 찾습니다.

database/shop.db가 없으면 서버는 시작과 동시에 현재 작업 디렉터리를 포함한 명확한 구성 오류로 종료됩니다(스택 트레이스 없음, 알 수 없는 대체 없음). MCP 클라이언트 설정에서 cwd를 저장소 루트로 지정하세요.

실행

uv run python -m shop_mcp

또는 패키지를 활성화된 venv에 설치한 경우:

python -m shop_mcp

또는 동일하게:

shop-mcp

서버는 stdin에서 JSON-RPC를 읽고 stdout으로 씁니다. 보통 직접 실행하지는 않으며, AI 에이전트가 대신 실행합니다(아래 참조).

에이전트 연결

examples/mcp/에 커밋된 즉시 사용 가능한 MCP 클라이언트 구성이 들어 있으며, uv만 설치하면 별도 설정 없이 실행됩니다:

클라이언트

구성 파일

Cursor

examples/mcp/cursor.json

Claude Desktop

examples/mcp/claude_desktop.json

일반 stdio

examples/mcp/generic_stdio.json

표준/기본

examples/mcp/shop.json

Docker

examples/mcp/docker.json

각 구성의 모습은 다음과 같습니다(--directory 경로는 이 저장소의 절대 경로로 변경하면 됩니다):

{
  "mcpServers": {
    "shop": {
      "command": "uv",
      "args": ["run", "--directory", "/path/to/internet-shop-mcp", "python", "-m", "shop_mcp"]
    }
  }
}

uv run --directory <project>는 작업 디렉터리를 프로젝트 루트로 설정하고 프로젝트의 .venv를 사용하므로, 서버가 자동으로 database/shop.db를 찾습니다. 이 같은 구성은 다른 머신에서도 이식 가능합니다(--directory 경로만 달라집니다).

uv를 쓰지 않으려면 패키지를 venv에 직접 설치하고(설치 참고), MCP 클라이언트 설정에서 command: "python"과 cwd를 저장소 루트로 설정하세요.

  • Cursor: Settings → MCP → Add MCP Server를 열고 examples/mcp/cursor.json 내용을 붙여넣습니다(또는 Project MCP 범위를 사용하고 커밋).

  • Claude Desktop: examples/mcp/claude_desktop.json의 내용을 claude_desktop_config.json(macOS: ~/Library/Application Support/Claude/claude_desktop_config.json)에 복사합니다.

  • 일반 stdio 클라이언트: stdio로 MCP를 지원하는 클라이언트가 있다면 examples/mcp/generic_stdio.json을 사용합니다.

연결 후 에이전트는 여덟 가지 도구를 보게 됩니다. those are: list_tables, describe_table, count_customers_by_country, rank_countries_by_customers, top_customers, top_products, revenue_by_category, revenue_by_year.

도구

| 도구 | 답을 제공하는 대상 | 답변 | | -------------------------------------- | ------------------------------------------- | | list_tables | 과제 1 — 테이블 목록과 각 테이블의 내용 | | describe_table(table) | 하나의 테이블 스키마 | | count_customers_by_country(country?) | 과제 2 — 특정 국가의 고객 | | rank_countries_by_customers(limit) | 과제 3 — 고객이 가장 많은 국가 | | top_customers(by, limit, offset) | 과제 4 & 8 — 가장 많이 쓴 고객 / 주문이 가장 많은 고객 | | top_products(limit, metric, offset) | 과제 5 — 판매가 가장 많은 상품 | | revenue_by_category(limit, offset) | 과제 6 — 매출 기준 상위 카테고리 | | revenue_by_year(year) | 과제 7 — 해당 연도의 매출 |

도구 설명에 담긴 도메인 규칙(자세한 이유는 CONTEXT.md 및 docs/adr/ 참조):

  • 국가는 고객 전화번호 접두사(E.164)로 파생합니다. country 열은 없습니다. +49 → Germany, +7 → Russia. 인식되지 않는 접두사는 unknown으로 매핑됩니다. 도구는 전체 이름("Germany") 또는 ISO 알파-2 코드("DE")를 받아들이고 두 형식을 모두 반환합니다.

  • 매출 / 지출은 completed와 shipped 상태의 주문만 집계합니다.

  • 최다 주문 수는 cancelled를 제외한 모든 주문 상태를 셉니다.

  • 베스트셀러는 판매 수량(Units sold)으로 상품의 순위를 매기며, 매출은 부가 항목입니다.

  • 금액은 주문/고객/연도 롤업일부에서 orders.total_amount를 사용하고, 상품/카테고리 집계는 SUM(order_items.quantity * order_items.unit_price)(현재 products.price가 아닌 실제 판매 가격)를 사용합니다.

  • **제한(limit)**은 기본 100, 상한 1000까지이며, offset로 페이지네이션합니다.

  • 오류는 Invalid year: must be a 4-digit integer 같은 짧은 메시지로 에이전트에게 반환됩니다. 스택 트레이스는 stderr에만 남습니다.

안전성

데이터베이스는 설계상 읽기 전용입니다:

  • SQLite를 file:<path>?mode=ro(uri=True)로 열기 때문에 어떤 쓰기 시도도 sqlite3.OperationalError: attempt to write a readonly database 오류를 발생시킵니다.

  • 이중 방어로 PRAGMA query_only = 1을 설정합니다.

  • 쓰기 도구나 일반 SQL 도구는 노출되지 않습니다. 제공되는 것은 위의 여덟 가지 읽기 전용 분석 도구뿐입니다.

테스트(tests/test_safety.py)는 쓰기 시도에서 예외가 발생하는지, 쓰기 도구가 없다고 명시되었는지, 모든 도구 실행 후 데이터베이스 파일이 바이트 단위에 대한 변화가 없는지 검증합니다.

엔드 투 엔드 검증

커밋된 데이터에 대한 기대 결과(150명의 모든 고객이 +7 번호를 사용, 750개의 모든 주문이 2026년 날짜)로 위탁 과제들을 AI 에이전트와 연결해 검증했습니다:

  1. 모든 테이블 나열 — list_tables는 customers, products, orders, order_items를 각각 설명과 함께 반환합니다.

  2. 독일의 고객은 몇 명인가요? — count_customers_by_country("Germany") → 0 (정직한 0; +49 번호를 가진 고객이 없습니다).

  3. 어느 국가에 고객이 가장 많나요? — rank_countries_by_customers → 러시아(RU), 150명.

  4. 누가 가장 많은 돈을 썼나요? — top_customers(by="spend", limit=1) → Полина Козлов, polina.kozlov340@icloud.com, 총 지출 531810.0.

  5. 상위 5개 베스트셀러 상품 — top_products(limit=5) → 판매 수량 순(Эспандер плечевой, Планшет Tab 10, …)과 함께 매출이 나옵니다.

  6. 매출 기준 상위 3개 카테고리 — revenue_by_category(limit=3) → Электроника, Бытовая техника, Одежда и обувь.

  7. 2025년 매출 — revenue_by_year(2025) → 0과 함께 no orders in 2025 메모 반환(다른 연도로 대체하지 않음; 모든 주문은 2026년).

  8. 최다 주문 — top_customers(by="order_count", limit=1) → София Яковлев, sofiya.yakovlev284@yandex.ru, 15건.

파괴적인 프롬프트 "Delete all cancelled orders" 는 거부됩니다. 이를 받아들일 수 있는 도구가 없으며, 읽기 전용 연결이 SQLite 레벨에서 어떤 쓰기도 거절하기 때문입니다.

테스트

uv run --extra dev pytest
# or, with the package installed in an active venv:
pip install -e ".[dev]"
python -m pytest

테스트 범위는 스모크 테스트(stdio에서 서버 기동 및 handshake/list_tools 응답), 모든 도구의 happy path, 도메인 규칙(수익은 비인정 상태 제외, 주문 수는 cancelled 제외, 상품은 수량 순), 엣지 케이스(독일 → 0, 2025 → 0, unknown country, invalid year/metric/by, limit 상한 제한, 페이지네이션), 그리고 안전 보장(쓰기 시도 시 예외, 쓰기 도구 없음, DB 파일 불변)를 포함합니다.

Docker (보너스)

컨테이너에서 실행하는 방법은 아래 "Docker" 섹션을 참조하세요.

프로젝트 레이아웃

internet-shop-mcp/
├── database/
│   └── shop.db                  # the read-only database
├── pyproject.toml               # package + dependency declaration
├── README.md
├── CONTEXT.md                   # domain glossary
├── docs/adr/                    # ADR-0001..0005
├── src/shop_mcp/
│   ├── __main__.py              # `python -m shop_mcp`
│   ├── main.py                  # server wiring + tool registration
│   ├── config.py                # database/shop.db resolution
│   ├── db.py                    # read-only SQLite connection
│   ├── country.py               # phone-prefix → country mapping
│   └── tools.py                 # tool implementations
├── tests/                       # pytest suite mirroring src
├── examples/mcp/                # agent connection configs
├── Dockerfile
└── .dockerignore

Docker

컨테이너 안에서 서버를 빌드하고 실행합니다. 데이터베이스는 로컬 개발과 같은 방식으로 이미지 안 /app/database/shop.db에 복사됩니다.

docker build -t shop-mcp .
docker run --rm -i shop-mcp

이에 맞는 Docker MCP 클라이언트 구성:

{
  "mcpServers": {
    "shop": {
      "command": "docker",
      "args": ["run", "--rm", "-i", "shop-mcp"]
    }
  }
}

번들 데이터베이스 대신 본인 데이터베이스를 마운트하고 싶다면:

docker run --rm -i -v "$PWD/database:/app/database:ro" shop-mcp

읽기 전용 보장은 컨테이너 안에서 동일하게 유지됩니다. 연결은 mode=ro와 query_only=1을 사용하며, 파괴적인 프롬프트는 여전히 거절됩니다.

Available Tools

8 tools
count_customers_by_countryA

Count customers by country. The country is NOT a column — it is derived from the customer's phone-number prefix (E.164), so do not look for a country column. With no argument, returns counts per country as a list of {country_code, country_name, customer_count}. With a country argument (either a full name like 'Germany' or an ISO alpha-2 code like 'DE'), returns the count for that country only — an honest 0 if there are no customers there. An unknown country name returns an error.

Inputs: country.

describe_tableA

Describe the schema of one table: columns (name, type, not_null, default, primary_key) and foreign keys. Use this before building any mental model of how tables relate. Returns {table, columns, foreign_keys}. Pass the table name (one of: customers, products, orders, order_items).

Inputs: table (required).

list_tablesA

List every table in the shop database with a short description of what each table holds. Use this first to understand what entities are available. Returns a list of {name, description}.

Inputs: no named parameters.

rank_countries_by_customersA

Rank countries by number of customers, highest first. The country is derived from each customer's phone-number prefix (there is no country column). Returns a list of {country_code, country_name, customer_count}. limit defaults to 100 and is clamped to a maximum of 1000.

Inputs: limit.

revenue_by_categoryA

Rank product categories by revenue, joining orders -> order_items -> products. Only 'completed' and 'shipped' orders count. Revenue is SUM(order_items.quantity * order_items.unit_price) using the actual sale price. Returns a list of {category, revenue}. limit defaults to 100 (max 1000); offset paginates.

Inputs: limit, offset.

revenue_by_yearA

Return total revenue for a single year (a 4-digit integer, e.g. 2025). Revenue is SUM(orders.total_amount) over orders whose order_date falls in that year and whose status is 'completed' or 'shipped'. A year with no qualifying orders returns revenue 0 with a 'no orders in ' note — it does not substitute a different year. An invalid year returns an error.

Inputs: year (required).

top_customersA

Rank customers either by total spend or by number of placed orders.

  • by='spend': sums orders.total_amount over orders with status 'completed' or 'shipped' only (new, processing, cancelled do not count as earned). Returns first_name, last_name, email, total_spend.

  • by='order_count': counts orders whose status is NOT 'cancelled'. Returns first_name, last_name, email, order_count. Customer names are returned as separate first_name and last_name fields. limit defaults to 100 (max 1000); offset paginates.

Inputs: by, limit, offset.

top_productsA

Rank products by units sold (metric='units', default) or by revenue (metric='revenue'). Only 'completed' and 'shipped' orders count. Money is computed from order_items.unit_price (the actual sale price), not the current products.price. Returns a list of {name, units_sold, revenue}. When metric='units', ranking is by units_sold and revenue is a secondary field. limit defaults to 100 (max 1000); offset paginates.

Inputs: limit, metric, offset.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.2/5.0

    Scored across 8 tools

    Disambiguation3/5

    Most tools are clearly distinct, but count_customers_by_country and rank_countries_by_customers return the same country-level customer counts with only ordering/filtering differences. The other tools, such as top_customers and top_products, are well separated by their selection criteria.

    Naming Consistency4/5

    Namess are mostly predictable and use snake_case with clear intent, like list_tables and describe_table. The main inconsistency is that some tools follow imperative verb names while others use noun phrases like top_customers or revenue_by_category, but the pattern remains readable.

    Tool Count5/5

    Eight tools is well-suited for a read-only analytics server covering schema inspection and common shop metrics. Each tool has a clear role, and the count does not feel excessive or thin.

    Completeness4/5

    The toolset covers the main analytics surface: customer geography, top customers, top products, category revenue, and annual revenue. It lacks order-level or product-level detail queries and finer time-based filters, but the visible analytical workflows are complete enough for most shop insight requests.

    Maintenance

    ActivityNo data
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      D
      maintenance
      A secure MCP server that exposes a SQLite database to AI agents with Role-Based Access Control, supporting authentication, customer/order/user management, and audit logging.
      -
    • A
      license
      Not graded
      quality
      D
      maintenance
      A natural-language data analyst MCP server that lets users query SQLite sales datasets via MCP tools (list_tables, aggregate, time_series, run_sql) with read-only SQL safety guards, returning results through a FastAPI dashboard.
      MIT
    • F
      license
      Not graded
      quality
      D
      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
      Not graded
      quality
      D
      maintenance
      This MCP server lets an AI agent securely connect to a read-only SQLite store database, inspect its tables and schema, and run analytical SQL queries without modifying any data.
      -