Elicitação MCP: Implementar Elicitação em Servidores com FastMCP e Python

Elicitação MCP: Implementar Elicitação em Servidores com FastMCP e Python Elicitação MCP: Implementar Elicitação em Servidores com FastMCP e Python

Nesta publicação, vamos ver como desenvolver um servidor e um cliente MCP com elicitação. E se você também não tem ideia do que é elicitação, não se preocupe, que eu vou explicar. Elicitação é quando o servidor precisa de informações do usuário, então, por meio do cliente, ele as solicita ao usuário.

Servidor MCP com elicitaçãolink image 21

Vamos criar um servidor MCP que funciona como um buscador de viagens. Assim, ele solicitará dados ao usuário. Todas as viagens possíveis serão armazenadas em uma variável. Não será um buscador real, mas um exemplo para mostrar a elicitação.

Implementação do servidor com elicitação.link image 22

Criamos duas classes do tipo enum para definir os diferentes tipos de viagens e as faixas de orçamento.

Criamos um dicionário para registrar todas as viagens possíveis.

Criamos uma função para extrair o valor da resposta da elicitação.

E, por último, implementamos a função intelligent_travel_booking_agent, que é a ferramenta que solicitará os dados ao usuário e salvará os resultados em uma variável.

A função envia as perguntas ao cliente, para que ele as envie ao usuário. O usuário responderá e o cliente enviará a resposta ao servidor.

No momento em que tiver os dados necessários do cliente, ele “procurará” a viagem que melhor se adapta às suas necessidades.

Criar ambiente virtual do servidorlink image 23

Primeiro criamos a pasta onde vamos desenvolvê-lo.

	
!mkdir MCP_elicitation_server
Copied

Criamos o ambiente com uv

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

Iniciamos o ambiente

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

Instalamos as bibliotecas necessárias

	
!cd MCP_elicitation_server && uv add fastmcp
Copied
	
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

Código do servidorlink image 24

	
%%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()
Copied
	
Writing MCP_elicitation_server/server.py

Cliente com elicitaçãolink image 25

Agora criamos o cliente com elicitação, ele executará a tool do servidor, receberá as perguntas do servidor e retornará as respostas.

Implementação do cliente com elicitaçãolink image 26

Criamos uma classe para o cliente com elicitação.

A classe se conecta ao servidor e executa a ferramenta do servidor.

Criar ambiente virtual do clientelink image 27

Primeiro criamos a pasta onde vamos desenvolvê-lo.

	
!mkdir MCP_elicitation_client
Copied

Criamos o ambiente com uv

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

Iniciamos o ambiente

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

Instalamos as bibliotecas necessárias

	
!cd MCP_elicitation_client && uv add fastmcp
Copied
	
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

Código do clientelink image 28

	
%%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)}")
Copied
	
Writing MCP_elicitation_client/client.py

Execuçãolink image 29

Como o servidor e o cliente foram criados com base no protocolo STDIO, não precisamos iniciar o servidor, portanto, executamos diretamente o cliente.

	
!cd MCP_elicitation_client && source .venv/bin/activate && uv run client.py ../MCP_elicitation_server/server.py
Copied
	
============================================================
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:

Vemos que primeiro ele pergunta sobre o tipo de viagem, escolhemos business.

	
!cd MCP_elicitation_client && source .venv/bin/activate && uv run client.py ../MCP_elicitation_server/server.py
Copied
	
============================================================
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:

Vemos que agora ele pergunta pela cidade de destino, escolhemos Paris.

	
!cd MCP_elicitation_client && source .venv/bin/activate && uv run client.py ../MCP_elicitation_server/server.py
Copied
	
============================================================
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:

Agora pergunte pela data da viagem, escolhemos next month

	
!cd MCP_elicitation_client && source .venv/bin/activate && uv run client.py ../MCP_elicitation_server/server.py
Copied
	
============================================================
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:

Pergunta sobre o número de pessoas, escolhemos 1

	
!cd MCP_elicitation_client && source .venv/bin/activate && uv run client.py ../MCP_elicitation_server/server.py
Copied
	
