MCP Elicitation: Implementing Elicitation in Servers with FastMCP and Python

MCP Elicitation: Implementing Elicitation in Servers with FastMCP and Python MCP Elicitation: Implementing Elicitation in Servers with FastMCP and Python

In this post, we're going to look at how to develop an MCP server and client with elicitation. And if you also have no idea what elicitation is, don't worry, I'll explain it to you. Elicitation is when the server needs information from the user, so it asks the user for it through the client.

MCP server with elicitationlink image 11

We are going to create an MCP server that acts as a travel search engine. So it will ask the user for data. All possible trips will be stored in a variable; it will not be a real search engine, but rather an example to demonstrate elicitation.

Server implementation with elicitationlink image 12

We created two enum types to define the different types of trips and budget ranges.

We created a dictionary to store all possible trips.

We created a function to extract the value of the elicitation response.

Finally, we implement the intelligent_travel_booking_agent function, which is the tool that will request data from the user and save the results in a variable.

The function sends questions to the client, so that the client can send them to the user. The user will respond, and the client will send the response to the server.

Once it has the necessary data from the client, it will “search” for the trip that best suits their needs.

Create virtual server environmentlink image 13

First, we create the folder where we are going to develop it.

	
!mkdir MCP_elicitation_server
Copy

We create the environment with uv

	
!cd MCP_elicitation_server && uv init .
Copy
	
Initialized project `mcp-elicitation-server` at `/Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_server`

We started it

	
!cd MCP_elicitation_server && uv venv
Copy
	
Using CPython 3.12.8
Creating virtual environment at: .venv
Activate with: source .venv/bin/activate

