Skip to main content
Glama
flexible-hotels-mcp-server

flexible-hotels-mcp-server

by sholts2026

flexible-hotels-mcp-server

MCP-сервер (Model Context Protocol), который позволяет ИИ (Claude или любому другому MCP-клиенту) искать гостиничные номера по количеству ночей в гибком диапазоне дат, а не по фиксированной дате заезда/выезда.

Например: «3 ночи в Тель-Авиве, где-то между 1.9 и 20.9» — сервер сканирует все возможные даты заезда в диапазоне, получает реальные цены для каждой из них и возвращает самые выгодные предложения, отсортированные по цене.

Партнёрская модель: это исключительно инструмент сравнения цен — он не собирает платёжные данные и не выполняет бронирование. Каждый результат содержит ссылку (bookingUrl), ведущую на источник (сейчас Booking.com), где пользователь может самостоятельно завершить покупку, если вообще захочет.

Источник данных: Amadeus for Developers — ведущее бесплатное API в сфере туризма, с полностью бесплатной тестовой средой (test) без необходимости вводить банковскую карту.

Что здесь есть

Четыре инструмента (tools), доступных ИИ:

Инструмент

Что он делает

flexible_hotels_resolve_city_code

Преобразует произвольное название города («Тель-Авив») в код IATA («TLV»)

flexible_hotels_list_hotels_in_city

Возвращает список отелей (и их идентификаторов) в указанном городе

flexible_hotels_search_flexible_offers

Основной инструмент — гибкий поиск по количеству ночей в диапазоне дат, со ссылкой на бронирование для каждого результата

flexible_hotels_get_offer_details

Полные детали и актуальная цена для конкретного предложения + ссылка на бронирование

Логика «гибкого поиска» реализована в src/services/hotelSearch.ts: поскольку Amadeus (как и любой другой провайдер) поддерживает только один фиксированный диапазон дат на запрос, сервер сам перебирает каждую возможную дату заезда в заданном окне, вызывает API соответствующим образом и объединяет результаты. Ссылка для каждого результата формируется в src/services/affiliateLink.ts.

Related MCP server: Amadeus Hotel API MCP Server

Установка

1. Получите бесплатный API-ключ (2 минуты, без банковской карты):

  1. Зарегистрируйтесь на https://developers.amadeus.com/register

  2. После подтверждения создайте «New App» в My Self-Service Workspace

  3. Вы получите API Key и API Secret — это будут AMADEUS_CLIENT_ID и AMADEUS_CLIENT_SECRET

Это среда test (sandbox) — полностью бесплатная, с щедрой месячной квотой и ограничением скорости около 10 запросов в секунду. Она охватывает сотни тысяч отелей по всему миру с реальными данными (хотя иногда частичными/кэшированными). Чтобы перейти на полные живые данные в будущем, можно запросить production-доступ у Amadeus (платный) и изменить AMADEUS_ENV=production.

2. Локальная установка:

npm install
cp .env.example .env
# ערכו את .env והכניסו את המפתחות שקיבלתם
npm run build

3. Проверка, что всё работает (без ущерба для квоты — не отправляет реальные запросы в Amadeus):

npm test

Запуск

npm start

По умолчанию сервер работает через stdio (подходит для локального подключения к клиентам вроде Claude Desktop). Чтобы запустить его как удалённый HTTP-сервер (для подключения из Claude.ai / Cowork как «custom connector», или из любого другого удалённого MCP-клиента):

TRANSPORT=http PORT=3000 npm start

Подключение как «плагина» к ИИ

Claude Desktop (локально)

Добавьте в файл настроек claude_desktop_config.json:

{
  "mcpServers": {
    "flexible-hotels": {
      "command": "node",
      "args": ["/נתיב-מלא/ל/flexible-hotels-mcp-server/dist/index.js"],
      "env": {
        "AMADEUS_CLIENT_ID": "המפתח-שלכם",
        "AMADEUS_CLIENT_SECRET": "הסוד-שלכם"
      }
    }
  }
}

После перезапуска Claude Desktop ИИ сможет напрямую вызывать эти инструменты в диалоге.

Удалённое подключение (Claude.ai / Cowork / любой другой клиент)

Чтобы продукт был доступен как «плагин» для нескольких пользователей без необходимости каждому запускать код локально, нужно развернуть (deploy) сервер в режиме TRANSPORT=http на каком-либо сервере/хосте, а затем подключить адрес https://ваш-домен/mcp как custom MCP connector в настройках клиента.

Railway (рекомендуется, если у вас уже есть аккаунт + установлен CLI):