============================================================
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:

E, por último, pergunte pelo orçamento, escolhemos budget

	
!cd MCP_elicitation_client && source .venv/bin/activate && uv run client.py ../MCP_elicitation_server/server.py
Copied
	
============================================================
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:

Mostra uma viagem possível e nos pergunta se queremos confirmar, escolhemos confirm

	
!cd MCP_elicitation_client && source .venv/bin/activate && uv run client.py ../MCP_elicitation_server/server.py
Copied
	
============================================================
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]

Vemos que o servidor solicitou os dados ao usuário aos poucos para poder fazer uma reserva o mais personalizada possível.

Continuar lendo

MCP Durabilidade: Servidor e Cliente com Persistência para Tarefas de Longa Duração

MCP Durabilidade: Servidor e Cliente com Persistência para Tarefas de Longa Duração

Aprenda a construir servidor e cliente MCP com durabilidade para tarefas de longa duração. Tutorial completo do Model Context Protocol com persistência de dados usando SQLite, gerenciamento de tarefas em background e monitoramento em tempo real. Implemente migração de dados, processamento em lote e treinamento de modelos ML que sobrevivem a reinicializações do servidor. Código Python com FastMCP, recursos, ferramentas e padrões de durabilidade para aplicações enterprise.

Stream Informações em MCP: Guia Completo para Atualizações de Progresso em Tempo Real com FastMCP

Stream Informações em MCP: Guia Completo para Atualizações de Progresso em Tempo Real com FastMCP

Aprenda como implementar streaming em tempo real em aplicações MCP (Model Context Protocol) usando FastMCP. Este guia abrangente mostra como criar servidores e clientes MCP que suportam atualizações de progresso e informações streaming para tarefas de longa duração. Você construirá ferramentas habilitadas para streaming que fornecem feedback em tempo real durante processamento de dados, upload de arquivos, tarefas de monitoramento e outras operações que demandam muito tempo. Descubra como usar StreamableHttpTransport, implementar manipuladores de progresso com Context e criar barras de progresso visuais que melhoram a experiência do usuário ao trabalhar com aplicações MCP que requerem feedback contínuo.

Últimos posts -->

Você viu esses projetos?

Horeca chatbot

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

Chatbot conversacional para cozinheiros de hotéis e restaurantes. Um cozinheiro, gerente de cozinha ou serviço de quarto de um hotel ou restaurante pode falar com o chatbot para obter informações sobre receitas e menus. Mas também implementa agentes, com os quais pode editar ou criar novas receitas ou menus

Naviground

Naviground Naviground

Subtify

Subtify Subtify
Python
Whisper
Spaces

Gerador de legendas para vídeos no idioma que você desejar. Além disso, coloca uma legenda de cor diferente para cada pessoa

Ver todos os projetos -->

Quer aplicar IA no seu projeto? Entre em contato!

Quer melhorar com essas dicas?

Últimos tips -->

Use isso localmente

Os espaços do Hugging Face nos permitem executar modelos com demos muito simples, mas e se a demo quebrar? Ou se o usuário a deletar? Por isso, criei contêineres docker com alguns espaços interessantes, para poder usá-los localmente, aconteça o que acontecer. Na verdade, se você clicar em qualquer botão de visualização de projeto, ele pode levá-lo a um espaço que não funciona.

Flow edit

Flow edit Flow edit

Edite imagens com este modelo de Flow. Baseado em SD3 ou FLUX, você pode editar qualquer imagem e gerar novas

FLUX.1-RealismLora

FLUX.1-RealismLora FLUX.1-RealismLora
Ver todos os contêineres -->

Quer aplicar IA no seu projeto? Entre em contato!

Você quer treinar seu modelo com esses datasets?

short-jokes-dataset

Dataset com piadas em inglês

opus100

Dataset com traduções de inglês para espanhol

netflix_titles

Dataset com filmes e séries da Netflix

Ver mais datasets -->