We install the necessary libraries.

	
!cd MCP_elicitation_server && uv add fastmcp
Copy
	
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 KiB
jsonschema-specifications ------------------------------ 0 B/18.00 KiB
⠙ Preparing packages... (0/11)------------------ 14.88 KiB/68.03 KiB
jsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiB
⠙ Preparing packages... (0/11)------------------ 14.88 KiB/68.03 KiB
jsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiB
⠙ Preparing packages... (0/11)------------------ 14.88 KiB/68.03 KiB
jsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiB
⠙ Preparing packages... (0/11)------------------ 14.88 KiB/68.03 KiB
jsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiB
more-itertools ------------------------------ 14.88 KiB/68.03 KiB
⠙ Preparing packages... (0/11)------------------ 0 B/115.37 KiB
jsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiB
more-itertools ------------------------------ 14.88 KiB/68.03 KiB
⠙ Preparing packages... (0/11)------------------ 14.89 KiB/115.37 KiB
jsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiB
more-itertools ------------------------------ 30.88 KiB/68.03 KiB
⠙ Preparing packages... (0/11)------------------ 14.89 KiB/115.37 KiB
jsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiB
more-itertools ------------------------------ 46.88 KiB/68.03 KiB
⠙ Preparing packages... (0/11)------------------ 14.89 KiB/115.37 KiB
jsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiB
more-itertools ------------------------------ 62.88 KiB/68.03 KiB
⠙ Preparing packages... (0/11)------------------ 14.89 KiB/115.37 KiB
jsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiB
more-itertools ------------------------------ 68.03 KiB/68.03 KiB
⠙ Preparing packages... (0/11)------------------ 14.89 KiB/115.37 KiB
jsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiB
more-itertools ------------------------------ 68.03 KiB/68.03 KiB
⠙ Preparing packages... (0/11)------------------ 14.89 KiB/115.37 KiB
jsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiB
more-itertools ------------------------------ 68.03 KiB/68.03 KiB
⠙ Preparing packages... (0/11)------------------ 14.89 KiB/115.37 KiB
jsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiB
more-itertools ------------------------------ 68.03 KiB/68.03 KiB
⠙ Preparing packages... (0/11)------------------ 14.89 KiB/115.37 KiB
jsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiB
more-itertools ------------------------------ 68.03 KiB/68.03 KiB
pycparser ------------------------------ 14.89 KiB/115.37 KiB
⠙ Preparing packages... (0/11)------------------ 0 B/434.43 KiB
jsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiB
starlette ------------------------------ 14.89 KiB/72.01 KiB
cyclopts ------------------------------ 0 B/84.13 KiB
pycparser ------------------------------ 30.89 KiB/115.37 KiB
cffi ------------------------------ 14.92 KiB/176.80 KiB
⠙ Preparing packages... (0/11)------------------ 0 B/434.43 KiB
jsonschema-specifications ------------------------------ 14.87 KiB/18.00 KiB
starlette ------------------------------ 14.89 KiB/72.01 KiB
cyclopts ------------------------------ 0 B/84.13 KiB
pycparser ------------------------------ 46.89 KiB/115.37 KiB
cffi ------------------------------ 14.92 KiB/176.80 KiB
⠙ Preparing packages... (0/11)------------------ 0 B/434.43 KiB
starlette ------------------------------ 14.89 KiB/72.01 KiB
cyclopts ------------------------------ 0 B/84.13 KiB
pycparser ------------------------------ 78.89 KiB/115.37 KiB
mcp ------------------------------ 0 B/159.97 KiB
cffi ------------------------------ 14.92 KiB/176.80 KiB
dnspython ------------------------------ 0 B/323.33 KiB
pydantic ------------------------------ 0 B/434.43 KiB
⠙ Preparing packages... (0/11)------------------ 0 B/6.71 MiB
starlette ------------------------------ 46.89 KiB/72.01 KiB
cyclopts ------------------------------ 32.00 KiB/84.13 KiB
mcp ------------------------------ 32.00 KiB/159.97 KiB
cffi ------------------------------ 63.62 KiB/176.80 KiB
dnspython ------------------------------ 46.78 KiB/323.33 KiB
pydantic ------------------------------ 32.87 KiB/434.43 KiB
⠙ Preparing packages... (0/11)------------------ 30.88 KiB/6.71 MiB
cyclopts ------------------------------ 59.40 KiB/84.13 KiB
mcp ------------------------------ 64.00 KiB/159.97 KiB
cffi ------------------------------ 63.62 KiB/176.80 KiB
dnspython ------------------------------ 46.78 KiB/323.33 KiB
pydantic ------------------------------ 62.42 KiB/434.43 KiB
⠙ Preparing packages... (0/11)------------------ 46.88 KiB/6.71 MiB
mcp ------------------------------ 96.00 KiB/159.97 KiB
cffi ------------------------------ 127.62 KiB/176.80 KiB
fastmcp ------------------------------ 30.89 KiB/306.67 KiB
dnspython ------------------------------ 110.89 KiB/323.33 KiB
pydantic ------------------------------ 154.40 KiB/434.43 KiB
⠙ Preparing packages... (0/11)------------------ 78.88 KiB/6.71 MiB
mcp ------------------------------ 159.97 KiB/159.97 KiB
fastmcp ------------------------------ 94.89 KiB/306.67 KiB
dnspython ------------------------------ 206.89 KiB/323.33 KiB
pydantic ------------------------------ 222.42 KiB/434.43 KiB
⠙ Preparing packages... (0/11)------------------ 122.63 KiB/6.71 MiB
mcp ------------------------------ 159.97 KiB/159.97 KiB
fastmcp ------------------------------ 110.89 KiB/306.67 KiB
dnspython ------------------------------ 222.89 KiB/323.33 KiB
pydantic ------------------------------ 238.42 KiB/434.43 KiB
⠙ Preparing packages... (0/11)------------------ 142.88 KiB/6.71 MiB
fastmcp ------------------------------ 110.89 KiB/306.67 KiB
dnspython ------------------------------ 222.89 KiB/323.33 KiB
pydantic ------------------------------ 238.42 KiB/434.43 KiB
⠙ Preparing packages... (0/11)------------------ 411.17 KiB/6.71 MiB
fastmcp ------------------------------ 206.68 KiB/306.67 KiB
dnspython ------------------------------ 254.89 KiB/323.33 KiB
pydantic ------------------------------ 318.10 KiB/434.43 KiB
⠙ Preparing packages... (0/11)[2m--------------- 3.25 MiB/6.71 MiB
fastmcp ------------------------------ 222.89 KiB/306.67 KiB
dnspython ------------------------------ 270.89 KiB/323.33 KiB
⠙ Preparing packages... (0/11)-------------- 366.42 KiB/434.43 KiB
fastmcp ------------------------------ 238.89 KiB/306.67 KiB
dnspython ------------------------------ 270.89 KiB/323.33 KiB
⠹ Preparing packages... (8/11)-------------- 382.42 KiB/434.43 KiB
fastmcp ------------------------------ 254.89 KiB/306.67 KiB
⠹ Preparing packages... (8/11)-------------- 286.89 KiB/323.33 KiB
Prepared 11 packages in 212ms
Installed 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

Server codelink image 14

	
%%writefile MCP_elicitation_server/server.py
"""
MCP Multi-Turn server with Elicitation + Sampling
============================================================
This server demonstrates the use of elicitacion and sampling
to 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 asyncio
import json
from typing import Any, Dict, List, Optional
from datetime import datetime, timedelta
from enum import Enum
from fastmcp import FastMCP, Context
from fastmcp.server.elicitation import AcceptedElicitation, DeclinedElicitation, CancelledElicitation
from mcp.types import TextContent
# MCP server instance
mcp = FastMCP("Travel Booking Agent with AI")
# Enumerations
class 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 destinations
DESTINATIONS_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 bookings
bookings: 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.tool
async def intelligent_travel_booking_agent(context: Context) -> str:
"""
Intelligent travel booking agent that combines elicitacion
for 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 information
await context.info("Collecting basic travel information...")
# Travel type
travel_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 destination
destination_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 analysis
await context.info("Analyzing destination...")
# Determine destination using local database
destination_info = None
for 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']}")
break
if not destination_info:
# For unknown destinations, use generic data
destination_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 details
await context.info("Collecting specific travel details...")
# Travel dates
dates_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 travelers
travelers_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
# Budget
budget_result = await context.elicit(
message="What is your budget per person? Options: budget, mid-range, luxury",
response_type=BudgetRange
)
budget_range = BudgetRange.MID_RANGE.value
if isinstance(budget_result, AcceptedElicitation):
budget_range = extract_elicitation_value(budget_result.data)
booking_data["budget"] = budget_range
# STEP 4: Itinerary personalization
await context.info("Generating personalized itinerary...")
# Static itinerary based on travel type
if 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 dinner
DAY 2-3: Primary activities
- {destination_info['highlights'][0]} (executive tour)
- {destination_info['highlights'][1]} (quick visit)
- Free time for calls/meetings
DAY 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 dinner
DAY 2-3: Primary attractions
- {destination_info['highlights'][0]} (family activity)
- {destination_info['highlights'][1]} (entertainment for kids)
- Parks and playgrounds
DAY 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 dinner
DAY 2-3: Primary attractions
- {destination_info['highlights'][0]}
- {destination_info['highlights'][1]}
- Cultural activities
DAY 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 options
await 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_travelers
booking_data["price_per_person"] = adjusted_price
booking_data["total_price"] = total_price
# STEP 6: Elicitation - Critical confirmation of prices
await context.info("Soliciting confirmation...")
confirmation_message = f"""
RESUMEN OF YOUR PERSONALIZED TRIP
Destination: {destination_info['name']}
Type: {booking_data['travel_type'].title()}
Travelers: {num_travelers} people
Dates: {travel_dates}
Budget: {budget_range.value.title()}
PRICES:
- Per person: ${adjusted_price:,} EUR
- Total: ${total_price:,} EUR
INCLUDES:
- Round trip flights
- Accommodation ({budget_range.value})
- Itinerary
- Support 24/7
Confirm 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 response
if 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 itinerary
BONUS INCLUDED:
- Digital personalized guide
- List of useful phrases in local language
- Offline map with points of interest
- Emergency contacts
Prepare for unforgettable memories!"""
return f"""
{confirmation_message}
Reservation ID: {booking_id}
Destination: {destination_info['name']}
Total: ${total_price:,} EUR
You 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ómicas
cheaper_price = int(adjusted_price * 0.75)
cheaper_total = cheaper_price * num_travelers
alternative_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_price
booking_data["total_price"] = cheaper_total
booking_data["option"] = "cheaper"
booking_data["status"] = "confirmed"
bookings[booking_id] = booking_data
savings = total_price - cheaper_total
return f"""
Cheaper option confirmed!
Savings: ${savings:,} EUR
Reservation 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: # cancel
return "🚫 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()
Copy
	
Writing MCP_elicitation_server/server.py

Client with elicitationlink image 15

Now we create the client with elicitation. It will run the server's tool, receive questions from the server, and return the answers.

Client implementation with elicitationlink image 16

We create a class for the client with elicitation.

The class connects to the server and executes the server's tool.

Create virtual customer environmentlink image 17

First, we create the folder where we are going to develop it.

	
!mkdir MCP_elicitation_client
Copy

We create the environment with uv

	
!cd MCP_elicitation_client && uv init .
Copy
	
Initialized project `mcp-elicitation-client` at `/Users/macm1/Documents/web/portafolio/posts/MCP_elicitation_client`

We started it

	
!cd MCP_elicitation_client && uv venv
Copy
	
Using CPython 3.12.8
Creating virtual environment at: .venv
Activate with: source .venv/bin/activate

We install the necessary libraries.

	
!cd MCP_elicitation_client && uv add fastmcp
Copy
	
Resolved 64 packages in 27ms
Installed 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

Client codelink image 18

	
%%writefile MCP_elicitation_client/client.py
"""
MCP Multi-Turn Client with Elicitation + Sampling
=========================================================
This client demonstrates the use of elicitation and sampling
in an intelligent travel booking agent.
Demonstrates:
1. Elicitation for critical user decisions
2. Sampling to generate personalized recommendations with AI
3. Complete booking flow with confirmations
4. Handling complex responses (accept/reject/modify)
5. Smooth integration between human inputs and AI completions
Usage:
python client.py
"""
import asyncio
import json
from typing import Any, Dict, List, Optional
import sys
from fastmcp import Client
from fastmcp.client.transports import StdioTransport
from fastmcp.client.elicitation import ElicitResult
from fastmcp.client.sampling import SamplingParams, RequestContext as SamplingRequestContext
class 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_command
async 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 handler
async 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 list
if 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) - 1
if 0 <= choice_idx < len(response_type):
response = response_type[choice_idx]
break
else:
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 input
response_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 necessary
if 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 string
if 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 handler
async 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 type
task_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 TextContent
return TextContent(text=simulated_response, type="text")
client = Client(
transport,
elicitation_handler=elicitation_handler,
sampling_handler=sampling_handler
)
return client
async 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 arguments
if 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)}")
Copy
	