cd flexible-hotels-mcp-server
railway login          # רק אם עוד לא מחוברים — פותח דפדפן לאישור
railway up --new -y --detach --json   # יוצר פרויקט חדש, מעלה את הקוד ומפעיל build מה-Dockerfile
railway variable set AMADEUS_CLIENT_ID=המפתח-שלכם --skip-deploys
railway variable set AMADEUS_CLIENT_SECRET=הסוד-שלכם --skip-deploys
railway variable set AMADEUS_ENV=test
railway domain          # מפיק כתובת ציבורית כמו https://xxx.up.railway.app

Сервер запускается (и проходит health check) также до настройки ключей Amadeus — инструменты поиска просто будут возвращать понятную ошибку, пока не будут заданы реальные ключи и не произойдёт автоматический редеплой.

Render: файл render.yaml в корне проекта готов как Blueprint — подключаете repo к Render, «New» -> «Blueprint» и заполняете AMADEUS_CLIENT_ID/AMADEUS_CLIENT_SECRET в интерфейсе (см. комментарии внутри файла).

Обратите внимание во всех вариантах: AMADEUS_CLIENT_ID/AMADEUS_CLIENT_SECRET должны быть переменными окружения, заданными на хост-сервере, и никогда не должны быть записаны в коде.

Пример использования (что «видит» ИИ)

User: תמצא לי 3 לילות בתל אביב, איפשהו בין ה-1 ל-20 בספטמבר, לזוג.

AI calls: flexible_hotels_resolve_city_code(keyword="Tel Aviv")
  -> TLV

AI calls: flexible_hotels_search_flexible_offers(
  city_code="TLV", nights=3,
  earliest_check_in="2026-09-01", latest_check_in="2026-09-20",
  adults=2
)
  -> רשימת עסקאות ממוינת מהזולה ביותר, עם תאריך צ'ק-אין/אאוט מדויק וקישור הזמנה לכל אחת

User: מעולה, תראה לי את הפרטים המלאים של האופציה הכי זולה.

AI calls: flexible_hotels_get_offer_details(offer_id="...")
  -> מחיר מעודכן + קישור לחיצה שמעביר את המשתמש להשלים את ההזמנה באתר המקורי

Бизнес-модель: партнёрская программа

Этот сервер не выполняет бронирования и не касается платёжных данных ни на каком этапе — это намеренно, как из соображений простоты/безопасности, так и потому, что так работают магазины приложений (например, ChatGPT App Directory), которые требуют «external checkout» и запрещают сбор номеров банковских карт через сам инструмент.

Как это работает на практике:

  1. Сервер находит реальные цены через Amadeus (бесплатно).

  2. Для каждого результата формируется ссылка на страницу поиска на Booking.com с уже заполненными названием отеля и датами (src/services/affiliateLink.ts).

  3. Если вы зарегистрируетесь в Booking.com Affiliate Partner Program (бесплатно, самостоятельная регистрация, без специального одобрения) и получите aid, его можно задать как переменную окружения BOOKING_AFFILIATE_ID — тогда каждая ссылка будет содержать ваш партнёрский идентификатор, и вы сможете получать комиссию за бронирования, совершённые по ссылке.

  4. Без BOOKING_AFFILIATE_ID ссылки по-прежнему полностью работают — просто не приносят вознаграждения.

Это именно то «просто зарегистрироваться», о котором вы просили: однократная регистрация в партнёрской программе Booking.com (не в Amadeus, не в Railway) — всё, что нужно, чтобы ссылки начали приносить доход.

Известные ограничения

  • Бесплатная квота: среда test Amadeus ограничена месячной квотой и скоростью запросов (~10/сек). Гибкий поиск по окну из N дней отправляет до N запросов (с небольшой задержкой между ними) — большое окно = более медленный поиск. Окно ограничено 30 днями на один поиск для защиты квоты.

  • Количество отелей: по умолчанию проверяется до 15 отелей в городе на каждую дату (можно увеличить до 30 через max_hotels или сузить до конкретных hotelIds).

  • Данные sandbox: в среде test наиболее надёжное покрытие — в крупных городах (например, NYC, LON, PAR). В небольших городах может возвращаться мало отелей или ничего — это решается переходом на production.

  • Ссылки на бронирование формируют поиск на Booking.com по названию отеля и датам — это не прямая глубокая ссылка (deep link) на конкретный номер, потому что Amadeus её не предоставляет. В большинстве случаев нужный отель появляется первым в результатах.

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

