Skip to main content
Glama
haraj-mcp

haraj-mcp

by bibo242

haraj-mcp

Сервер Model Context Protocol (MCP) для haraj.com.sa — крупнейшей доски объявлений в Саудовской Аравии.

Этот сервер предоставляет 21 инструмент любому MCP-совместимому агенту (Claude Desktop, Cursor, opencode, Zed и т.д.), позволяя искать и получать объявления с маркетплейса в реальном времени без копирования и вставки curl-команд.

Все инструменты повторяют реальные операции haraj.com.sa, зафиксированные в ходе живой браузерной сессии (2026-08-17). Никаких выдуманных фильтров — каждый аргумент соответствует тому, что живой фронтенд фактически отправляет в своих GraphQL-запросах.

Claude Desktop / Cursor / opencode
        │
        │  MCP (JSON-RPC over stdio)
        ▼
   ┌──────────────┐
   │  haraj-mcp   │ ── HTTPS ──▶  graphql.haraj.com.sa
   │  (Python)    │                + livestream.haraj.com.sa
   └──────────────┘

Доступные инструменты (21)

Обнаружение

Tool

Purpose

trending_keywords(range_in_days)

Самые популярные поисковые запросы (по умолчанию за 7 дней)

search_suggest(prefix)

Автодополнение из живого поискового поля (топ-10)

related_tags(tag)

Города с количеством объявлений для указанного тега

live_streams(limit)

Текущие открытые прямые эфиры покупок haraj

Лента / поиск

Tool

Purpose

fetch_feed(tag, city?, cities?, page?, before_update_date?, limit?)

Лента на основе тега (главная страница + страницы категорий). before_update_date — это курсор: передайте updateDate последнего элемента, чтобы получить следующую страницу.

search(keyword, cities?, city?, tag?, tags?, during_date?, near?, ...)

Поиск по ключевым словам. during_date принимает 1days/3days/1week/1months. near — это геохеш @lat,lon.

promoted_posts(tag)

Карусель продвигаемых объявлений для тега

sellers_list(tags, page?)

Продавцы по тегу (недвижимость и т.д.)

Детали объявления

Tool

Purpose

get_post_details(post_id)

Объявление + 3 связанные группы (через настоящий эндпоинт similarPosts — канонический способ "получить по id")

post_like_info(post_id)

{is_like, total, is_following}

comments(post_id)

Список комментариев

post_contact(post_id)

{contactText, contactMobile, shouldEnableWhatsApp}

locker_shipment_offer(post_id)

{offerId, isEligible, price} (доставка Locker)

Пользователь

Tool

Purpose

user(username?, user_id?, rating_summary_only?)

Полный профиль (рейтинг, подписчики, история местоположений, значки)

is_following_user(username)

bool

follow_user(username)

Мутация: переключает подписку

user_mention_suggestions()

Для @-упоминаний

Аккаунт

Tool

Purpose

notes(set_read?)

Уведомления (значок колокольчика)

outgoing_buy_requests(page?)

История эскроу "Покупка с уверенностью"

is_following_tag(tag)

bool

check_auth()

Проверка, что учётные данные из .env всё ещё действительны

Для fetch_feed, promoted_posts и search передайте full=True, чтобы получить полный объект Post вместо компактной сводки. Компактная сводка содержит следующие ключи:

{
  "id": 185926519,
  "title": "...",
  "price_sar": 650.0,
  "price_display": "650 SAR",
  "url": "https://haraj.com.sa/...",
  "city": "الشرقيه",
  "geo_city": "الدمام",
  "post_date": 1785729404,
  "has_image": true,
  "thumb_url": "https://mimg6cdn.haraj.com.sa/...",
  "tags": ["شاشات", "..."],
  "has_price": true
}

Related MCP server: opensooq-mcp

Установка

cd /mnt/W/Desktop/Software/haraj-mcp
pip install -e .

Эта команда устанавливает консольный скрипт haraj-mcp в ваш PATH.

Настройка авторизации

cp .env.example .env
# Edit .env and paste your HARAJ_JWT and LAST_REQUEST_ID.

Как получить свежие значения (они истекают каждые ~10 дней):

  1. Откройте https://haraj.com.sa в Chrome и войдите в систему.

  2. F12 → вкладка Network → нажмите на любой запрос к graphql.haraj.com.sa.

  3. В Headers скопируйте authorization (начинается с Bearer eyJ…) и lastRequestId.

  4. Вставьте их в .env и перезапустите MCP-сервер.

Проверить можно с помощью check_auth — он возвращает утверждение exp из JWT и seconds_remaining.

Подключение к вашему MCP-клиенту

opencode / Claude Desktop / Cursor

Добавьте это в конфигурацию MCP вашего клиента (обычно ~/.config/opencode/opencode.json, ~/Library/Application Support/Claude/claude_desktop_config.json или ~/.cursor/mcp.json):

{
  "mcpServers": {
    "haraj": {
      "command": "haraj-mcp",
      "cwd": "/mnt/W/Desktop/Software/haraj-mcp"
    }
  }
}