Writing MCP_elicitation_client/client.py

Executionlink image 19

Since the server and client have been built on the STDIO protocol, we don't need to start the server, so we run the client directly.

	
!cd MCP_elicitation_client && source .venv/bin/activate && uv run client.py ../MCP_elicitation_server/server.py
Copy
	
============================================================
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;;\
BK20250915205244
INFO 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, adventure
Your response:

We see that it first asks for the type of trip, so we choose “business.”

	
!cd MCP_elicitation_client && source .venv/bin/activate && uv run client.py ../MCP_elicitation_server/server.py
Copy
	
============================================================
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;;\
BK20250915205425
INFO 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, adventure
Your response: business
Agent requests: What is your desired destination? Options: Paris, Tokyo, New York, Bali, or other
Your response:

We see that it now asks for the destination city, so we choose Paris.

	
!cd MCP_elicitation_client && source .venv/bin/activate && uv run client.py ../MCP_elicitation_server/server.py
Copy
	
============================================================
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;;\
BK20250915205632
INFO 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, adventure
Your response: business
Agent requests: What is your desired destination? Options: Paris, Tokyo, New York, Bali, or other
Your response: Paris
[09/15/25 20:56:56] INFO Server log: Analyzing destination... logging.py:40
INFO Server log: Destination found: Paris, France logging.py:40
INFO Server log: Collecting specific travel details... logging.py:40
Agent requests: When are you planning to travel? (format: YYYY-MM-DD or description like 'next month')
Your response:

Now it asks for the travel date, we choose next month

	
!cd MCP_elicitation_client && source .venv/bin/activate && uv run client.py ../MCP_elicitation_server/server.py
Copy
	
============================================================
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;;\
BK20250915205947
INFO 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, adventure
Your response: business
Agent requests: What is your desired destination? Options: Paris, Tokyo, New York, Bali, or other
Your response: Paris
[09/15/25 20:56:56] INFO Server log: Analyzing destination... logging.py:40
INFO Server log: Destination found: Paris, France logging.py:40
INFO Server log: Collecting specific travel details... logging.py:40
Agent requests: When are you planning to travel? (format: YYYY-MM-DD or description like 'next month')
Your response: next month
Agent requests: How many people will be traveling?
Your response:

Ask for the number of people, we choose 1

	
!cd MCP_elicitation_client && source .venv/bin/activate && uv run client.py ../MCP_elicitation_server/server.py
Copy
	
============================================================
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;;\
BK20250915210052
INFO 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, adventure
Your response: business
Agent requests: What is your desired destination? Options: Paris, Tokyo, New York, Bali, or other
Your response: Paris
[09/15/25 20:56:56] INFO Server log: Analyzing destination... logging.py:40
INFO Server log: Destination found: Paris, France logging.py:40
INFO Server log: Collecting specific travel details... logging.py:40
Agent requests: When are you planning to travel? (format: YYYY-MM-DD or description like 'next month')
Your response: next month
Agent requests: How many people will be traveling?
Your response: 1
Agent requests: What is your budget per person? Options: budget, mid-range, luxury
Your response:

And finally, ask about the budget; we choose “budget.”

	
!cd MCP_elicitation_client && source .venv/bin/activate && uv run client.py ../MCP_elicitation_server/server.py
Copy
	
============================================================
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;;\
BK20250915210206
INFO 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, adventure
Your response: business
Agent requests: What is your desired destination? Options: Paris, Tokyo, New York, Bali, or other
Your response: Paris
[09/15/25 20:56:56] INFO Server log: Analyzing destination... logging.py:40
INFO Server log: Destination found: Paris, France logging.py:40
INFO Server log: Collecting specific travel details... logging.py:40
Agent requests: When are you planning to travel? (format: YYYY-MM-DD or description like 'next month')
Your response: next month
Agent requests: How many people will be traveling?
Your response: 1
Agent requests: What is your budget per person? Options: budget, mid-range, luxury
Your response: budget
[09/15/25 21:01:55] INFO Server log: Generating personalized itinerary... logging.py:40
INFO Server log: Calculating prices... logging.py:40
INFO Server log: Soliciting confirmation... logging.py:40
Agent requests:
RESUMEN OF YOUR PERSONALIZED TRIP
Destination: Paris, France
Type: Business
Travelers: 1 people
Dates: next month
Budget: Budget
PRICES:
- Per person: $595 EUR
- Total: $595 EUR
INCLUDES:
- Round trip flights
- Accommodation (budget)
- Itinerary
- Support 24/7
Confirm this reservation? Options: confirm, view cheaper options, modify dates, cancel
Your response:

It shows a possible trip and asks us if we want to confirm it. We choose confirm.

	
!cd MCP_elicitation_client && source .venv/bin/activate && uv run client.py ../MCP_elicitation_server/server.py
Copy
	
