En este post vamos a ver cómo desarrollar un servidor y un cliente MCP con elicitación. Y si a ti también te pasa que no tienes ni idea de lo que es elicitación, no te preocupes, que ya te lo cuento. Elicitación es cuando el servidor necesita información por parte del usuario, así que a través del cliente se la pide al usuario
Servidor MCP con elicitación
Vamos a crear un servidor MCP que actúa como un buscador de viajes. Así que irá pidiéndole datos al usuario. Todos los posibles viajes van a estar guardados en una variable, no va a ser un buscador real, es un ejemplo para mostrar la elicitación.
Implementación del servidor con elicitación
Creamos dos clases de tipo enum
para definir los diferentes tipos de viajes y los rangos de presupuesto.
Creamos un diccionario para guardar todos los posibles viajes.
Creamos una función para extraer el valor de la respuesta de la elicitación.
Y por último, implementamos la función intelligent_travel_booking_agent
que es la tool
que va a ir pidiendo los datos al usuario y va a ir guardando los resultados en una variable.
La función va mandando las preguntas al cliente, para que el cliente se las pueda mandar al usuario. El usuario responderá y el cliente mandará la respuesta al servidor.
En el momento en el que tenga los datos necesarios del cliente, le "buscará" el viaje que mejor se adapte a sus necesidades.
Crear entorno virtual del servidor
Primero creamos la carpeta donde lo vamos a desarrollar
!mkdir MCP_elicitation_serverCopied
Creamos el entorno con uv
!cd MCP_elicitation_server && uv init .Copied
Initialized project `mcp-elicitation-server` at `/Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_server`
Lo iniciamos
!cd MCP_elicitation_server && uv venvCopied
Using CPython 3.12.8Creating virtual environment at: .venvActivate with: source .venv/bin/activate
Instalamos las librerías necesarias
!cd MCP_elicitation_server && uv add fastmcpCopied
Resolved 64 packages in 210ms⠙ Preparing packages... (0/11) ⠋ Preparing packages... (0/0)⠙ Preparing packages... (0/11)------------- 0 B/68.03 KiB⠙ Preparing packages... (0/11)------------- 14.88 KiB/68.03 KiB⠙ Preparing packages... (0/11)------------------ 14.88 KiB/68.03 KiBjsonschema-specifications ------------------------------ 0 B/18.00 KiB⠙ Preparing packages... (0/11)------------------ 14.88 KiB/68.03 KiBjsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiB⠙ Preparing packages... (0/11)------------------ 14.88 KiB/68.03 KiBjsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiB⠙ Preparing packages... (0/11)------------------ 14.88 KiB/68.03 KiBjsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiB⠙ Preparing packages... (0/11)------------------ 14.88 KiB/68.03 KiBjsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiBmore-itertools ------------------------------ 14.88 KiB/68.03 KiB⠙ Preparing packages... (0/11)------------------ 0 B/115.37 KiBjsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiBmore-itertools ------------------------------ 14.88 KiB/68.03 KiB⠙ Preparing packages... (0/11)------------------ 14.89 KiB/115.37 KiBjsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiBmore-itertools ------------------------------ 30.88 KiB/68.03 KiB⠙ Preparing packages... (0/11)------------------ 14.89 KiB/115.37 KiBjsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiBmore-itertools ------------------------------ 46.88 KiB/68.03 KiB⠙ Preparing packages... (0/11)------------------ 14.89 KiB/115.37 KiBjsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiBmore-itertools ------------------------------ 62.88 KiB/68.03 KiB⠙ Preparing packages... (0/11)------------------ 14.89 KiB/115.37 KiBjsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiBmore-itertools ------------------------------ 68.03 KiB/68.03 KiB⠙ Preparing packages... (0/11)------------------ 14.89 KiB/115.37 KiBjsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiBmore-itertools ------------------------------ 68.03 KiB/68.03 KiB⠙ Preparing packages... (0/11)------------------ 14.89 KiB/115.37 KiBjsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiBmore-itertools ------------------------------ 68.03 KiB/68.03 KiB⠙ Preparing packages... (0/11)------------------ 14.89 KiB/115.37 KiBjsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiBmore-itertools ------------------------------ 68.03 KiB/68.03 KiB⠙ Preparing packages... (0/11)------------------ 14.89 KiB/115.37 KiBjsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiBmore-itertools ------------------------------ 68.03 KiB/68.03 KiBpycparser ------------------------------ 14.89 KiB/115.37 KiB⠙ Preparing packages... (0/11)------------------ 0 B/434.43 KiBjsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiBstarlette ------------------------------ 14.89 KiB/72.01 KiBcyclopts ------------------------------ 0 B/84.13 KiBpycparser ------------------------------ 30.89 KiB/115.37 KiBcffi ------------------------------ 14.92 KiB/176.80 KiB⠙ Preparing packages... (0/11)------------------ 0 B/434.43 KiBjsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiBstarlette ------------------------------ 14.89 KiB/72.01 KiBcyclopts ------------------------------ 0 B/84.13 KiBpycparser ------------------------------ 46.89 KiB/115.37 KiBcffi ------------------------------ 14.92 KiB/176.80 KiB⠙ Preparing packages... (0/11)------------------ 0 B/434.43 KiBstarlette ------------------------------ 14.89 KiB/72.01 KiBcyclopts ------------------------------ 0 B/84.13 KiBpycparser ------------------------------ 78.89 KiB/115.37 KiBmcp ------------------------------ 0 B/159.97 KiBcffi ------------------------------ 14.92 KiB/176.80 KiBdnspython ------------------------------ 0 B/323.33 KiBpydantic ------------------------------ 0 B/434.43 KiB⠙ Preparing packages... (0/11)------------------ 0 B/6.71 MiBstarlette ------------------------------ 46.89 KiB/72.01 KiBcyclopts ------------------------------ 32.00 KiB/84.13 KiBmcp ------------------------------ 32.00 KiB/159.97 KiBcffi ------------------------------ 63.62 KiB/176.80 KiBdnspython ------------------------------ 46.78 KiB/323.33 KiBpydantic ------------------------------ 32.87 KiB/434.43 KiB⠙ Preparing packages... (0/11)------------------ 30.88 KiB/6.71 MiBcyclopts ------------------------------ 59.40 KiB/84.13 KiBmcp ------------------------------ 64.00 KiB/159.97 KiBcffi ------------------------------ 63.62 KiB/176.80 KiBdnspython ------------------------------ 46.78 KiB/323.33 KiBpydantic ------------------------------ 62.42 KiB/434.43 KiB⠙ Preparing packages... (0/11)------------------ 46.88 KiB/6.71 MiBmcp ------------------------------ 96.00 KiB/159.97 KiBcffi ------------------------------ 127.62 KiB/176.80 KiBfastmcp ------------------------------ 30.89 KiB/306.67 KiBdnspython ------------------------------ 110.89 KiB/323.33 KiBpydantic ------------------------------ 154.40 KiB/434.43 KiB⠙ Preparing packages... (0/11)------------------ 78.88 KiB/6.71 MiBmcp ------------------------------ 159.97 KiB/159.97 KiBfastmcp ------------------------------ 94.89 KiB/306.67 KiBdnspython ------------------------------ 206.89 KiB/323.33 KiBpydantic ------------------------------ 222.42 KiB/434.43 KiB⠙ Preparing packages... (0/11)------------------ 122.63 KiB/6.71 MiBmcp ------------------------------ 159.97 KiB/159.97 KiBfastmcp ------------------------------ 110.89 KiB/306.67 KiBdnspython ------------------------------ 222.89 KiB/323.33 KiBpydantic ------------------------------ 238.42 KiB/434.43 KiB⠙ Preparing packages... (0/11)------------------ 142.88 KiB/6.71 MiBfastmcp ------------------------------ 110.89 KiB/306.67 KiBdnspython ------------------------------ 222.89 KiB/323.33 KiBpydantic ------------------------------ 238.42 KiB/434.43 KiB⠙ Preparing packages... (0/11)------------------ 411.17 KiB/6.71 MiBfastmcp ------------------------------ 206.68 KiB/306.67 KiBdnspython ------------------------------ 254.89 KiB/323.33 KiBpydantic ------------------------------ 318.10 KiB/434.43 KiB⠙ Preparing packages... (0/11)[2m--------------- 3.25 MiB/6.71 MiBfastmcp ------------------------------ 222.89 KiB/306.67 KiBdnspython ------------------------------ 270.89 KiB/323.33 KiB⠙ Preparing packages... (0/11)-------------- 366.42 KiB/434.43 KiBfastmcp ------------------------------ 238.89 KiB/306.67 KiBdnspython ------------------------------ 270.89 KiB/323.33 KiB⠹ Preparing packages... (8/11)-------------- 382.42 KiB/434.43 KiBfastmcp ------------------------------ 254.89 KiB/306.67 KiB⠹ Preparing packages... (8/11)-------------- 286.89 KiB/323.33 KiBPrepared 11 packages in 212msInstalled 61 packages in 149ms+ annotated-types==0.7.0+ anyio==4.10.0+ attrs==25.3.0+ authlib==1.6.3+ certifi==2025.8.3+ cffi==2.0.0+ charset-normalizer==3.4.3+ click==8.2.1+ cryptography==45.0.7+ cyclopts==3.24.0+ dnspython==2.8.0+ docstring-parser==0.17.0+ docutils==0.22+ email-validator==2.3.0+ exceptiongroup==1.3.0+ fastmcp==2.12.3+ h11==0.16.0+ httpcore==1.0.9+ httpx==0.28.1+ httpx-sse==0.4.1+ idna==3.10+ isodate==0.7.2+ jsonschema==4.25.1+ jsonschema-path==0.3.4+ jsonschema-specifications==2025.9.1+ lazy-object-proxy==1.12.0+ markdown-it-py==4.0.0+ markupsafe==3.0.2+ mcp==1.14.0+ mdurl==0.1.2+ more-itertools==10.8.0+ openapi-core==0.19.5+ openapi-pydantic==0.5.1+ openapi-schema-validator==0.6.3+ openapi-spec-validator==0.7.2+ parse==1.20.2+ pathable==0.4.4+ pycparser==2.23+ pydantic==2.11.9+ pydantic-core==2.33.2+ pydantic-settings==2.10.1+ pygments==2.19.2+ pyperclip==1.9.0+ python-dotenv==1.1.1+ python-multipart==0.0.20+ pyyaml==6.0.2+ referencing==0.36.2+ requests==2.32.5+ rfc3339-validator==0.1.4+ rich==14.1.0+ rich-rst==1.3.1+ rpds-py==0.27.1+ six==1.17.0+ sniffio==1.3.1+ sse-starlette==3.0.2+ starlette==0.48.0+ typing-extensions==4.15.0+ typing-inspection==0.4.1+ urllib3==2.5.0+ uvicorn==0.35.0+ werkzeug==3.1.1
Código del servidor
%%writefile MCP_elicitation_server/server.py"""MCP Multi-Turn server with Elicitation + Sampling============================================================This server demonstrates the use of elicitacion and samplingto create an intelligent travel booking agent that:1. Requests information from the user (elicitacion)2. Generates AI content to improve the experience (sampling)3. Confirms critical decisions (elicitacion)4. Personalizes recommendations (sampling)Use case: Intelligent travel booking agent that uses AI to personalize recommendations and elicitacion for critical confirmations.Usage:python server.py"""import asyncioimport jsonfrom typing import Any, Dict, List, Optionalfrom datetime import datetime, timedeltafrom enum import Enumfrom fastmcp import FastMCP, Contextfrom fastmcp.server.elicitation import AcceptedElicitation, DeclinedElicitation, CancelledElicitationfrom mcp.types import TextContent# MCP server instancemcp = FastMCP("Travel Booking Agent with AI")# Enumerationsclass TravelType(str, Enum):BUSINESS = "business"LEISURE = "leisure"FAMILY = "family"ADVENTURE = "adventure"class BudgetRange(str, Enum):BUDGET = "budget"MID_RANGE = "mid-range"LUXURY = "luxury"# Simulated database of destinationsDESTINATIONS_DB = {"paris": {"name": "Paris, France","base_price": 850,"highlights": ["Eiffel Tower", "Louvre", "Notre-Dame", "Champs-Élysées"],"best_season": "Spring/Fall","travel_time": "2-3 hours from Spain"},"tokio": {"name": "Tokio, Japan","base_price": 1200,"highlights": ["Shibuya", "Traditional temples", "Advanced technology", "Unique gastronomy"],"best_season": "Spring/Fall","travel_time": "11-14 hours from Spain"},"new york": {"name": "New York, United States","base_price": 650,"highlights": ["Central Park", "Broadway", "Statue of Liberty", "Times Square"],"best_season": "All year round","travel_time": "5-6 hours from Europe"},"bali": {"name": "Bali, Indonesia","base_price": 900,"highlights": ["Tropical beaches", "Hindu temples", "Rice fields", "Spa and wellness"],"best_season": "April-October","travel_time": "15-20 hours from Spain"}}# Storage for bookingsbookings: Dict[str, Dict[str, Any]] = {}def extract_elicitation_value(elicitation_data):"""Helper to extract value from elicitation response"""if isinstance(elicitation_data, dict) and "value" in elicitation_data:return elicitation_data["value"]return elicitation_data@mcp.toolasync def intelligent_travel_booking_agent(context: Context) -> str:"""Intelligent travel booking agent that combines elicitacionfor critical decisions and sampling for AI personalization."""booking_id = f"BK{datetime.now().strftime('%Y%m%d%H%M%S')}"booking_data = {"id": booking_id, "timestamp": datetime.now().isoformat()}await context.info(f"Starting new booking: {booking_id}")# STEP 1: Elicitation - Basic travel informationawait context.info("Collecting basic travel information...")# Travel typetravel_type_result = await context.elicit(message="What type of trip are you planning? Options: business, leisure, family, adventure",response_type=TravelType)if not isinstance(travel_type_result, AcceptedElicitation):return "🚫 Booking cancelled: Travel type not specified"travel_type_value = extract_elicitation_value(travel_type_result.data)booking_data["travel_type"] = travel_type_value# Desired destinationdestination_result = await context.elicit(message="What is your desired destination? Options: Paris, Tokyo, New York, Bali, or other",response_type=str)if not isinstance(destination_result, AcceptedElicitation):return "🚫 Booking incomplete: Destination not specified"destination_value = extract_elicitation_value(destination_result.data)destination_input = destination_value.lower().strip()booking_data["destination_input"] = destination_input# STEP 2: Destination analysisawait context.info("Analyzing destination...")# Determine destination using local databasedestination_info = Nonefor key in DESTINATIONS_DB:if key in destination_input or destination_input in key:destination_info = DESTINATIONS_DB[key]booking_data["destination"] = destination_info["name"]await context.info(f"Destination found: {destination_info['name']}")breakif not destination_info:# For unknown destinations, use generic datadestination_info = {"name": destination_input.title(),"base_price": 800,"highlights": ["Main attractions", "Local culture", "Gastronomy", "Unique experiences"],"best_season": "Depends on region","travel_time": "Depends on origin"}booking_data["destination"] = destination_info["name"]await context.info(f"Destination not found, using generic data: {destination_info['name']}")# STEP 3: Elicitation - Specific travel detailsawait context.info("Collecting specific travel details...")# Travel datesdates_result = await context.elicit(message="When are you planning to travel? (format: YYYY-MM-DD or description like 'next month')",response_type=str)travel_dates = "To be determined"if isinstance(dates_result, AcceptedElicitation):travel_dates = extract_elicitation_value(dates_result.data)booking_data["travel_dates"] = travel_dates# Number of travelerstravelers_result = await context.elicit(message="How many people will be traveling?",response_type=int)if not isinstance(travelers_result, AcceptedElicitation):return "🚫 Booking incomplete: Number of travelers not specified"num_travelers = extract_elicitation_value(travelers_result.data)booking_data["travelers"] = num_travelers# Budgetbudget_result = await context.elicit(message="What is your budget per person? Options: budget, mid-range, luxury",response_type=BudgetRange)budget_range = BudgetRange.MID_RANGE.valueif isinstance(budget_result, AcceptedElicitation):budget_range = extract_elicitation_value(budget_result.data)booking_data["budget"] = budget_range# STEP 4: Itinerary personalizationawait context.info("Generating personalized itinerary...")# Static itinerary based on travel typeif booking_data['travel_type'] == 'business':itinerary_text = f"""💼 BUSINESS ITINERARY - {destination_info['name']} ({num_travelers} people)DAY 1: Arrival and orientation- Morning: Check-in hotel executive- Afternoon: Business meetings- Evening: Business dinnerDAY 2-3: Primary activities- {destination_info['highlights'][0]} (executive tour)- {destination_info['highlights'][1]} (quick visit)- Free time for calls/meetingsDAY 4: Closing- Last meetings- Transfer to airport💰 ADDITIONAL COST ESTIMATES:- Executive meals: $400-600 EUR- Transport premium: $200 EUR- Activities: $300 EUR✈️ BUSINESS TIPS:- Hotel with business center 24/7- SIM card local for unlimited data- Business formal wardrobe"""elif booking_data['travel_type'] == 'family':itinerary_text = f"""👨👩👧👦 FAMILY ITINERARY - {destination_info['name']} ({num_travelers} people)DAY 1: Smooth arrival- Morning: Check-in family accommodation- Afternoon: Exploration of the neighborhood- Evening: Local authentic dinnerDAY 2-3: Primary attractions- {destination_info['highlights'][0]} (family activity)- {destination_info['highlights'][1]} (entertainment for kids)- Parks and playgroundsDAY 4: Relaxed activities- Shopping for souvenirs- Last photos- Preparation for return💰 FAMILY COST:- Food: $600-800 EUR- Activities: $500 EUR- Transport: $250 EUR- Souvenirs: $200 EUR👨👩👧👦 FAMILY TIPS:- Apartment with kitchen- Bring snacks and entertainment- Flexible schedules for rest"""else:itinerary_text = f"""🌍 PERSONALIZED ITINERARY - {destination_info['name']} ({num_travelers} people)DAY 1: Orientation- Arrival and check-in- Initial exploration of the area- Local dinnerDAY 2-3: Primary attractions- {destination_info['highlights'][0]}- {destination_info['highlights'][1]}- Cultural activitiesDAY 4: Unique experiences- {destination_info['highlights'][2] if len(destination_info['highlights']) > 2 else 'Special activities'}- Local gastronomy- Shopping💰 ADDITIONAL COST ESTIMATES:- Food: $300-500 EUR per person- Activities: $200-400 EUR per person- Local transport: $100-150 EUR per person📝 PRACTICAL TIPS:- Best season: {destination_info['best_season']}- Travel time: {destination_info['travel_time']}- Bring camera for memories"""booking_data["itinerary"] = itinerary_text# STEP 5: Calculation of prices and optionsawait context.info("Calculating prices...")base_price = destination_info["base_price"]budget_multipliers = {"budget": 0.7,"mid-range": 1.0,"luxury": 1.5}adjusted_price = int(base_price * budget_multipliers.get(budget_range.value, 1.0))total_price = adjusted_price * num_travelersbooking_data["price_per_person"] = adjusted_pricebooking_data["total_price"] = total_price# STEP 6: Elicitation - Critical confirmation of pricesawait context.info("Soliciting confirmation...")confirmation_message = f"""RESUMEN OF YOUR PERSONALIZED TRIPDestination: {destination_info['name']}Type: {booking_data['travel_type'].title()}Travelers: {num_travelers} peopleDates: {travel_dates}Budget: {budget_range.value.title()}PRICES:- Per person: ${adjusted_price:,} EUR- Total: ${total_price:,} EURINCLUDES:- Round trip flights- Accommodation ({budget_range.value})- Itinerary- Support 24/7Confirm this reservation? Options: confirm, view cheaper options, modify dates, cancel"""confirmation_result = await context.elicit(message=confirmation_message,response_type=["confirm", "view cheaper options", "modify dates", "cancel"])if not isinstance(confirmation_result, AcceptedElicitation):return "🚫 Reservation not confirmed - Session ended"user_choice = extract_elicitation_value(confirmation_result.data)# STEP 7: Handling user responseif user_choice == "confirm":booking_data["status"] = "confirmed"booking_data["confirmation_time"] = datetime.now().isoformat()bookings[booking_id] = booking_data# Custom confirmation message (simplified version)confirmation_message = f"""Congratulations! Your adventure is officially confirmed.You made a great decision choosing {destination_info['name']}. Our team is excited to be part of your next journey.WHAT COMES NOW:- You will receive complete documentation by email in 24h- We will contact you 48h before the trip- You have support 24/7 during your entire journey- Access to our mobile app with itineraryBONUS INCLUDED:- Digital personalized guide- List of useful phrases in local language- Offline map with points of interest- Emergency contactsPrepare for unforgettable memories!"""return f"""{confirmation_message}Reservation ID: {booking_id}Destination: {destination_info['name']}Total: ${total_price:,} EURYou will receive a confirmation email soon.{itinerary_text}For any questions: [email protected]""".strip()elif user_choice == "view cheaper options":# Generar alternativas más económicascheaper_price = int(adjusted_price * 0.75)cheaper_total = cheaper_price * num_travelersalternative_confirmation = await context.elicit(message=f"Cheaper option found: ${cheaper_price:,} per person (Total: ${cheaper_total:,}). Includes basic accommodation and flights with scale. Accept? Options: accept, reject",response_type=["accept", "reject"])if isinstance(alternative_confirmation, AcceptedElicitation) and extract_elicitation_value(alternative_confirmation.data) == "accept":booking_data["price_per_person"] = cheaper_pricebooking_data["total_price"] = cheaper_totalbooking_data["option"] = "cheaper"booking_data["status"] = "confirmed"bookings[booking_id] = booking_datasavings = total_price - cheaper_totalreturn f"""Cheaper option confirmed!Savings: ${savings:,} EURReservation ID: {booking_id}Destination: {destination_info['name']}Total final: ${cheaper_total:,} EUR""".strip()else:return "🔄 Cheaper option rejected. You can restart the process when you want."elif user_choice == "modify dates":new_dates_result = await context.elicit(message="What are your preferred dates?",response_type=str)if isinstance(new_dates_result, AcceptedElicitation):new_dates = extract_elicitation_value(new_dates_result.data)return f"📅 Dates updated to: {new_dates}. Restart the process to see new prices and availability."else:return "📅 Modification of dates cancelled."else: # cancelreturn "🚫 Reservation cancelled by the user. We hope to help you in the future!"if __name__ == "__main__":print("🚀 Starting Intelligent Travel Booking Agent MCP...")print("=" * 55)print("Available tools:")print("1. ✈️ intelligent_travel_booking_agent - Intelligent travel booking agent")print("=" * 55)print("🤖 Combines elicitation (confirmations) + AI sampling (recommendations)")mcp.run()Copied
Writing MCP_elicitation_server/server.py
Cliente con elicitación
Ahora creamos el cliente con elicitación, va a ejecutar la tool
del servidor, va a recibir las preguntas del servidor y va a devolverle las respuestas
Implementación del cliente con elicitación
Creamos una clase para el cliente con elicitación.
La clase conecta con el servidor y ejecuta la tool
del servidor.
Crear entorno virtual del cliente
Primero creamos la carpeta donde lo vamos a desarrollar
!mkdir MCP_elicitation_clientCopied
Creamos el entorno con uv
!cd MCP_elicitation_client && uv init .Copied
Initialized project `mcp-elicitation-client` at `/Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client`
Lo iniciamos
!cd MCP_elicitation_client && uv venvCopied
Using CPython 3.12.8Creating virtual environment at: .venvActivate with: source .venv/bin/activate
Instalamos las librerías necesarias
!cd MCP_elicitation_client && uv add fastmcpCopied
Resolved 64 packages in 27msInstalled 61 packages in 161ms ░░░░░░░░░░░░░░░░░░░░ [0/0] Installing wheels...+ annotated-types==0.7.0+ anyio==4.10.0+ attrs==25.3.0+ authlib==1.6.3+ certifi==2025.8.3+ cffi==2.0.0+ charset-normalizer==3.4.3+ click==8.2.1+ cryptography==45.0.7+ cyclopts==3.24.0+ dnspython==2.8.0+ docstring-parser==0.17.0+ docutils==0.22+ email-validator==2.3.0+ exceptiongroup==1.3.0+ fastmcp==2.12.3+ h11==0.16.0+ httpcore==1.0.9+ httpx==0.28.1+ httpx-sse==0.4.1+ idna==3.10+ isodate==0.7.2+ jsonschema==4.25.1+ jsonschema-path==0.3.4+ jsonschema-specifications==2025.9.1+ lazy-object-proxy==1.12.0+ markdown-it-py==4.0.0+ markupsafe==3.0.2+ mcp==1.14.0+ mdurl==0.1.2+ more-itertools==10.8.0+ openapi-core==0.19.5+ openapi-pydantic==0.5.1+ openapi-schema-validator==0.6.3+ openapi-spec-validator==0.7.2+ parse==1.20.2+ pathable==0.4.4+ pycparser==2.23+ pydantic==2.11.9+ pydantic-core==2.33.2+ pydantic-settings==2.10.1+ pygments==2.19.2+ pyperclip==1.9.0+ python-dotenv==1.1.1+ python-multipart==0.0.20+ pyyaml==6.0.2+ referencing==0.36.2+ requests==2.32.5+ rfc3339-validator==0.1.4+ rich==14.1.0+ rich-rst==1.3.1+ rpds-py==0.27.1+ six==1.17.0+ sniffio==1.3.1+ sse-starlette==3.0.2+ starlette==0.48.0+ typing-extensions==4.15.0+ typing-inspection==0.4.1+ urllib3==2.5.0+ uvicorn==0.35.0+ werkzeug==3.1.1
Código del cliente
%%writefile MCP_elicitation_client/client.py"""MCP Multi-Turn Client with Elicitation + Sampling=========================================================This client demonstrates the use of elicitation and samplingin an intelligent travel booking agent.Demonstrates:1. Elicitation for critical user decisions2. Sampling to generate personalized recommendations with AI3. Complete booking flow with confirmations4. Handling complex responses (accept/reject/modify)5. Smooth integration between human inputs and AI completionsUsage:python client.py"""import asyncioimport jsonfrom typing import Any, Dict, List, Optionalimport sysfrom fastmcp import Clientfrom fastmcp.client.transports import StdioTransportfrom fastmcp.client.elicitation import ElicitResultfrom fastmcp.client.sampling import SamplingParams, RequestContext as SamplingRequestContextclass ElicitationTravelClient:"""Client that demonstrates elicitation"""def __init__(self, server_command: List[str]):"""Initializes the elicitation client.Args:server_command: Command to execute the MCP server"""self.server_command = server_commandasync def connect(self) -> Client:"""Creates and connects the client to the server."""transport = StdioTransport(command=self.server_command[0],args=self.server_command[1:])# Configure the elicitation handlerasync def elicitation_handler(message: str, response_type, params, ctx) -> ElicitResult:"""Handles the server's elicitation requests.If user_scenario is None, asks for real input from the user.If a scenario is configured, simulates automatic responses."""print(f" Agent requests: {message}")# Show options if response_type is a listif isinstance(response_type, list):print("Available options:")for i, option in enumerate(response_type, 1):print(f" {i}. {option}")while True:try:choice = input(f"Your response (1-{len(response_type)}): ").strip()choice_idx = int(choice) - 1if 0 <= choice_idx < len(response_type):response = response_type[choice_idx]breakelse:print(f"❌ Please select a number from 1 to {len(response_type)}")except ValueError:print("❌ Please enter a valid number")else:# For other types, ask for direct inputresponse_hint = ""if response_type == int:response_hint = " (integer)"elif response_type == str:response_hint = " (text)"response = input(f"Your response{response_hint}: ").strip()# Convert to the correct type if necessaryif response_type == int:try:response = int(response)except ValueError:print("⚠️ Using default value: 1")response = 1# FastMCP expects a JSON object (dict), not a direct stringif isinstance(response, str):return ElicitResult(action="accept", content={"value": response})elif isinstance(response, (int, float)):return ElicitResult(action="accept", content={"value": response})else:return ElicitResult(action="accept", content=response)# Configure the sampling handlerasync def sampling_handler(messages, params: SamplingParams, ctx: SamplingRequestContext):"""Handles the server's sampling requests (AI completions).Simulates responses from different AI models according to the context."""print(f" AI request for {self._detect_ai_task(messages, params)}:")print(f" System: {params.system_prompt[:80]}..." if params.system_prompt else " System: Not specified")print(f" User: {messages[0].content.text[:80]}..." if messages else " User: Empty")# Generate simulated response according to the task typetask_type = self._detect_ai_task(messages, params)simulated_response = self._generate_ai_response(task_type, messages, params)print(f"AI responds: {simulated_response[:100]}...")from mcp.types import TextContentreturn TextContent(text=simulated_response, type="text")client = Client(transport,elicitation_handler=elicitation_handler,sampling_handler=sampling_handler)return clientasync def demo_interactive_booking(self, client: Client) -> None:"""Interactive real demo - the user introduces their own responses."""print(" " + "*" * 50)print("Demo: Real Interactive Booking")print("*" * 50)try:result = await client.call_tool("intelligent_travel_booking_agent", {})print(f" Interactive booking result:")print(result.content[0].text)except Exception as e:print(f"❌ Error in interactive booking: {str(e)}")async def interactive_demo():"""Interactive demo where the user chooses the type of traveler."""# Verify command line argumentsif len(sys.argv) != 2:print(f"Usage: python {sys.argv[0]} <path_to_fastmcp_server_script>")sys.exit(1)print("=" * 60)print("Intelligent Travel Booking Agent with Multi-Turn Interactions")print("=" * 60)server_script_path = sys.argv[1]server_command = ["python",server_script_path]client_manager = ElicitationTravelClient(server_command)async with await client_manager.connect() as client:print("Connected to the intelligent travel booking agent")try:await client_manager.demo_interactive_booking(client)except Exception as e:print(f"❌ Error: {str(e)}")if __name__ == "__main__":try:asyncio.run(interactive_demo())except KeyboardInterrupt:print(" 👋 Bye!")except Exception as e:print(f"❌ Error: {str(e)}")Copied
Writing MCP_elicitation_client/client.py
Ejecución
Como el servidor y el cliente se ha hecho sobre el protocolo STDIO
no necesitamos levantar el servidor, así que ejecutamos directamente el cliente
!cd MCP_elicitation_client && source .venv/bin/activate && uv run client.py ../MCP_elicitation_server/server.pyCopied
============================================================Intelligent Travel Booking Agent with Multi-Turn Interactions============================================================╭────────────────────────────────────────────────────────────────────────────╮│ ││ _ __ ___ _____ __ __ _____________ ____ ____ ││ _ __ ___ .'____/___ ______/ /_/ |/ / ____/ __ |___ / __ ││ _ __ ___ / /_ / __ `/ ___/ __/ /|_/ / / / /_/ / ___/ / / / / / ││ _ __ ___ / __/ / /_/ (__ ) /_/ / / / /___/ ____/ / __/_/ /_/ / ││ _ __ ___ /_/ ____/____/__/_/ /_/____/_/ /_____(*)____/ ││ ││ ││ FastMCP 2.0 ││ ││ ││ 🖥️ Server name: Travel Booking Agent with AI ││ 📦 Transport: STDIO ││ ││ 🏎️ FastMCP version: 2.12.3 ││ 🤝 MCP SDK version: 1.14.0 ││ ││ 📚 Docs: https://gofastmcp.com ││ 🚀 Deploy: https://fastmcp.cloud ││ │╰────────────────────────────────────────────────────────────────────────────╯[09/15/25 20:52:44] INFO Starting MCP server 'Travel Booking ]8;id=502080;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/server/server.py\server.py]8;;\:]8;id=404784;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/server/server.py#1495\1495]8;;\Agent with AI' with transport'stdio'Connected to the intelligent travel booking agent**************************************************Demo: Real Interactive Booking**************************************************[09/15/25 20:52:44] INFO Server log: Starting new booking: ]8;id=545502;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py\logging.py]8;;\:]8;id=910257;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py#40\40]8;;\BK20250915205244INFO Server log: Collecting basic travel ]8;id=329673;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py\logging.py]8;;\:]8;id=767066;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py#40\40]8;;\information...Agent requests: What type of trip are you planning? Options: business, leisure, family, adventureYour response:
Vemos que primero pregunta por el tipo de viaje, elegimos business
!cd MCP_elicitation_client && source .venv/bin/activate && uv run client.py ../MCP_elicitation_server/server.pyCopied
============================================================Intelligent Travel Booking Agent with Multi-Turn Interactions============================================================╭────────────────────────────────────────────────────────────────────────────╮│ ││ _ __ ___ _____ __ __ _____________ ____ ____ ││ _ __ ___ .'____/___ ______/ /_/ |/ / ____/ __ |___ / __ ││ _ __ ___ / /_ / __ `/ ___/ __/ /|_/ / / / /_/ / ___/ / / / / / ││ _ __ ___ / __/ / /_/ (__ ) /_/ / / / /___/ ____/ / __/_/ /_/ / ││ _ __ ___ /_/ ____/____/__/_/ /_/____/_/ /_____(*)____/ ││ ││ ││ FastMCP 2.0 ││ ││ ││ 🖥️ Server name: Travel Booking Agent with AI ││ 📦 Transport: STDIO ││ ││ 🏎️ FastMCP version: 2.12.3 ││ 🤝 MCP SDK version: 1.14.0 ││ ││ 📚 Docs: https://gofastmcp.com ││ 🚀 Deploy: https://fastmcp.cloud ││ │╰────────────────────────────────────────────────────────────────────────────╯[09/15/25 20:54:25] INFO Starting MCP server 'Travel Booking ]8;id=94017;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/server/server.py\server.py]8;;\:]8;id=573315;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/server/server.py#1495\1495]8;;\Agent with AI' with transport'stdio'Connected to the intelligent travel booking agent**************************************************Demo: Real Interactive Booking**************************************************[09/15/25 20:54:25] INFO Server log: Starting new booking: ]8;id=528137;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py\logging.py]8;;\:]8;id=704323;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py#40\40]8;;\BK20250915205425INFO Server log: Collecting basic travel ]8;id=706305;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py\logging.py]8;;\:]8;id=977937;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py#40\40]8;;\information...Agent requests: What type of trip are you planning? Options: business, leisure, family, adventureYour response: businessAgent requests: What is your desired destination? Options: Paris, Tokyo, New York, Bali, or otherYour response:
Vemos que ahora pregunta por la ciudad de destino, elegimos Paris
!cd MCP_elicitation_client && source .venv/bin/activate && uv run client.py ../MCP_elicitation_server/server.pyCopied
============================================================Intelligent Travel Booking Agent with Multi-Turn Interactions============================================================╭────────────────────────────────────────────────────────────────────────────╮│ ││ _ __ ___ _____ __ __ _____________ ____ ____ ││ _ __ ___ .'____/___ ______/ /_/ |/ / ____/ __ |___ / __ ││ _ __ ___ / /_ / __ `/ ___/ __/ /|_/ / / / /_/ / ___/ / / / / / ││ _ __ ___ / __/ / /_/ (__ ) /_/ / / / /___/ ____/ / __/_/ /_/ / ││ _ __ ___ /_/ ____/____/__/_/ /_/____/_/ /_____(*)____/ ││ ││ ││ FastMCP 2.0 ││ ││ ││ 🖥️ Server name: Travel Booking Agent with AI ││ 📦 Transport: STDIO ││ ││ 🏎️ FastMCP version: 2.12.3 ││ 🤝 MCP SDK version: 1.14.0 ││ ││ 📚 Docs: https://gofastmcp.com ││ 🚀 Deploy: https://fastmcp.cloud ││ │╰────────────────────────────────────────────────────────────────────────────╯[09/15/25 20:56:32] INFO Starting MCP server 'Travel Booking ]8;id=161535;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/server/server.py\server.py]8;;\:]8;id=465925;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/server/server.py#1495\1495]8;;\Agent with AI' with transport'stdio'Connected to the intelligent travel booking agent**************************************************Demo: Real Interactive Booking**************************************************[09/15/25 20:56:32] INFO Server log: Starting new booking: ]8;id=211309;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py\logging.py]8;;\:]8;id=952259;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py#40\40]8;;\BK20250915205632INFO Server log: Collecting basic travel ]8;id=264744;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py\logging.py]8;;\:]8;id=868015;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py#40\40]8;;\information...Agent requests: What type of trip are you planning? Options: business, leisure, family, adventureYour response: businessAgent requests: What is your desired destination? Options: Paris, Tokyo, New York, Bali, or otherYour response: Paris[09/15/25 20:56:56] INFO Server log: Analyzing destination... logging.py:40INFO Server log: Destination found: Paris, France logging.py:40INFO Server log: Collecting specific travel details... logging.py:40Agent requests: When are you planning to travel? (format: YYYY-MM-DD or description like 'next month')Your response:
Ahora pregunta por la fecha de viaje, elegimos next month
!cd MCP_elicitation_client && source .venv/bin/activate && uv run client.py ../MCP_elicitation_server/server.pyCopied
============================================================Intelligent Travel Booking Agent with Multi-Turn Interactions============================================================╭────────────────────────────────────────────────────────────────────────────╮│ ││ _ __ ___ _____ __ __ _____________ ____ ____ ││ _ __ ___ .'____/___ ______/ /_/ |/ / ____/ __ |___ / __ ││ _ __ ___ / /_ / __ `/ ___/ __/ /|_/ / / / /_/ / ___/ / / / / / ││ _ __ ___ / __/ / /_/ (__ ) /_/ / / / /___/ ____/ / __/_/ /_/ / ││ _ __ ___ /_/ ____/____/__/_/ /_/____/_/ /_____(*)____/ ││ ││ ││ FastMCP 2.0 ││ ││ ││ 🖥️ Server name: Travel Booking Agent with AI ││ 📦 Transport: STDIO ││ ││ 🏎️ FastMCP version: 2.12.3 ││ 🤝 MCP SDK version: 1.14.0 ││ ││ 📚 Docs: https://gofastmcp.com ││ 🚀 Deploy: https://fastmcp.cloud ││ │╰────────────────────────────────────────────────────────────────────────────╯[09/15/25 20:59:47] INFO Starting MCP server 'Travel Booking ]8;id=446100;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/server/server.py\server.py]8;;\:]8;id=325661;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/server/server.py#1495\1495]8;;\Agent with AI' with transport'stdio'Connected to the intelligent travel booking agent**************************************************Demo: Real Interactive Booking**************************************************[09/15/25 20:59:47] INFO Server log: Starting new booking: ]8;id=322003;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py\logging.py]8;;\:]8;id=198612;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py#40\40]8;;\BK20250915205947INFO Server log: Collecting basic travel ]8;id=449057;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py\logging.py]8;;\:]8;id=203031;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py#40\40]8;;\information...Agent requests: What type of trip are you planning? Options: business, leisure, family, adventureYour response: businessAgent requests: What is your desired destination? Options: Paris, Tokyo, New York, Bali, or otherYour response: Paris[09/15/25 20:56:56] INFO Server log: Analyzing destination... logging.py:40INFO Server log: Destination found: Paris, France logging.py:40INFO Server log: Collecting specific travel details... logging.py:40Agent requests: When are you planning to travel? (format: YYYY-MM-DD or description like 'next month')Your response: next monthAgent requests: How many people will be traveling?Your response:
Pregunta por el número de personas, elegimos 1
!cd MCP_elicitation_client && source .venv/bin/activate && uv run client.py ../MCP_elicitation_server/server.pyCopied
============================================================Intelligent Travel Booking Agent with Multi-Turn Interactions============================================================╭────────────────────────────────────────────────────────────────────────────╮│ ││ _ __ ___ _____ __ __ _____________ ____ ____ ││ _ __ ___ .'____/___ ______/ /_/ |/ / ____/ __ |___ / __ ││ _ __ ___ / /_ / __ `/ ___/ __/ /|_/ / / / /_/ / ___/ / / / / / ││ _ __ ___ / __/ / /_/ (__ ) /_/ / / / /___/ ____/ / __/_/ /_/ / ││ _ __ ___ /_/ ____/____/__/_/ /_/____/_/ /_____(*)____/ ││ ││ ││ FastMCP 2.0 ││ ││ ││ 🖥️ Server name: Travel Booking Agent with AI ││ 📦 Transport: STDIO ││ ││ 🏎️ FastMCP version: 2.12.3 ││ 🤝 MCP SDK version: 1.14.0 ││ ││ 📚 Docs: https://gofastmcp.com ││ 🚀 Deploy: https://fastmcp.cloud ││ │╰────────────────────────────────────────────────────────────────────────────╯[09/15/25 21:00:52] INFO Starting MCP server 'Travel Booking ]8;id=656645;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/server/server.py\server.py]8;;\:]8;id=131308;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/server/server.py#1495\1495]8;;\Agent with AI' with transport'stdio'Connected to the intelligent travel booking agent**************************************************Demo: Real Interactive Booking**************************************************[09/15/25 21:00:52] INFO Server log: Starting new booking: ]8;id=64387;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py\logging.py]8;;\:]8;id=680560;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py#40\40]8;;\BK20250915210052INFO Server log: Collecting basic travel ]8;id=68449;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py\logging.py]8;;\:]8;id=601001;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py#40\40]8;;\information...Agent requests: What type of trip are you planning? Options: business, leisure, family, adventureYour response: businessAgent requests: What is your desired destination? Options: Paris, Tokyo, New York, Bali, or otherYour response: Paris[09/15/25 20:56:56] INFO Server log: Analyzing destination... logging.py:40INFO Server log: Destination found: Paris, France logging.py:40INFO Server log: Collecting specific travel details... logging.py:40Agent requests: When are you planning to travel? (format: YYYY-MM-DD or description like 'next month')Your response: next monthAgent requests: How many people will be traveling?Your response: 1Agent requests: What is your budget per person? Options: budget, mid-range, luxuryYour response:
Y por último pregunta por el presupuesto, elegimos budget
!cd MCP_elicitation_client && source .venv/bin/activate && uv run client.py ../MCP_elicitation_server/server.pyCopied
============================================================Intelligent Travel Booking Agent with Multi-Turn Interactions============================================================╭────────────────────────────────────────────────────────────────────────────╮│ ││ _ __ ___ _____ __ __ _____________ ____ ____ ││ _ __ ___ .'____/___ ______/ /_/ |/ / ____/ __ |___ / __ ││ _ __ ___ / /_ / __ `/ ___/ __/ /|_/ / / / /_/ / ___/ / / / / / ││ _ __ ___ / __/ / /_/ (__ ) /_/ / / / /___/ ____/ / __/_/ /_/ / ││ _ __ ___ /_/ ____/____/__/_/ /_/____/_/ /_____(*)____/ ││ ││ ││ FastMCP 2.0 ││ ││ ││ 🖥️ Server name: Travel Booking Agent with AI ││ 📦 Transport: STDIO ││ ││ 🏎️ FastMCP version: 2.12.3 ││ 🤝 MCP SDK version: 1.14.0 ││ ││ 📚 Docs: https://gofastmcp.com ││ 🚀 Deploy: https://fastmcp.cloud ││ │╰────────────────────────────────────────────────────────────────────────────╯[09/15/25 21:02:06] INFO Starting MCP server 'Travel Booking ]8;id=110664;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/server/server.py\server.py]8;;\:]8;id=283411;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/server/server.py#1495\1495]8;;\Agent with AI' with transport'stdio'Connected to the intelligent travel booking agent**************************************************Demo: Real Interactive Booking**************************************************[09/15/25 21:02:06] INFO Server log: Starting new booking: ]8;id=714510;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py\logging.py]8;;\:]8;id=891173;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py#40\40]8;;\BK20250915210206INFO Server log: Collecting basic travel ]8;id=262915;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py\logging.py]8;;\:]8;id=817621;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py#40\40]8;;\information...Agent requests: What type of trip are you planning? Options: business, leisure, family, adventureYour response: businessAgent requests: What is your desired destination? Options: Paris, Tokyo, New York, Bali, or otherYour response: Paris[09/15/25 20:56:56] INFO Server log: Analyzing destination... logging.py:40INFO Server log: Destination found: Paris, France logging.py:40INFO Server log: Collecting specific travel details... logging.py:40Agent requests: When are you planning to travel? (format: YYYY-MM-DD or description like 'next month')Your response: next monthAgent requests: How many people will be traveling?Your response: 1Agent requests: What is your budget per person? Options: budget, mid-range, luxuryYour response: budget[09/15/25 21:01:55] INFO Server log: Generating personalized itinerary... logging.py:40INFO Server log: Calculating prices... logging.py:40INFO Server log: Soliciting confirmation... logging.py:40Agent requests:RESUMEN OF YOUR PERSONALIZED TRIPDestination: Paris, FranceType: BusinessTravelers: 1 peopleDates: next monthBudget: BudgetPRICES:- Per person: $595 EUR- Total: $595 EURINCLUDES:- Round trip flights- Accommodation (budget)- Itinerary- Support 24/7Confirm this reservation? Options: confirm, view cheaper options, modify dates, cancelYour response:
Muestra un posible viaje y nos pregunta si lo queremos confirmar, elegimos confirm
!cd MCP_elicitation_client && source .venv/bin/activate && uv run client.py ../MCP_elicitation_server/server.pyCopied
============================================================Intelligent Travel Booking Agent with Multi-Turn Interactions============================================================╭────────────────────────────────────────────────────────────────────────────╮│ ││ _ __ ___ _____ __ __ _____________ ____ ____ ││ _ __ ___ .'____/___ ______/ /_/ |/ / ____/ __ |___ / __ ││ _ __ ___ / /_ / __ `/ ___/ __/ /|_/ / / / /_/ / ___/ / / / / / ││ _ __ ___ / __/ / /_/ (__ ) /_/ / / / /___/ ____/ / __/_/ /_/ / ││ _ __ ___ /_/ ____/____/__/_/ /_/____/_/ /_____(*)____/ ││ ││ ││ FastMCP 2.0 ││ ││ ││ 🖥️ Server name: Travel Booking Agent with AI ││ 📦 Transport: STDIO ││ ││ 🏎️ FastMCP version: 2.12.3 ││ 🤝 MCP SDK version: 1.14.0 ││ ││ 📚 Docs: https://gofastmcp.com ││ 🚀 Deploy: https://fastmcp.cloud ││ │╰────────────────────────────────────────────────────────────────────────────╯[09/15/25 21:04:20] INFO Starting MCP server 'Travel Booking ]8;id=960192;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/server/server.py\server.py]8;;\:]8;id=627123;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/server/server.py#1495\1495]8;;\Agent with AI' with transport'stdio'Connected to the intelligent travel booking agent**************************************************Demo: Real Interactive Booking**************************************************[09/15/25 21:04:20] INFO Server log: Starting new booking: ]8;id=204873;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py\logging.py]8;;\:]8;id=342279;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py#40\40]8;;\BK20250915210420INFO Server log: Collecting basic travel ]8;id=995160;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py\logging.py]8;;\:]8;id=505961;file:///Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client/.venv/lib/python3.12/site-packages/fastmcp/client/logging.py#40\40]8;;\information...Agent requests: What type of trip are you planning? Options: business, leisure, family, adventureYour response: businessAgent requests: What is your desired destination? Options: Paris, Tokyo, New York, Bali, or otherYour response: Paris[09/15/25 20:56:56] INFO Server log: Analyzing destination... logging.py:40INFO Server log: Destination found: Paris, France logging.py:40INFO Server log: Collecting specific travel details... logging.py:40Agent requests: When are you planning to travel? (format: YYYY-MM-DD or description like 'next month')Your response: next monthAgent requests: How many people will be traveling?Your response: 1Agent requests: What is your budget per person? Options: budget, mid-range, luxuryYour response: budget[09/15/25 21:01:55] INFO Server log: Generating personalized itinerary... logging.py:40INFO Server log: Calculating prices... logging.py:40INFO Server log: Soliciting confirmation... logging.py:40Agent requests:RESUMEN OF YOUR PERSONALIZED TRIPDestination: Paris, FranceType: BusinessTravelers: 1 peopleDates: next monthBudget: BudgetPRICES:- Per person: $595 EUR- Total: $595 EURINCLUDES:- Round trip flights- Accommodation (budget)- Itinerary- Support 24/7Confirm this reservation? Options: confirm, view cheaper options, modify dates, cancelYour response: confirmInteractive booking result:Congratulations! Your adventure is officially confirmed.You made a great decision choosing Paris, France. Our team is excited to be part of your next journey.WHAT COMES NOW:- You will receive complete documentation by email in 24h- We will contact you 48h before the trip- You have support 24/7 during your entire journey- Access to our mobile app with itineraryBONUS INCLUDED:- You will receive complete documentation by email in 24h- We will contact you 48h before the trip- You have support 24/7 during your entire journey- Access to our mobile app with itineraryBONUS INCLUDED:- Digital personalized guide- List of useful phrases in local language- Offline map with points of interest- Emergency contactsPrepare for unforgettable memories!Reservation ID: BK20250915205523Destination: Paris, FranceTotal: $595 EURYou will receive a confirmation email soon.💼 BUSINESS ITINERARY - Paris, France (1 people)DAY 1: Arrival and orientation- Morning: Check-in hotel executive- Afternoon: Business meetings- Evening: Business dinnerDAY 2-3: Primary activities- Eiffel Tower (executive tour)- Louvre (quick visit)- Free time for calls/meetingsDAY 4: Closing- Last meetings- Transfer to airport💰 ADDITIONAL COST ESTIMATES:- Executive meals: $400-600 EUR- Transport premium: $200 EUR- Activities: $300 EUR✈️ BUSINESS TIPS:- Hotel with business center 24/7- SIM card local for unlimited data- Business formal wardrobeFor any questions: [email protected]
Vemos que el servidor le ha ido pidiendo los datos al usuario poco a poco para poder realizar una reserva lo más personalizada posible.