Сервер читает .env из cwd, поэтому секреты остаются в каталоге проекта и не попадают в конфигурацию MCP-клиента.

Нестандартное расположение .env

Укажите HARAJ_MCP_ENV=/path/to/.env в блоке env конфигурации MCP.

Примеры промптов для агента

После подключения ваш агент сможет отвечать:

"Что сегодня в тренде на haraj?" "Получи последние 20 объявлений в حراج السيارات (категория автомобилей)." "Найди на haraj RTX 4090 за последнюю неделю (during_date=1week)." "Получи профиль продавца и все его текущие объявления для post_id=185354313." "Какую стоимость доставки я заплачу, если куплю это объявление через Locker?" "Что люди вводят в поисковой строке после شاشة?" "Перечисли все открытые прямые эфиры покупок прямо сейчас."

Запуск без MCP-клиента (отладка)

Передавайте JSON-RPC-сообщения прямо на сервер:

echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"0"}}
{"jsonrpc":"2.0","method":"notifications/initialized"}
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"list_regions","arguments":{}}}' | python -m haraj_mcp

Тесты

python tests/test_smoke.py

10 тестов покрывают: регистрацию инструментов (21 инструмент), живой URL version, заголовок sec-ch-ua-platform-version, сохранение опечатки initalChars, реальные переменные поиска, форму компактного сериализатора, валидацию JWT (действительный/просроченный/некорректный), обработку ошибок check_auth и полный сквозной тест через stdio.

Руководство для агента

Справочник "для чего используется каждый инструмент" (и примеры рабочих процессов агента) см. в docs/AGENT_GUIDE.md. В нём объясняется:

  • 21 инструмент, сгруппированный по сценариям использования (обнаружение, лента/поиск, детали объявления, пользователь, аккаунт)

  • Типовые многошаговые сценарии (например, "найди мне выгодное предложение на RTX 4090" → 5 последовательных вызовов инструментов)

  • Шпаргалка по пагинации (какие инструменты используют какой курсор)

  • Примечания по конфиденциальности / безопасности (какие инструменты возвращают чувствительные данные, такие как IBAN и номера мобильных)

  • Фрагменты диалогов, показывающие, как агент вызывает инструменты

Поделитесь docs/AGENT_GUIDE.md с LLM-клиентом (или используйте его как справочник при написании системных промптов).

Структура проекта

haraj-mcp/
├── pyproject.toml
├── README.md
├── .env.example
├── src/haraj_mcp/
│   ├── __init__.py
│   ├── __main__.py        # entry point: `python -m haraj_mcp`
│   ├── server.py         # FastMCP setup, 21 tool registrations
│   ├── tools.py          # the 21 tool implementations
│   └── auth.py           # .env reader + JWT validation
├── haraj/                # GraphQL client (captured from live haraj.com.sa)
│   ├── client.py
│   ├── models.py
│   ├── queries.py        # 20 exact-captured query strings
│   ├── constants.py
│   ├── auth.py
│   └── images.py
└── tests/test_smoke.py

Что изменилось в v0.2.0

В v0.1.0 было 4 инструмента (search_haraj, get_post, list_regions, check_auth), которые я выдумал на основе живой GraphQL-схемы, — многие из поддерживаемых фильтров никогда не использовались реальным сайтом.

v0.2.0 заменяет их на 21 инструмент, повторяющий реальные операции, которые использует haraj.com.sa. Зафиксировано в реальной браузерной сессии 2026-08-17 (219 запросов, 173 POST-запроса GraphQL). Ключевые исправления:

  • search больше не содержит выдуманных фильтров (carExtraInfo, priceRange, userLocation, notTag, authorUsername); только те переменные, которые реально отправляет живой сайт (search, cities, city, tag, tags, page, limit, onlyWithImage, onlyWithVideo, hideShowRooms, orderByPostId, duringDate, near)

  • searchSuggest сохраняет опечатку initalChars живого API (сервер требует её)

  • Параметр version в URL обновлён до 2026-08-11 22 (было 2026-08-03 15)

  • Добавлен заголовок sec-ch-ua-platform-version (отправляется при каждом живом вызове)

  • ViewOptions теперь содержит mustLoginToView (присутствует только в операции posts)

  • Новый инструмент live_streams для не-GraphQL эндпоинта livestream.haraj.com.sa

  • get_post_details теперь использует правильный эндпоинт similarPosts(id:) (вместо хака с использованием ID в качестве ключевого слова)

Available Tools

21 tools
check_authA
Read-onlyIdempotent

Verify the JWT and lastRequestId in .env are still valid. Returns {ok, expires_at, seconds_remaining, user_id} or {ok: false, error} if the JWT is missing or expired.

Inputs: no named parameters.

commentsC
Read-onlyIdempotent

Comment list for a post. Required: post_id. Optional: page, oldest_first (default true).

Inputs: post_id (required), page, oldest_first.

fetch_feedA
Read-onlyIdempotent