src/
├── index.ts              # נקודת כניסה, רישום השרת והכלים
├── constants.ts           # קבועים (URLs, מגבלות)
├── types.ts                # טיפוסי TypeScript משותפים
├── services/
│   ├── amadeusClient.ts   # קליינט HTTP מאומת ל-Amadeus (OAuth2, endpoints)
│   ├── hotelSearch.ts     # הלוגיקה של חיפוש גמיש (הליבה)
│   ├── affiliateLink.ts   # בניית קישור ההזמנה (Booking.com + aid אופציונלי)
│   └── format.ts           # פורמט markdown לתשובות
├── schemas/
│   └── schemas.ts          # סכמות Zod לכל כלי
├── tools/                  # רישום כל כלי MCP
└── test/
    └── hotelSearch.test.ts # בדיקות יחידה ללוגיקת החיפוש (ללא צורך במפתח API)
scripts/
└── smoke-test-tools.mjs    # בדיקת עשן שמפעילה את השרת האמיתי ומוודאת שכל הכלים נחשפים כראוי

Возможные дальнейшие расширения

  • Гибкий диапазон ночей (min/max nights), а не только фиксированное число.

  • Кэширование результатов поиска для экономии квоты.

  • Подключение дополнительных партнёрских программ (Expedia, Agoda и т.д.) и отображение нескольких ссылок на разные источники для каждого результата, а не только Booking.com.

  • Переход на платного провайдера (например, StayAPI / RapidAPI) для более широкого покрытия поставщиков по мере роста продукта.

  • Регистрация в магазине приложений ChatGPT (Apps SDK) — отдельный проект со своими требованиями (аккаунт разработчика OpenAI, политика конфиденциальности, демо-аккаунт для тестирования); текущая партнёрская модель (без сбора банковских карт) уже соответствует их требованию «external checkout».

Available Tools

4 tools
flexible_hotels_get_offer_detailsGet Hotel Offer DetailsA
Read-onlyIdempotent

Fetch full, up-to-date details for a single hotel offer previously returned by search_flexible_hotel_offers, including its cancellation policy.

Offer prices can shift between search and booking, so call this before telling the user a final price or sending them to book. Like the rest of this server, it never collects payment details — it only reads offer details and returns a click-through link to the real site.

Args:

  • offer_id (string): the offerId returned by search_flexible_hotel_offers

  • response_format ('markdown' | 'json'): output format (default markdown)

Returns: hotel name, confirmed price, check-in/check-out dates, room description, board type, cancellation deadline, and a booking link to the real site.

Examples:

  • Use when: the user picked one result from search_flexible_hotel_offers and wants to double-check the price before going to book

  • Don't use when: you don't have an offer_id yet — run search_flexible_hotel_offers first

Error Handling:

  • Returns "No details found for this offer id" if the offer expired (Amadeus test-environment offers are short-lived)

Inputs: offer_id (required), response_format.

flexible_hotels_list_hotels_in_cityList Hotels in a CityA
Read-onlyIdempotent

List hotels (with their Amadeus hotelId) located in a given IATA city code, optionally within a radius.

Use this to discover hotelIds you can pass into search_flexible_hotel_offers via hotel_ids, e.g. to restrict a search to a specific neighborhood or a shortlist of hotels the user already mentioned by name. It does NOT return prices or availability — only hotel identity/location. This tool does not modify any data.

Args:

  • city_code (string): 3-letter IATA city code, e.g. "TLV", "PAR" (use resolve_city_code to find it)

  • radius_km (number): search radius around the city center in km, 1-300 (default 20)

  • max_results (number): max hotels to return, 1-30 (default 20)

  • response_format ('markdown' | 'json'): output format (default markdown)

Returns: hotel name, hotelId, chain code, and coordinates for each matching hotel.

Examples:

  • Use when: "only search hotels near the Tel Aviv beachfront" -> narrow radius_km, then pass returned hotelIds to search_flexible_hotel_offers

  • Don't use when: you just want priced offers — use search_flexible_hotel_offers directly, it looks up hotels automatically

Error Handling:

  • Returns "No hotels found for city code ..." if the city_code is invalid or has no coverage in this environment

Inputs: city_code (required), radius_km, max_results, response_format.

flexible_hotels_resolve_city_codeResolve City Name to IATA City CodeA
Read-onlyIdempotent

Look up the 3-letter IATA city code for a free-text city name (e.g. "Tel Aviv" -> "TLV", "Paris" -> "PAR").

Every other tool in this server (list_hotels_in_city, search_flexible_hotel_offers) requires an IATA city_code, so this is normally the first tool to call when the user names a city.

Args:

  • keyword (string): city name or the start of it, e.g. "Tel Aviv", "New York", "Par"

  • max_results (number): max cities to return, 1-20 (default 10)

  • response_format ('markdown' | 'json'): output format (default markdown)

Returns: matching cities with their name, iataCode, and country code.

