|
|
import gradio as gr |
|
|
import random |
|
|
import json |
|
|
import uuid |
|
|
import os |
|
|
import copy |
|
|
from datetime import datetime, timezone |
|
|
from dotenv import load_dotenv |
|
|
|
|
|
|
|
|
from agentpay_sdk import AgentPayClient |
|
|
|
|
|
print("Starting MatchMaiker MCP server...") |
|
|
|
|
|
|
|
|
load_dotenv() |
|
|
|
|
|
|
|
|
|
|
|
try: |
|
|
agentpay_client = AgentPayClient(service_token=os.getenv("AGENTPAY_SERVICE_TOKEN", "")) |
|
|
print("AgentPay client initialized successfully") |
|
|
except Exception as e: |
|
|
print(f"Warning: AgentPay client initialization failed: {e}") |
|
|
agentpay_client = None |
|
|
|
|
|
|
|
|
PRICING = { |
|
|
"send_message": 100, |
|
|
"get_profile": 10 |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
DATA_DIR = "data" |
|
|
PROFILES_FILE = os.path.join(DATA_DIR, "profiles.json") |
|
|
QUESTIONNAIRE_FILE = os.path.join(DATA_DIR, "questionnaire.json") |
|
|
MESSAGES_FILE = os.path.join(DATA_DIR, "messages.json") |
|
|
|
|
|
def load_json_data(filepath, default_data=None): |
|
|
"""Loads JSON data from a file. Returns default_data if file not found or error.""" |
|
|
|
|
|
base_dir = os.path.dirname(os.path.abspath(__file__)) |
|
|
absolute_filepath = os.path.join(base_dir, filepath) if not os.path.isabs(filepath) else filepath |
|
|
|
|
|
try: |
|
|
|
|
|
file_dir = os.path.dirname(absolute_filepath) |
|
|
if not os.path.exists(file_dir): |
|
|
os.makedirs(file_dir, exist_ok=True) |
|
|
|
|
|
if not os.path.exists(absolute_filepath): |
|
|
with open(absolute_filepath, 'w') as f: |
|
|
effective_default = default_data |
|
|
if effective_default is None: |
|
|
if absolute_filepath.endswith("profiles.json"): |
|
|
effective_default = {} |
|
|
elif absolute_filepath.endswith("messages.json"): |
|
|
effective_default = [] |
|
|
else: |
|
|
effective_default = {} |
|
|
json.dump(effective_default, f, indent=2) |
|
|
return effective_default |
|
|
|
|
|
with open(absolute_filepath, 'r') as f: |
|
|
return json.load(f) |
|
|
except (IOError, json.JSONDecodeError) as e: |
|
|
print(f"Error loading {absolute_filepath}: {e}") |
|
|
if default_data is not None: return default_data |
|
|
if absolute_filepath.endswith("profiles.json"): return {} |
|
|
if absolute_filepath.endswith("messages.json"): return [] |
|
|
return {} |
|
|
|
|
|
def save_json_data(filepath, data): |
|
|
"""Saves Python data to a JSON file.""" |
|
|
base_dir = os.path.dirname(os.path.abspath(__file__)) |
|
|
absolute_filepath = os.path.join(base_dir, filepath) if not os.path.isabs(filepath) else filepath |
|
|
try: |
|
|
os.makedirs(os.path.dirname(absolute_filepath), exist_ok=True) |
|
|
with open(absolute_filepath, 'w') as f: |
|
|
json.dump(data, f, indent=2) |
|
|
return True |
|
|
except IOError as e: |
|
|
print(f"Error saving {absolute_filepath}: {e}") |
|
|
return False |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def new_profile(request: gr.Request): |
|
|
""" |
|
|
Generates and returns a dating profile questionnaire, a new public profile_id, |
|
|
and a new private auth_id. Also creates an initial profile stub. |
|
|
""" |
|
|
|
|
|
profile_id = f"user_{''.join(random.choices('abcdefghijklmnopqrstuvwxyz0123456789', k=8))}" |
|
|
auth_id = str(uuid.uuid4()) |
|
|
print(f"new_profile with Profile ID: {profile_id} and Auth ID: {auth_id}") |
|
|
|
|
|
|
|
|
questionnaire_data = load_json_data(QUESTIONNAIRE_FILE, default_data={"title": "Error Loading Questionnaire", "questions": []}) |
|
|
if not questionnaire_data.get("questions") or questionnaire_data.get("title") == "Error Loading Questionnaire": |
|
|
print(f"Critical Error: Could not load or parse questionnaire from {QUESTIONNAIRE_FILE}. Please ensure it exists and is valid JSON.") |
|
|
questionnaire_data = {"title": "Questionnaire Unavailable", "questions": []} |
|
|
|
|
|
|
|
|
profiles = load_json_data(PROFILES_FILE, default_data={}) |
|
|
|
|
|
timestamp = datetime.now(timezone.utc).isoformat() |
|
|
|
|
|
new_profile = { |
|
|
"profile_id": profile_id, |
|
|
"auth_id": auth_id, |
|
|
"created_at": timestamp, |
|
|
"updated_at": timestamp, |
|
|
"name": "", |
|
|
"gender": "", |
|
|
"profile_summary": "", |
|
|
"profile_image_filename": "default.jpg", |
|
|
"answers": {} |
|
|
} |
|
|
profiles[profile_id] = new_profile |
|
|
if not save_json_data(PROFILES_FILE, profiles): |
|
|
print(f"Critical Error: Failed to save profile for {profile_id} to {PROFILES_FILE}") |
|
|
|
|
|
|
|
|
|
|
|
instructions_for_agent = "You have received a `profile_id` (public identifier for this user\'s profile) and an `auth_id` (private key for authentication for this user). Please ask the user to store both securely. The `auth_id` must be sent as an `X-Auth-ID` header in subsequent requests that require authentication for this user (e.g., `update_profile_answers`, `get_matches`, `get_messages`, `get_profile` for own profile, `send_message`). The `profile_id` is used to publicly identify this user to others (e.g., in matches, or when sending/receiving messages). Before you proceed, please ask the user to update their MCP configuration to include their new Auth ID by adding the following to their mcp.json (or similar) configuration file: `\"matchmaker\": {\"command\": \"npx\", \"args\": [\"mcp-remote\", \"http://localhost:7860/gradio_api/mcp/sse\", \"--allow-http\", \"--header\", \"X-AUTH-ID:<your-auth-id>\"]}`, then to RESTART THE CLIENT (especially if you are Claude), or to try RECONNECTING (e.g. if you are Cursor or otherwise). Once they have done so, you must then walk the user through the questionnaire, preferably question by question, and collect the answers (in preparation to update the user's profile using update_profile_answers). If the user provides answers that are not in the list of valid answers, please ask them to provide a valid answer." |
|
|
instructions_for_user = "Your profile creation process has started! You\'ve been assigned a unique Profile ID and a secret Auth ID. Your AI agent will use these to manage your profile and interactions. Please walk through the questionnaire with your Agent, and provide your answers. You can upload a profile picture later." |
|
|
|
|
|
return { |
|
|
"profile_id": profile_id, |
|
|
"auth_id": auth_id, |
|
|
"questionnaire": questionnaire_data, |
|
|
"instructions_for_agent": instructions_for_agent, |
|
|
"instructions_for_user": instructions_for_user |
|
|
} |
|
|
|
|
|
def update_profile_answers(answers_payload_str: str, request: gr.Request): |
|
|
""" |
|
|
Updates a user's profile based on questionnaire answers. |
|
|
Requires X-Auth-ID header for authentication. |
|
|
Answers_payload_str is expected to be a JSON string. |
|
|
""" |
|
|
auth_id = request.headers.get("x-auth-id") |
|
|
if not auth_id: |
|
|
return {"status": "error", "message": "Authentication failed: X-Auth-ID header is missing."} |
|
|
print(f"update_profile_answers with Auth ID: {auth_id}") |
|
|
|
|
|
try: |
|
|
answers_payload = json.loads(answers_payload_str) |
|
|
if not isinstance(answers_payload, dict): |
|
|
raise json.JSONDecodeError("Payload is not a dictionary.", answers_payload_str, 0) |
|
|
except json.JSONDecodeError as e: |
|
|
return {"status": "error", "message": f"Invalid JSON format in answers_payload: {e}"} |
|
|
|
|
|
profiles = load_json_data(PROFILES_FILE, default_data={}) |
|
|
user_profile = None |
|
|
target_profile_id = None |
|
|
|
|
|
for pid, profile_data in profiles.items(): |
|
|
if profile_data.get("auth_id") == auth_id: |
|
|
user_profile = profile_data |
|
|
target_profile_id = pid |
|
|
break |
|
|
|
|
|
if not user_profile: |
|
|
return {"status": "error", "message": "Authentication failed: Invalid X-Auth-ID."} |
|
|
|
|
|
questionnaire = load_json_data(QUESTIONNAIRE_FILE, default_data={"questions": []}) |
|
|
questions_map = {q["id"]: q for q in questionnaire.get("questions", [])} |
|
|
|
|
|
updated_fields = False |
|
|
for question_id, answer_value in answers_payload.items(): |
|
|
question_details = questions_map.get(question_id) |
|
|
if not question_details: |
|
|
print(f"Warning: Received answer for unknown question_id '{question_id}'. Skipping.") |
|
|
continue |
|
|
|
|
|
if question_details.get("purpose") == "metadata": |
|
|
field_to_map = question_details.get("maps_to_field") |
|
|
if field_to_map: |
|
|
user_profile[field_to_map] = answer_value |
|
|
updated_fields = True |
|
|
else: |
|
|
print(f"Warning: Metadata question '{question_id}' has no valid 'maps_to_field'. Skipping.") |
|
|
elif question_details.get("purpose") == "matchmaking": |
|
|
user_profile["answers"][question_id] = answer_value |
|
|
updated_fields = True |
|
|
else: |
|
|
print(f"Warning: Question '{question_id}' has unknown purpose '{question_details.get('purpose')}'. Skipping.") |
|
|
|
|
|
if updated_fields: |
|
|
user_profile["updated_at"] = datetime.now(timezone.utc).isoformat() |
|
|
profiles[target_profile_id] = user_profile |
|
|
if not save_json_data(PROFILES_FILE, profiles): |
|
|
return {"status": "error", "message": "Failed to save profile updates."} |
|
|
|
|
|
return { |
|
|
"status": "success", |
|
|
"message": "Profile updated successfully.", |
|
|
"instructions_for_agent": "Profile answers updated. Next, ask if the user would like to upload a profile picture now. If so, you can use the 'upload_profile_picture' tool. Otherwise, you can do this later, and then call `get_matches` to find potential matches, or `get_profile` (using the user's `profile_id`) to view their newly created profile.", |
|
|
"instructions_for_user": "Your profile has been updated! You can now look for matches or view your profile." |
|
|
} |
|
|
|
|
|
def get_matches(request: gr.Request): |
|
|
""" |
|
|
Finds potential matches for the authenticated user. |
|
|
Requires X-Auth-ID header for authentication. |
|
|
For P1, this returns up to 3 random profiles, excluding the user's own. |
|
|
""" |
|
|
auth_id = request.headers.get("x-auth-id") |
|
|
if not auth_id: |
|
|
return {"status": "error", "message": "Authentication failed: X-Auth-ID header is missing."} |
|
|
print(f"get_matches with Auth ID: {auth_id}") |
|
|
|
|
|
profiles = load_json_data(PROFILES_FILE, default_data={}) |
|
|
|
|
|
requester_profile_id = None |
|
|
requester_profile = None |
|
|
for pid, profile_data in profiles.items(): |
|
|
if profile_data.get("auth_id") == auth_id: |
|
|
requester_profile_id = pid |
|
|
requester_profile = profile_data |
|
|
break |
|
|
|
|
|
if not requester_profile: |
|
|
return {"status": "error", "message": "Authentication failed: Invalid X-Auth-ID."} |
|
|
|
|
|
|
|
|
requester_gender = requester_profile.get("gender") |
|
|
requester_preference = requester_profile.get("answers", {}).get("q_gender_preference") |
|
|
|
|
|
|
|
|
if not requester_gender or not requester_preference: |
|
|
return { |
|
|
"status": "success", |
|
|
"matches": [], |
|
|
"instructions_for_agent": "The user has not specified their gender and/or gender preference in their profile. Please ask them to update their profile before getting matches.", |
|
|
"instructions_for_user": "Please complete your gender and preference information in your profile to get matches." |
|
|
} |
|
|
|
|
|
potential_matches_profiles = [] |
|
|
for pid, potential_match in profiles.items(): |
|
|
if pid == requester_profile_id or not potential_match.get("name"): |
|
|
continue |
|
|
|
|
|
match_gender = potential_match.get("gender") |
|
|
match_preference = potential_match.get("answers", {}).get("q_gender_preference") |
|
|
|
|
|
|
|
|
if not match_gender or not match_preference: |
|
|
continue |
|
|
|
|
|
|
|
|
gender_map = {"Man": "Men", "Woman": "Women"} |
|
|
|
|
|
requester_is_interested = ( |
|
|
requester_preference == "All" or |
|
|
requester_preference == gender_map.get(match_gender) |
|
|
) |
|
|
|
|
|
|
|
|
match_is_interested = ( |
|
|
match_preference == "All" or |
|
|
match_preference == gender_map.get(requester_gender) |
|
|
) |
|
|
|
|
|
if requester_is_interested and match_is_interested: |
|
|
potential_matches_profiles.append(potential_match) |
|
|
|
|
|
|
|
|
num_matches = min(len(potential_matches_profiles), 3) |
|
|
selected_matches = random.sample(potential_matches_profiles, k=num_matches) |
|
|
|
|
|
|
|
|
host = request.headers.get('host', 'localhost:7860') |
|
|
if host.startswith('localhost') or host.startswith('127.0.0.1'): |
|
|
protocol = 'http' |
|
|
else: |
|
|
protocol = 'https' |
|
|
base_url = f"{protocol}://{host}" |
|
|
|
|
|
matches_list = [] |
|
|
for match_profile in selected_matches: |
|
|
image_filename = match_profile.get("profile_image_filename") |
|
|
image_url = None |
|
|
if image_filename: |
|
|
image_url = f"{base_url}/gradio_api/file=data/profile_images/{image_filename}" |
|
|
|
|
|
matches_list.append({ |
|
|
"profile_id": match_profile.get("profile_id"), |
|
|
"name": match_profile.get("name"), |
|
|
"gender": match_profile.get("gender"), |
|
|
"profile_summary": match_profile.get("profile_summary"), |
|
|
"profile_image_url": image_url |
|
|
}) |
|
|
|
|
|
return { |
|
|
"status": "success", |
|
|
"matches": matches_list, |
|
|
"instructions_for_agent": "You have received a list of matches. For each match, you can call `get_profile` using their `profile_id` to get more details ($0.10 per profile). You can also use `send_message` to send a message to a match's `profile_id` ($1.00 per message). For each match, please format it in a nice card-like display (not raw JSON), including the match's name, gender, profile summary, and profile image (in a way that it should render in the chat client).", |
|
|
"instructions_for_user": "Here are some potential matches! Your AI agent can get more details on them ($0.10 per profile) or help you send a message ($1.00 per message). Or, if you don't like any of your matches, you can call `get_matches` again to get a new list (free)." |
|
|
} |
|
|
|
|
|
def get_profile(profile_id_to_get: str, request: gr.Request): |
|
|
""" |
|
|
Gets a user's full profile. |
|
|
Requires X-Auth-ID header for authentication. |
|
|
Access is free for viewing one's own profile. |
|
|
Accessing another user's profile costs $0.10 and requires X-AGENTPAY-API-KEY. |
|
|
""" |
|
|
|
|
|
auth_id = request.headers.get("x-auth-id") |
|
|
agentpay_api_key = request.headers.get("x-agentpay-api-key") |
|
|
|
|
|
if not auth_id: |
|
|
return {"status": "error", "message": "Authentication failed: X-Auth-ID header is missing."} |
|
|
|
|
|
print(f"get_profile with Auth ID: {auth_id}") |
|
|
|
|
|
profiles = load_json_data(PROFILES_FILE, default_data={}) |
|
|
|
|
|
requester_profile_id = None |
|
|
for pid, profile_data in profiles.items(): |
|
|
if profile_data.get("auth_id") == auth_id: |
|
|
requester_profile_id = pid |
|
|
break |
|
|
|
|
|
if not requester_profile_id: |
|
|
return {"status": "error", "message": "Authentication failed: Invalid X-Auth-ID."} |
|
|
|
|
|
target_profile = profiles.get(profile_id_to_get) |
|
|
|
|
|
if not target_profile: |
|
|
return {"status": "error", "message": f"Profile with ID '{profile_id_to_get}' not found."} |
|
|
|
|
|
|
|
|
is_viewing_other = profile_id_to_get != requester_profile_id |
|
|
|
|
|
if is_viewing_other: |
|
|
|
|
|
if not agentpay_api_key: |
|
|
return {"status": "error", "message": "Payment failed: X-AGENTPAY-API-KEY header is required to view other profiles."} |
|
|
|
|
|
|
|
|
if not agentpay_client or not agentpay_client.validate_api_key(agentpay_api_key): |
|
|
return {"status": "error", "message": "Payment failed: Invalid AgentPay API key"} |
|
|
|
|
|
|
|
|
usage_id = str(uuid.uuid4()) |
|
|
amount_cents = PRICING["get_profile"] |
|
|
result = agentpay_client.consume( |
|
|
api_key=agentpay_api_key, |
|
|
amount_cents=amount_cents, |
|
|
usage_event_id=usage_id, |
|
|
metadata={"tool": "get_profile", "requester": requester_profile_id, "target": profile_id_to_get} |
|
|
) |
|
|
|
|
|
if not result.success: |
|
|
return {"status": "error", "message": f"Payment failed: {result.error_message}"} |
|
|
|
|
|
|
|
|
target_profile.pop("auth_id", None) |
|
|
|
|
|
|
|
|
host = request.headers.get('host', 'localhost:7860') |
|
|
if host.startswith('localhost') or host.startswith('127.0.0.1'): |
|
|
protocol = 'http' |
|
|
else: |
|
|
protocol = 'https' |
|
|
base_url = f"{protocol}://{host}" |
|
|
image_filename = target_profile.get("profile_image_filename") |
|
|
image_url = None |
|
|
if image_filename: |
|
|
image_url = f"{base_url}/gradio_api/file=data/profile_images/{image_filename}" |
|
|
|
|
|
target_profile['profile_image_url'] = image_url |
|
|
target_profile.pop("profile_image_filename", None) |
|
|
|
|
|
|
|
|
cost_incurred = 0.0 |
|
|
if is_viewing_other: |
|
|
cost_incurred = PRICING["get_profile"] / 100.0 |
|
|
instructions_for_agent = f"You have retrieved the profile for {profile_id_to_get}. A cost of {cost_incurred} was charged via AgentPay." |
|
|
instructions_for_user = f"Here is the profile for {profile_id_to_get}." |
|
|
else: |
|
|
instructions_for_agent = f"You have retrieved your own profile ({profile_id_to_get}). No cost was incurred." |
|
|
instructions_for_user = f"Here is your profile." |
|
|
|
|
|
return { |
|
|
"status": "success", |
|
|
"profile": target_profile, |
|
|
"cost_incurred_usd": cost_incurred, |
|
|
"instructions_for_agent": instructions_for_agent, |
|
|
"instructions_for_user": instructions_for_user |
|
|
} |
|
|
|
|
|
def send_message(receiver_profile_id: str, content: str, request: gr.Request = None): |
|
|
""" |
|
|
Sends a message to a match. |
|
|
Requires X-Auth-ID header for authentication and X-AGENTPAY-API-KEY for payment. |
|
|
Costs $1.00 per message. |
|
|
""" |
|
|
|
|
|
auth_id = request.headers.get("x-auth-id") |
|
|
agentpay_api_key = request.headers.get("x-agentpay-api-key") |
|
|
|
|
|
if not auth_id: |
|
|
return {"status": "error", "message": "Authentication failed: X-Auth-ID header is missing."} |
|
|
|
|
|
if not agentpay_api_key: |
|
|
return {"status": "error", "message": "Payment failed: X-AGENTPAY-API-KEY header is missing."} |
|
|
|
|
|
|
|
|
if not agentpay_client or not agentpay_client.validate_api_key(agentpay_api_key): |
|
|
return {"status": "error", "message": "Payment failed: Invalid AgentPay API key"} |
|
|
|
|
|
print(f"send_message with Auth ID: {auth_id}") |
|
|
|
|
|
profiles = load_json_data(PROFILES_FILE, default_data={}) |
|
|
|
|
|
sender_profile_id = None |
|
|
for pid, profile_data in profiles.items(): |
|
|
if profile_data.get("auth_id") == auth_id: |
|
|
sender_profile_id = pid |
|
|
break |
|
|
|
|
|
if not sender_profile_id: |
|
|
return {"status": "error", "message": "Authentication failed: Invalid X-Auth-ID."} |
|
|
|
|
|
if receiver_profile_id not in profiles: |
|
|
return {"status": "error", "message": "Receiver profile ID not found."} |
|
|
|
|
|
|
|
|
usage_id = str(uuid.uuid4()) |
|
|
amount_cents = PRICING["send_message"] |
|
|
result = agentpay_client.consume( |
|
|
api_key=agentpay_api_key, |
|
|
amount_cents=amount_cents, |
|
|
usage_event_id=usage_id, |
|
|
metadata={"tool": "send_message", "sender": sender_profile_id, "receiver": receiver_profile_id} |
|
|
) |
|
|
|
|
|
if not result.success: |
|
|
return {"status": "error", "message": f"Payment failed: {result.error_message}"} |
|
|
|
|
|
messages = load_json_data(MESSAGES_FILE, default_data=[]) |
|
|
|
|
|
new_message = { |
|
|
"message_id": str(uuid.uuid4()), |
|
|
"sender_profile_id": sender_profile_id, |
|
|
"receiver_profile_id": receiver_profile_id, |
|
|
"content": content, |
|
|
"timestamp": datetime.now(timezone.utc).isoformat(), |
|
|
"read_status": False |
|
|
} |
|
|
|
|
|
messages.append(new_message) |
|
|
|
|
|
if not save_json_data(MESSAGES_FILE, messages): |
|
|
return {"status": "error", "message": "Failed to save message."} |
|
|
|
|
|
return { |
|
|
"status": "success", |
|
|
"message_id": new_message["message_id"], |
|
|
"cost_incurred_usd_cents": amount_cents, |
|
|
"instructions_for_agent": f"Message sent successfully to {receiver_profile_id}. A cost of ${amount_cents/100:.2f} was charged via AgentPay. You can get all messages for the user with `get_messages`.", |
|
|
"instructions_for_user": f"Your message has been sent to {receiver_profile_id}!" |
|
|
} |
|
|
|
|
|
def get_messages(request: gr.Request): |
|
|
""" |
|
|
Gets all messages for the authenticated user (sent and received). |
|
|
Marks retrieved messages where the user is the receiver as read for subsequent calls. |
|
|
Requires X-Auth-ID header for authentication. |
|
|
""" |
|
|
auth_id = request.headers.get("x-auth-id") |
|
|
if not auth_id: |
|
|
return {"status": "error", "message": "Authentication failed: X-Auth-ID header is missing."} |
|
|
print(f"get_messages with Auth ID: {auth_id}") |
|
|
|
|
|
profiles = load_json_data(PROFILES_FILE, default_data={}) |
|
|
|
|
|
user_profile_id = None |
|
|
for pid, profile_data in profiles.items(): |
|
|
if profile_data.get("auth_id") == auth_id: |
|
|
user_profile_id = pid |
|
|
break |
|
|
|
|
|
if not user_profile_id: |
|
|
return {"status": "error", "message": "Authentication failed: Invalid X-Auth-ID."} |
|
|
|
|
|
all_messages = load_json_data(MESSAGES_FILE, default_data=[]) |
|
|
|
|
|
|
|
|
messages_for_user = copy.deepcopy([ |
|
|
msg for msg in all_messages |
|
|
if msg.get("sender_profile_id") == user_profile_id or msg.get("receiver_profile_id") == user_profile_id |
|
|
]) |
|
|
|
|
|
|
|
|
messages_for_user.sort(key=lambda x: x.get("timestamp", ""), reverse=True) |
|
|
|
|
|
|
|
|
needs_save = False |
|
|
for i, original_msg in enumerate(all_messages): |
|
|
|
|
|
if original_msg.get("receiver_profile_id") == user_profile_id and not original_msg.get("read_status"): |
|
|
all_messages[i]["read_status"] = True |
|
|
needs_save = True |
|
|
|
|
|
|
|
|
if needs_save: |
|
|
if not save_json_data(MESSAGES_FILE, all_messages): |
|
|
|
|
|
print("Error: Could not update read_status for messages in the database.") |
|
|
|
|
|
|
|
|
|
|
|
return { |
|
|
"status": "success", |
|
|
"messages": messages_for_user, |
|
|
"instructions_for_agent": "You have received all messages for the user. Messages they received in this batch have now been marked as 'read' on the server.", |
|
|
"instructions_for_user": "Here are your messages." |
|
|
} |
|
|
|
|
|
def upload_profile_picture(image_upload, request: gr.Request): |
|
|
""" |
|
|
Uploads a profile picture for the authenticated user. |
|
|
The new filename will be based on the user's profile_id. |
|
|
Requires X-Auth-ID header for authentication. |
|
|
""" |
|
|
auth_id = request.headers.get("x-auth-id") |
|
|
if not auth_id: |
|
|
return {"status": "error", "message": "Authentication failed: X-Auth-ID header is missing."} |
|
|
|
|
|
if image_upload is None: |
|
|
return {"status": "error", "message": "No image file provided."} |
|
|
|
|
|
profiles = load_json_data(PROFILES_FILE, default_data={}) |
|
|
|
|
|
user_profile = None |
|
|
target_profile_id = None |
|
|
for pid, profile_data in profiles.items(): |
|
|
if profile_data.get("auth_id") == auth_id: |
|
|
user_profile = profile_data |
|
|
target_profile_id = pid |
|
|
break |
|
|
|
|
|
if not user_profile: |
|
|
return {"status": "error", "message": "Authentication failed: Invalid X-Auth-ID."} |
|
|
|
|
|
|
|
|
temp_path = image_upload |
|
|
|
|
|
|
|
|
file_ext = os.path.splitext(temp_path)[1] |
|
|
if not file_ext: |
|
|
file_ext = ".png" |
|
|
|
|
|
|
|
|
new_filename = f"{target_profile_id}{file_ext}" |
|
|
|
|
|
|
|
|
base_dir = os.path.dirname(os.path.abspath(__file__)) |
|
|
destination_path = os.path.join(base_dir, "data", "profile_images", new_filename) |
|
|
|
|
|
try: |
|
|
|
|
|
os.rename(temp_path, destination_path) |
|
|
except Exception as e: |
|
|
return {"status": "error", "message": f"Failed to save image file: {e}"} |
|
|
|
|
|
|
|
|
user_profile["profile_image_filename"] = new_filename |
|
|
user_profile["updated_at"] = datetime.now(timezone.utc).isoformat() |
|
|
profiles[target_profile_id] = user_profile |
|
|
|
|
|
if not save_json_data(PROFILES_FILE, profiles): |
|
|
return {"status": "error", "message": "Failed to update profile with new image filename."} |
|
|
|
|
|
host = request.headers.get('host', 'localhost:7860') |
|
|
if host.startswith('localhost') or host.startswith('127.0.0.1'): |
|
|
protocol = 'http' |
|
|
else: |
|
|
protocol = 'https' |
|
|
base_url = f"{protocol}://{host}" |
|
|
image_url = f"{base_url}/gradio_api/file=data/profile_images/{new_filename}" |
|
|
|
|
|
return { |
|
|
"status": "success", |
|
|
"message": "Profile picture updated successfully.", |
|
|
"new_image_url": image_url |
|
|
} |
|
|
|
|
|
def print_headers(text, request: gr.Request): |
|
|
"""Print the headers of the request for debugging purposes.""" |
|
|
print(f"Headers for print_headers request: {request.headers}") |
|
|
print(f"Text for print_headers: {text}") |
|
|
return f"Printed headers and text: {text}" |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
headers_demo = gr.Interface( |
|
|
fn=print_headers, |
|
|
inputs=gr.Textbox(label="Input Text"), |
|
|
outputs=gr.Textbox(label="Output Text (same as input)"), |
|
|
title="Headers Debug", |
|
|
description="Prints request headers to the console. Check your terminal." |
|
|
) |
|
|
|
|
|
|
|
|
new_profile_demo = gr.Interface( |
|
|
fn=new_profile, |
|
|
inputs=None, |
|
|
outputs=gr.JSON(label="Questionnaire, IDs, and Instructions"), |
|
|
title="Dating Profile Questionnaire", |
|
|
description="Generates a new user dating profile and returns a questionnaire, Profile ID, and Auth ID. (Agent-triggered MCP tool)" |
|
|
) |
|
|
|
|
|
|
|
|
|
|
|
update_profile_answers_demo = gr.Interface( |
|
|
fn=update_profile_answers, |
|
|
inputs=[gr.Textbox(label="Answers Payload (JSON string)", lines=5)], |
|
|
outputs=gr.JSON(label="Update Status"), |
|
|
title="Update Profile Answers", |
|
|
description="Updates a user's profile with answers to the questionnaire. Requires X-Auth-ID header." |
|
|
) |
|
|
|
|
|
|
|
|
|
|
|
get_matches_demo = gr.Interface( |
|
|
fn=get_matches, |
|
|
inputs=None, |
|
|
outputs=gr.JSON(label="Matches"), |
|
|
title="Get Matches", |
|
|
description="Gets a list of potential matches for the authenticated user. Requires X-Auth-ID header. FREE service." |
|
|
) |
|
|
|
|
|
|
|
|
|
|
|
get_profile_demo = gr.Interface( |
|
|
fn=get_profile, |
|
|
inputs=[gr.Textbox(label="Profile ID to Get")], |
|
|
outputs=gr.JSON(label="Profile Details"), |
|
|
title="Get Profile", |
|
|
description="Gets the full profile for a given Profile ID. Requires X-Auth-ID header. Free for own profile, $0.10 for others (requires X-AGENTPAY-API-KEY)." |
|
|
) |
|
|
|
|
|
|
|
|
|
|
|
send_message_demo = gr.Interface( |
|
|
fn=send_message, |
|
|
inputs=[ |
|
|
gr.Textbox(label="Receiver Profile ID"), |
|
|
gr.Textbox(label="Message Content", lines=5) |
|
|
], |
|
|
outputs=gr.JSON(label="Send Status"), |
|
|
title="Send Message", |
|
|
description="Sends a message to another user. Requires X-Auth-ID and X-AGENTPAY-API-KEY headers. ($1.00 per message)" |
|
|
) |
|
|
|
|
|
|
|
|
|
|
|
get_messages_demo = gr.Interface( |
|
|
fn=get_messages, |
|
|
inputs=None, |
|
|
outputs=gr.JSON(label="Messages"), |
|
|
title="Get Messages", |
|
|
description="Gets all messages sent or received by the authenticated user. Requires X-Auth-ID header." |
|
|
) |
|
|
|
|
|
|
|
|
|
|
|
upload_profile_picture_demo = gr.Interface( |
|
|
fn=upload_profile_picture, |
|
|
inputs=[gr.Image(type="filepath", label="Upload Profile Picture")], |
|
|
outputs=gr.JSON(label="Upload Status"), |
|
|
title="Upload Profile Picture", |
|
|
description="Uploads a profile picture for the authenticated user. Requires X-Auth-ID header." |
|
|
) |
|
|
|
|
|
|
|
|
|
|
|
demo = gr.TabbedInterface( |
|
|
[new_profile_demo, update_profile_answers_demo, get_matches_demo, get_profile_demo, send_message_demo, get_messages_demo, upload_profile_picture_demo, headers_demo], |
|
|
["New Profile", "Update Profile Answers", "Get Matches", "Get Profile", "Send Message", "Get Messages", "Upload Profile Picture", "Headers Debug"] |
|
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
|
|
|
|
base_dir = os.path.dirname(os.path.abspath(__file__)) |
|
|
allowed_images_path = os.path.join(base_dir, "data", "profile_images") |
|
|
|
|
|
with gr.Blocks() as app: |
|
|
gr.Markdown(""" |
|
|
# MatchMaiker: MCP-Native Dating Platform 🩵 |
|
|
|
|
|
## **Turn your AI agent into the ultimate wingman or wingwoman!** |
|
|
|
|
|
MatchMaiker is the first MCP-native dating platform, demonstrating the power of fully embedded, end-to-end agentic applications. |
|
|
|
|
|
### **Why is this interesting?** |
|
|
- **The user and product experience:** A full, E2E, MCP-native application, from onboarding through monetization (and yes, it's a dating app!) |
|
|
- **The infrastructure:** Actually building these kinds of MCP-native experiences, especially payments, by integrating [AgentPay](https://agentpay.me). |
|
|
|
|
|
### **Key Features:** |
|
|
- **New Profile:** Sign up, get your Auth ID, and answer some profile questions—the best part is that AI can help you with all the answers! |
|
|
- **Update Profile:** Once you're ready, the agent will help you update your profile with your responses. It can do this multiple times, and helps you polish it. |
|
|
- **Get Matches:** Based on your profile and preferences, MatchMaiker will help you find you the best matches, returning summaries of each. |
|
|
- **Full Profiles:** Fetch full profiles for anyone you're interested in. As a demonstration of MCP-native payments, we integrated AgentPay here ($0.10 per profile). |
|
|
- **Send Messages:** Send messages to prospective dates. As another demonstration of MCP-native payments, we integrated AgentPay here, too ($1.00 per message). |
|
|
- **Check Messages:** Have full-fledged conversations with your dates via MatchMaiker, complete with a read/unread inbox at your fingertips. |
|
|
|
|
|
## **Try it out!** |
|
|
|
|
|
As a fully MCP-native application, the experience is best enjoyed in your own MCP client. |
|
|
|
|
|
**Set it up in your own MCP client (e.g. Claude Desktop):** [📖 Check out the README](https://huggingface.co/spaces/Agents-MCP-Hackathon/MatchMaiker/blob/main/README.md) |
|
|
|
|
|
**Video Demo:** You can also get a quick preview of the experience in the video below (or [watch it on Loom](https://www.loom.com/share/465724e5ef914860978ec590b461f525?sid=6a60fb9a-954f-4850-9394-550937692388)): |
|
|
""") |
|
|
gr.Video(value="data/demo.mp4", label="Video Demo") |
|
|
gr.Markdown(""" |
|
|
|
|
|
--- |
|
|
|
|
|
*Built by the AgentPay team. [Learn more](https://agentpay.me) / hello@agentpay.me* |
|
|
|
|
|
--- |
|
|
""") |
|
|
demo.render() |
|
|
app.launch(mcp_server=True, allowed_paths=[allowed_images_path, "static", "data"]) |
|
|
|