============================================================
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;;\
BK20250915210420
INFO 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, adventure
Your response: business
Agent requests: What is your desired destination? Options: Paris, Tokyo, New York, Bali, or other
Your response: Paris
[09/15/25 20:56:56] INFO Server log: Analyzing destination... logging.py:40
INFO Server log: Destination found: Paris, France logging.py:40
INFO Server log: Collecting specific travel details... logging.py:40
Agent requests: When are you planning to travel? (format: YYYY-MM-DD or description like 'next month')
Your response: next month
Agent requests: How many people will be traveling?
Your response: 1
Agent requests: What is your budget per person? Options: budget, mid-range, luxury
Your response: budget
[09/15/25 21:01:55] INFO Server log: Generating personalized itinerary... logging.py:40
INFO Server log: Calculating prices... logging.py:40
INFO Server log: Soliciting confirmation... logging.py:40
Agent requests:
RESUMEN OF YOUR PERSONALIZED TRIP
Destination: Paris, France
Type: Business
Travelers: 1 people
Dates: next month
Budget: Budget
PRICES:
- Per person: $595 EUR
- Total: $595 EUR
INCLUDES:
- Round trip flights
- Accommodation (budget)
- Itinerary
- Support 24/7
Confirm this reservation? Options: confirm, view cheaper options, modify dates, cancel
Your response: confirm
Interactive 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 itinerary
BONUS 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 itinerary
BONUS INCLUDED:
- Digital personalized guide
- List of useful phrases in local language
- Offline map with points of interest
- Emergency contacts
Prepare for unforgettable memories!
Reservation ID: BK20250915205523
Destination: Paris, France
Total: $595 EUR
You 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 dinner
DAY 2-3: Primary activities
- Eiffel Tower (executive tour)
- Louvre (quick visit)
- Free time for calls/meetings
DAY 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
For any questions: [email protected]

We see that the server has been asking the user for information little by little in order to make the reservation as personalized as possible.

Continue reading

Stream Information in MCP: Complete Guide to Real-time Progress Updates with FastMCP

Stream Information in MCP: Complete Guide to Real-time Progress Updates with FastMCP

Learn how to implement real-time streaming in MCP (Model Context Protocol) applications using FastMCP. This comprehensive guide shows you how to create MCP servers and clients that support progress updates and streaming information for long-running tasks. You'll build streaming-enabled tools that provide real-time feedback during data processing, file uploads, monitoring tasks, and other time-intensive operations. Discover how to use StreamableHttpTransport, implement progress handlers with Context, and create visual progress bars that enhance user experience when working with MCP applications that require continuous feedback.

Last posts -->

Have you seen these projects?

Horeca chatbot

Horeca chatbot Horeca chatbot
Python
LangChain
PostgreSQL
PGVector
React
Kubernetes
Docker
GitHub Actions

Chatbot conversational for cooks of hotels and restaurants. A cook, kitchen manager or room service of a hotel or restaurant can talk to the chatbot to get information about recipes and menus. But it also implements agents, with which it can edit or create new recipes or menus

Subtify

Subtify Subtify
Python
Whisper
Spaces

Subtitle generator for videos in the language you want. Also, it puts a different color subtitle to each person

View all projects -->

Do you want to apply AI in your project? Contact me!

Do you want to improve with these tips?

Last tips -->

Use this locally

Hugging Face spaces allow us to run models with very simple demos, but what if the demo breaks? Or if the user deletes it? That's why I've created docker containers with some interesting spaces, to be able to use them locally, whatever happens. In fact, if you click on any project view button, it may take you to a space that doesn't work.

Flow edit

Flow edit Flow edit

FLUX.1-RealismLora

FLUX.1-RealismLora FLUX.1-RealismLora
View all containers -->

Do you want to apply AI in your project? Contact me!

Do you want to train your model with these datasets?

short-jokes-dataset

Dataset with jokes in English

opus100

Dataset with translations from English to Spanish

netflix_titles

Dataset with Netflix movies and series

View more datasets -->