haraj-mcp
haraj-mcp
Un servidor de Model Context Protocol (MCP) para haraj.com.sa, el mercado de anuncios clasificados más grande de Arabia Saudí.
Este servidor expone 21 herramientas a cualquier agente compatible con MCP (Claude Desktop, Cursor, opencode, Zed, etc.) para que pueda buscar y obtener listados del mercado en tiempo real, sin necesidad de copiar y pegar comandos curl.
Todas las herramientas replican las operaciones reales de haraj.com.sa capturadas desde una sesión de navegador en vivo (2026-08-17). Sin filtros inventados: cada argumento coincide exactamente con lo que el frontend real envía en sus llamadas GraphQL.
Claude Desktop / Cursor / opencode
│
│ MCP (JSON-RPC over stdio)
▼
┌──────────────┐
│ haraj-mcp │ ── HTTPS ──▶ graphql.haraj.com.sa
│ (Python) │ + livestream.haraj.com.sa
└──────────────┘Herramientas expuestas (21)
Descubrimiento
Herramienta | Propósito |
| Términos de búsqueda más populares (7 días por defecto) |
| Autocompletado del cuadro de búsqueda en vivo (top 10) |
| Ciudades con recuentos para una etiqueta determinada |
| Transmisiones en vivo de compras de haraj actualmente abiertas |
Feed / búsqueda
Herramienta | Propósito |
| Feed basado en etiquetas (página de inicio + páginas de categoría). |
| Búsqueda por palabra clave. |
| Carrusel de publicaciones promocionadas para una etiqueta |
| Vendedores por etiqueta (inmobiliario, etc.) |
Detalle de publicación
Herramienta | Propósito |
| Publicación + 3 grupos relacionados (a través del endpoint real |
|
|
| Lista de comentarios |
|
|
|
|
Usuario
Herramienta | Propósito |
| Perfil completo (calificación, seguidores, historial de ubicaciones, insignias) |
| booleano |
| Mutación: alterna el seguimiento |
| Para menciones @ |
Cuenta
Herramienta | Propósito |
| Notificaciones (el icono de la campana) |
| Historial de depósito en garantía de "Buy with confidence" |
| booleano |
| Verifica que las credenciales de |
Para fetch_feed, promoted_posts y search, pasa full=True para obtener el objeto Post completo en lugar de un resumen compacto. El resumen compacto tiene estas claves:
{
"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
Instalación
cd /mnt/W/Desktop/Software/haraj-mcp
pip install -e .Esto instala el script de consola haraj-mcp en tu PATH.
Configurar autenticación
cp .env.example .env
# Edit .env and paste your HARAJ_JWT and LAST_REQUEST_ID.Cómo obtener valores nuevos (expiran cada ~10 días):
Abre https://haraj.com.sa en Chrome e inicia sesión.
F12 → pestaña Network → haz clic en cualquier solicitud de
graphql.haraj.com.sa.En Headers, copia
authorization(empieza porBearer eyJ…) ylastRequestId.Pégalo en
.envy reinicia el servidor MCP.
Puedes verificarlo con check_auth: devuelve el claim exp del JWT y seconds_remaining.
Conexión con tu cliente MCP
opencode / Claude Desktop / Cursor
Añade esto a la configuración MCP de tu cliente (normalmente ~/.config/opencode/opencode.json, ~/Library/Application Support/Claude/claude_desktop_config.json o ~/.cursor/mcp.json):
{
"mcpServers": {
"haraj": {
"command": "haraj-mcp",
"cwd": "/mnt/W/Desktop/Software/haraj-mcp"
}
}
}El servidor lee .env desde cwd, por lo que los secretos permanecen en el directorio del proyecto y no se filtran a la configuración MCP de tu cliente.
Ubicación personalizada de .env
Define HARAJ_MCP_ENV=/path/to/.env en el bloque env de la configuración MCP.
Ejemplos de prompts para agentes
Una vez conectado, tu agente puede responder:
"¿Qué es tendencia en haraj hoy?"
"Obtén las últimas 20 publicaciones en
حراج السيارات(la categoría de coches)."
"Busca en haraj
RTX 4090en la última semana (during_date=1week)."
"Obtén el perfil del vendedor y todos sus listados actuales para post_id=185354313."
"¿Qué tarifa de envío pago si compro esta publicación a través de Locker?"
"¿Qué está escribiendo la gente en el cuadro de búsqueda después de
شاشة?"
"Enumera todas las transmisiones de compras en vivo abiertas ahora mismo."
Ejecutar sin un cliente MCP (depuración)
Envía mensajes JSON-RPC directamente al servidor:
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_mcpPruebas
python tests/test_smoke.py10 pruebas cubren: registro de herramientas (21 herramientas), URL version en vivo, cabecera sec-ch-ua-platform-version, preservación del error tipográfico initalChars, variables de búsqueda reales, forma del serializador compacto, validación de JWT (válido/expirado/malformado), manejo de errores de check_auth y una prueba integral de stdio de extremo a extremo.
Guía para agentes
Para una referencia por herramienta de "para qué se usa esto" (y ejemplos de flujos de trabajo de agentes), consulta docs/AGENT_GUIDE.md. Explica:
Las 21 herramientas organizadas por caso de uso (descubrimiento, feed/búsqueda, detalle de publicación, usuario, cuenta)
Flujos de trabajo comunes de varios pasos (p. ej., "encuéntrame una oferta de un RTX 4090" → 5 llamadas a herramientas encadenadas)
Chuleta de paginación (qué herramientas usan cada cursor)
Notas de privacidad / seguridad (qué herramientas devuelven datos sensibles como IBANs y números de móvil)
Fragmentos de conversación que muestran al agente llamando a las herramientas
Comparte docs/AGENT_GUIDE.md con el cliente LLM (o úsalo como referencia al escribir prompts de sistema).
Estructura del proyecto
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.pyQué cambió en v0.2.0
v0.1.0 tenía 4 herramientas (search_haraj, get_post, list_regions, check_auth) que había inventado a partir del esquema GraphQL en vivo; muchos de los filtros admitidos nunca los usaba el sitio real.
v0.2.0 las reemplaza con 21 herramientas que replican las operaciones reales que usa haraj.com.sa. Capturadas de una sesión de navegador real el 2026-08-17 (219 solicitudes, 173 POST de GraphQL). Los cambios clave:
searchya no tiene filtros inventados (carExtraInfo,priceRange,userLocation,notTag,authorUsername); solo las variables que el sitio en vivo realmente envía (search,cities,city,tag,tags,page,limit,onlyWithImage,onlyWithVideo,hideShowRooms,orderByPostId,duringDate,near)searchSuggestconserva el error tipográficoinitalCharsdel wire en vivo (el servidor lo requiere)El parámetro de URL
versionse actualizó a2026-08-11 22(antes2026-08-03 15)Se añadió la cabecera
sec-ch-ua-platform-version(se envía en cada llamada en vivo)ViewOptionstienemustLoginToView(solo presente en la operaciónposts)Nueva herramienta
live_streamspara el endpoint no GraphQLlivestream.haraj.com.saget_post_detailsahora usa el endpoint correctosimilarPosts(id:)(no el truco de usar el ID como palabra clave)
Available Tools
21 toolscheck_authARead-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.
commentsCRead-onlyIdempotent
Comment list for a post. Required: post_id. Optional: page, oldest_first (default true).
Inputs: post_id (required), page, oldest_first.
fetch_feedARead-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_detailsARead-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_tagARead-onlyIdempotent
True/false whether the authenticated user follows tag.
Inputs: tag (required), city.
is_following_userBRead-onlyIdempotent
True/false whether the authenticated user follows username.
Inputs: username (required).
live_streamsBRead-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_offerCRead-onlyIdempotent
{offerId, isEligible, price} for a post's Locker shipping option. Required: post_id.
Inputs: post_id (required).
notesBIdempotent
User notifications (the bell icon). set_read (default false) marks them as read on the server.
Inputs: set_read.
outgoing_buy_requestsBRead-onlyIdempotent
'Buy with confidence' (وساطة) escrow requests the user has placed. Optional: page (default 0).
Inputs: page.
post_contactCRead-onlyIdempotent
{contactText, contactMobile, shouldEnableWhatsApp} for a post. Required: post_id.
Inputs: post_id (required).
post_like_infoCRead-onlyIdempotent
{is_like, total, is_following} for a post. Required: post_id.
Inputs: post_id (required).
promoted_postsBRead-onlyIdempotent
Fetch the promoted-post carousel for a tag. Required: tag. Optional: city. Returns {count, posts}.
Inputs: tag (required), city, full.
searchARead-onlyIdempotent
Search haraj by keyword. Required: keyword. Optional: cities (list), city, tag, tags (list), page, limit, only_with_image (default true), only_with_video (default false), hide_show_rooms (default false), order_by_post_id (default false), during_date ('1days'|'3days'|'1week'|'1months'), near ('@lat,lon' e.g. '@26.4336,50.1116'), full (default false = compact). Returns {keyword, count, has_next_page, view_options, posts}.
Inputs: keyword (required), tag, city, full, +10 more.
search_suggestARead-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_listCRead-onlyIdempotent
Sellers for a tag (used by real-estate / business / investment pages). Required: tags (list of Arabic tag names).
Inputs: tags (required), page.
trending_keywordsBRead-onlyIdempotent
Top trending search terms over the last N days. range_in_days (default 7). Returns [{keyword, score}].
Inputs: range_in_days.
userARead-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_suggestionsARead-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
Scored across 21 tools
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.
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.
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.
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
Related MCP Connectors
All HasData scraping tools in one MCP server: Google, TikTok, Instagram, maps, e-commerce and more.
Hosted MCP server for DataLikers — Instagram & TikTok data API. 51 tools: Instagram user search by demographics (gender/age/race/country/city), profiles, bulk lookup, engagement, posts & reels, comments, hashtags, locations, stories, highlights, music, business accounts, top users; TikTok users, videos, comments, hashtags, playlists and top charts. Streamable HTTP, Bearer API key. Free tier: 100 requests on signup at https://datalikers.com/p/1by27bwg
17 data tools in one MCP server, run on Apify: Google Shopping, Flights, Hotels, News, Images, Videos, Ads Transparency, Jobs and Trends; YouTube transcripts; AI visibility checks; Google Maps leads; App Store and Google Play reviews. Pay per result. Sign in with Apify (OAuth) or an API token.
One MCP server for 180+ live web-data APIs returning clean JSON from sites that block scrapers.
Related MCP Servers
AlicenseCqualityBmaintenanceHosted MCP server for 3926 structured public web-data tools across 488 platform groups, returning clean JSON for search, maps, commerce, social, and finance.14500252 npm1MIT- AlicenseNot gradedqualityDmaintenanceA 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.2MIT
- FlicenseNot gradedqualityBmaintenanceRemote 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-
- AlicenseNot gradedqualityCmaintenanceMCP 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 npm8MIT