Fetch the post feed for a tag (the homepage + category pages). Required: tag (Arabic category name like 'حراج السيارات' or 'حراج الأجهزة'). Optional: city (Arabic region like 'الشرقيه'), cities (list of regions), page (default 0), limit (default 21), before_update_date (Unix seconds cursor — pass the last item's updateDate to get the next page), only_with_image (default true), only_with_video (default false), order_main_by_post_id (default false), full (return full Post objects, default false = compact). Returns {count, has_next_page, view_options, posts}.

Inputs: tag (required), city, full, page, +6 more.

follow_userA

Follow (or unfollow) a user. Required: username. Returns the new is_following state.

Inputs: username (required).

get_post_detailsA
Read-onlyIdempotent

Fetch a post + 3 related groups (similar posts in the same tag/city, similar images, related offers). This is the canonical 'fetch by id' — there is no direct getById operation in the GraphQL API. Required: post_id. full (default true = full similarPosts response).

Inputs: post_id (required), full.

is_following_tagA
Read-onlyIdempotent

True/false whether the authenticated user follows tag.

Inputs: tag (required), city.

is_following_userB
Read-onlyIdempotent

True/false whether the authenticated user follows username.

Inputs: username (required).

live_streamsB
Read-onlyIdempotent

Currently-open haraj live shopping streams. Non-GraphQL REST endpoint. Returns [{id, title, cover_url, streamer, num_messages, num_viewers, started_at}]. limit (default 40; the server caps it).

Inputs: limit.

locker_shipment_offerC
Read-onlyIdempotent

{offerId, isEligible, price} for a post's Locker shipping option. Required: post_id.

Inputs: post_id (required).

notesB
Idempotent

User notifications (the bell icon). set_read (default false) marks them as read on the server.

Inputs: set_read.

outgoing_buy_requestsB
Read-onlyIdempotent

'Buy with confidence' (وساطة) escrow requests the user has placed. Optional: page (default 0).

Inputs: page.

post_contactC
Read-onlyIdempotent

{contactText, contactMobile, shouldEnableWhatsApp} for a post. Required: post_id.

Inputs: post_id (required).

post_like_infoC
Read-onlyIdempotent

{is_like, total, is_following} for a post. Required: post_id.

Inputs: post_id (required).

search_suggestA
Read-onlyIdempotent

Live search-box autocomplete. Returns the top 10 suggestions for a typed prefix. Required: prefix (e.g. 'شاشة'). Optional: tag.

Inputs: prefix (required), tag.

sellers_listC
Read-onlyIdempotent

Sellers for a tag (used by real-estate / business / investment pages). Required: tags (list of Arabic tag names).

Inputs: tags (required), page.

userA
Read-onlyIdempotent

Full user profile (rating, followers, location history, badges). Pass either username (URL-encoded Arabic works) or user_id. rating_summary_only (default false) returns just the rating block.

Inputs: user_id, username, rating_summary_only.

user_mention_suggestionsA
Read-onlyIdempotent

Recent @-mention candidates for the comment / DM composer. Returns [{userId, username, handler}].

Inputs: no named parameters.

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    B3/5.0

    Scored across 21 tools

    Disambiguation5/5

    Each tool targets a clearly distinct resource or action. While several tools return posts (fetch_feed, search, promoted_posts) or relate to users (follow_user, is_following_user, user), the descriptions precisely differentiate their scopes and use cases.

    Naming Consistency3/5

    All names use snake_case, which is consistent, but the grammatical pattern is mixed: some are verb_noun (fetch_feed, get_post_details), some are noun phrases (promoted_posts, post_like_info), and some are is_* predicates (is_following_tag). This inconsistency makes the set less predictable.

    Tool Count3/5

    21 tools is on the high side for a single server, falling into the borderline heavy range per the rubric. Although each tool appears to cover a distinct API feature, the sheer number increases cognitive load and could be consolidated.

    Completeness3/5

    The surface covers many read operations and a few write actions (follow_user, notes set_read), but notable write operations are missing: creating or editing posts, liking/unliking, posting comments, following/unfollowing tags, and sending messages. These gaps limit agent autonomy for core marketplace interactions.

    Maintenance

    ActivityStale
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      C
      quality
      B
      maintenance
      Hosted MCP server for 3926 structured public web-data tools across 488 platform groups, returning clean JSON for search, maps, commerce, social, and finance.
      14
      500
      252 npm
      1
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      A read-only MCP server that gives LLM agents live access to OpenSooq, the largest classifieds marketplace in Kuwait, enabling search, pricing, seller reputation, and deal finding.
      2
      MIT
    • F
      license
      Not graded
      quality
      B
      maintenance
      Remote MCP server for Saudi real estate data from Kite (kite.sa): live rent and sale listings from 20+ Saudi sources, price checks against comparable listings, neighborhood stats, rental yield and development projects. Connect at https://mcp.kite.sa/mcp with OAuth sign-in.
      1
      -
    • A
      license
      Not graded
      quality
      C
      maintenance
      MCP server for the OLX.ba API that enables searching, publishing, editing, and managing listings (ads), including image handling, sponsorships, categories, locations, and user account operations through 36 tools covering all official API endpoints.
      10 npm
      8
      MIT