Examples:

  • Use when: "find flexible hotel deals in Tel Aviv" -> call with keyword="Tel Aviv" first to get city_code="TLV"

  • Don't use when: you already have a 3-letter IATA city code

Error Handling:

  • Returns "No cities found matching ..." if the keyword doesn't match anything

Inputs: keyword (required), max_results, response_format.

flexible_hotels_search_flexible_offersSearch Hotel Offers by Number of Nights (Flexible Dates)A
Read-only

Find the cheapest hotel offers for a fixed NUMBER OF NIGHTS across a WINDOW of possible check-in dates, instead of a single fixed check-in/check-out date pair. This is the core tool of this server.

For example: "3 nights in Tel Aviv, sometime between Sep 1 and Sep 20" is expressed as nights=3, earliest_check_in="2026-09-01", latest_check_in="2026-09-20". The tool scans every possible check-in date in that window (each implying checkout = check-in + nights), fetches real priced offers for each, and returns the cheapest options found, sorted by price — so the caller can see which exact dates are the best deal.

This does NOT search by a single fixed date — for that, just set earliest_check_in = latest_check_in. This is an AFFILIATE search tool: it never collects payment details or creates a booking. Each returned offer includes a bookingUrl — a link to the real hotel/OTA listing where the guest can complete the purchase themselves, if they choose to. Data comes from the Amadeus for Developers hotel API (free test/sandbox environment by default).

Args:

  • city_code (string): 3-letter IATA city code, e.g. "TLV" (use resolve_city_code to find it from a name)

  • nights (number): exact stay length in nights, 1-28

  • earliest_check_in / latest_check_in (YYYY-MM-DD): the flexible window of possible check-in dates, at most 30 days apart

  • hotel_ids (string[], optional): restrict to specific Amadeus hotelIds (from list_hotels_in_city)

  • max_hotels (number): if hotel_ids is omitted, how many hotels in the city to auto-check (default 15)

  • adults (number): guests per room (default 2)

  • room_quantity (number): rooms to book (default 1)

  • currency (string, optional): 3-letter ISO currency code, e.g. "USD"

  • max_results (number): how many offers to return, cheapest first (default 10)

  • response_format ('markdown' | 'json'): output format (default markdown)

Returns: For JSON format: { "cityCode": string, "nights": number, "earliestCheckIn": string, "latestCheckIn": string, "datesScanned": number, "datesWithOffers": number, "datesSkipped": [{ "date": string, "reason": string }], "hotelsConsidered": number, "offers": [{ "offerId", "hotelId", "hotelName", "checkInDate", "checkOutDate", "nights", "currency", "totalPrice", "boardType", "roomDescription", "bookingUrl" }, ...], "cheapest": <same shape as one offer, or null>, "truncated": boolean }

Examples:

  • Use when: "find me the cheapest 3-night stay in Paris sometime in the next month"

  • Use when: "is it cheaper to go for a long weekend early or late September?"

  • Don't use when: the user already has exact fixed dates in mind — a single-date search is faster (set earliest_check_in = latest_check_in), though this tool still works for that case.

Error Handling:

  • Returns an error if the date window exceeds 30 days — narrow it and retry

  • Individual dates that error out (e.g. sandbox has no data) are listed in datesSkipped rather than failing the whole search

Inputs: nights (required), city_code (required), latest_check_in (required), earliest_check_in (required), +7 more.

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    A4.6/5.0

    Scored across 4 tools

    Disambiguation5/5

    Each tool has a clearly distinct purpose: resolving city names to codes, listing hotels, searching flexible offers, and getting offer details. There is no overlap or ambiguity between them; the workflow is linear and obvious.

    Naming Consistency5/5

    All tool names follow the same pattern: 'flexible_hotels_' prefix followed by a verb_noun combination (resolve_city_code, list_hotels_in_city, search_flexible_offers, get_offer_details). The verbs are consistent and descriptive, making the API predictable.

    Tool Count4/5

    Four tools is on the lower end but well-scoped for a focused flexible hotel search server. Each tool is necessary and covers a distinct step in the workflow; there is no bloat or redundancy.

    Completeness5/5

    The server covers the complete user journey: resolve city → optionally list hotels → search offers → get details. For an affiliate-focused read-only service, the surface is complete with no obvious missing operations or dead ends.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      Enables AI agents to search, browse, and book hotels from a database of 2 million properties worldwide. Provides comprehensive hotel search capabilities with location lookup, filtering by amenities, detailed property information, and integrated booking functionality.
      6
      1
      ISC
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables AI agents to search, compare, and book hotels with real-time pricing and availability, supporting multiple location types, star ratings, and price filters.
      12
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI agents to search and book hotels globally with real-time pricing and inventory from over 2 million properties.
      46
      MIT