File size: 34,006 Bytes
4c571f8
 
 
 
 
9bfdb4b
eeb3194
c5f454e
 
 
 
 
b87473a
 
c5f454e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c571f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2630422
4c571f8
c30d3d4
4c571f8
 
 
 
 
2630422
9bfdb4b
4c571f8
 
 
 
 
 
 
 
eeb3194
 
4c571f8
2630422
183efb0
4c571f8
 
 
183efb0
 
 
2630422
4c571f8
 
2630422
4c571f8
 
 
 
 
c5f454e
 
4c571f8
 
 
 
 
 
 
 
 
eeb3194
 
 
 
 
 
c5f454e
 
eeb3194
c5f454e
eeb3194
 
 
 
 
 
 
 
 
 
 
 
 
c5f454e
eeb3194
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2630422
eeb3194
 
 
2630422
eeb3194
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a01596
eeb3194
 
 
9bfdb4b
 
 
 
 
 
c5f454e
 
9bfdb4b
c5f454e
4c571f8
9bfdb4b
 
 
2630422
9bfdb4b
c5f454e
9bfdb4b
2630422
9bfdb4b
c5f454e
2630422
9bfdb4b
 
2630422
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9bfdb4b
2630422
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f6f4f8
 
9bfdb4b
c30d3d4
 
 
 
 
 
 
2630422
9bfdb4b
3f6f4f8
2630422
 
 
 
 
3f6f4f8
 
 
2630422
3f6f4f8
2630422
3f6f4f8
9bfdb4b
 
 
 
987ae4a
c5f454e
9bfdb4b
 
 
4c571f8
9bfdb4b
 
 
c5f454e
9bfdb4b
c5f454e
 
 
 
 
9bfdb4b
c5f454e
 
9bfdb4b
 
 
 
 
c5f454e
9bfdb4b
 
 
 
 
 
 
 
 
 
 
c5f454e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9bfdb4b
 
 
2630422
c30d3d4
 
 
 
 
 
2630422
 
 
 
 
 
 
 
c5f454e
9bfdb4b
c5f454e
 
 
 
 
 
 
4c571f8
9bfdb4b
 
 
 
 
 
 
 
 
 
c5f454e
 
 
4c571f8
c5f454e
 
 
 
 
9bfdb4b
c5f454e
 
 
 
 
 
 
 
 
9bfdb4b
 
 
 
 
c5f454e
9bfdb4b
 
 
 
 
 
 
 
 
c5f454e
 
 
 
 
 
 
 
 
 
 
 
9bfdb4b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5f454e
 
9bfdb4b
 
 
 
 
 
 
 
 
c5f454e
 
9bfdb4b
c5f454e
9bfdb4b
 
 
 
 
c5f454e
9bfdb4b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2630422
 
 
 
 
 
c5f454e
 
2630422
 
 
 
 
 
 
 
 
 
c5f454e
2630422
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c30d3d4
 
 
 
 
 
 
2630422
 
 
 
 
 
 
9bfdb4b
 
4c571f8
 
9bfdb4b
 
 
 
 
4c571f8
 
 
 
 
 
 
 
 
 
 
2630422
 
4c571f8
 
c30d3d4
 
4c571f8
 
 
eeb3194
 
 
 
 
 
 
 
 
 
9bfdb4b
 
 
 
 
 
c5f454e
9bfdb4b
 
 
 
 
 
 
 
 
c5f454e
9bfdb4b
 
 
 
 
 
 
 
 
 
 
 
c5f454e
9bfdb4b
 
 
 
 
 
 
 
 
 
 
 
 
2630422
 
 
 
 
 
 
 
 
 
4c571f8
 
2630422
 
4c571f8
 
 
2630422
 
 
 
0ca3f64
5079f4f
 
 
20a9591
5079f4f
 
 
20a9591
 
fdbbcce
5079f4f
20a9591
5079f4f
 
20a9591
 
 
5079f4f
 
20a9591
 
17aa11b
 
20a9591
17aa11b
20a9591
 
fdbbcce
20a9591
17aa11b
5079f4f
 
 
20a9591
 
5079f4f
93247db
20a9591
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
import gradio as gr
import random
import json
import uuid
import os # Added for path joining
import copy # For deep copying message list
from datetime import datetime, timezone # Added timezone for UTC consistency
from dotenv import load_dotenv

# AgentPay SDK imports
from agentpay_sdk import AgentPayClient

print("Starting MatchMaiker MCP server...")

# Load environment variables
load_dotenv()

# --- AgentPay Configuration ---

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

# AgentPay pricing in cents
PRICING = {
    "send_message": 100,     # $1.00 = 100 cents
    "get_profile": 10  # $0.10 = 10 cents
}

# --- Start of JSON I/O Helper Functions ---

DATA_DIR = "data" # This will be relative to app.py, so matchmaker/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") # Though not used in this step

def load_json_data(filepath, default_data=None):
    """Loads JSON data from a file. Returns default_data if file not found or error."""
    # Construct path relative to this script's directory if not absolute
    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:
        # Ensure directory exists before trying to open file
        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: # questionnaire.json or other
                        effective_default = {} # Should be pre-populated, but as a fallback
                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

# --- End of JSON I/O Helper Functions ---

# --- Start of MCP Matchmaker Tools ---

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.
    """
    # 1. Generate profile_id and auth_id
    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}")

    # 2. Read questionnaire.json
    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": []} # Fallback

    # 3. Create new profile entry in profiles.json
    profiles = load_json_data(PROFILES_FILE, default_data={})
    # Ensure timestamp is timezone-aware (UTC)
    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}")
        # Decide how to handle this error - maybe return an error to the client?
    
    # 4. Return IDs, questionnaire data, and instructions
    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") # Headers are lowercased by Gradio/Starlette
    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 # Update the profile in the main dictionary
        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."}

    # Get the requester's gender and preference for matching logic
    requester_gender = requester_profile.get("gender")
    requester_preference = requester_profile.get("answers", {}).get("q_gender_preference")

    # If the user hasn't specified their gender/preference, we can't find matches.
    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 # Skip self and profiles with no name

        match_gender = potential_match.get("gender")
        match_preference = potential_match.get("answers", {}).get("q_gender_preference")

        # Handle cases where gender/preference might not be filled out for a profile
        if not match_gender or not match_preference:
            continue

        # Correctly map gender to preference strings
        gender_map = {"Man": "Men", "Woman": "Women"}
        
        requester_is_interested = (
            requester_preference == "All" or 
            requester_preference == gender_map.get(match_gender)
        )

        # Check if the potential match is interested in the requester
        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)

    # From the list of potential matches, randomly select up to 3
    num_matches = min(len(potential_matches_profiles), 3)
    selected_matches = random.sample(potential_matches_profiles, k=num_matches)

    # Construct base_url with correct protocol
    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.
    """
    # Extract headers directly
    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."}

    # Check if viewing another user's profile (requires payment)
    is_viewing_other = profile_id_to_get != requester_profile_id
    
    if is_viewing_other:
        # Require AgentPay API key for viewing other profiles
        if not agentpay_api_key:
            return {"status": "error", "message": "Payment failed: X-AGENTPAY-API-KEY header is required to view other profiles."}
        
        # Validate AgentPay API key directly
        if not agentpay_client or not agentpay_client.validate_api_key(agentpay_api_key):
            return {"status": "error", "message": "Payment failed: Invalid AgentPay API key"}
        
        # Charge for viewing other profile via AgentPay
        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}"}

    # For security, never return the auth_id
    target_profile.pop("auth_id", None)
    
    # Construct and add the full image URL, then remove the old filename key
    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)

    # Update cost and messaging based on whether payment was charged
    cost_incurred = 0.0
    if is_viewing_other:
        cost_incurred = PRICING["get_profile"] / 100.0  # Convert cents to dollars
        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.
    """
    # Extract headers directly
    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."}
    
    # Validate AgentPay API key directly
    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."}

    # Charge for sending message via AgentPay
    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 are unread when sent
    }
    
    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=[])
    
    # Use a deep copy to avoid modifying the list while iterating
    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
    ])

    # Sort messages by timestamp descending (newest first)
    messages_for_user.sort(key=lambda x: x.get("timestamp", ""), reverse=True)

    # Mark received messages as read and track if an update is needed
    needs_save = False
    for i, original_msg in enumerate(all_messages):
        # Check if this message is one of the user's messages and was received by them
        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

    # Save the updated message list back to the file if any message was marked as read
    if needs_save:
        if not save_json_data(MESSAGES_FILE, all_messages):
            # If saving fails, we should still return the messages, but log the error.
            print("Error: Could not update read_status for messages in the database.")
            # Depending on desired behavior, we could return an error status here.
            # For now, we will proceed to return the messages as requested.

    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."}

    # The 'image_upload' from gr.Image is a temporary file path
    temp_path = image_upload
    
    # Get the file extension
    file_ext = os.path.splitext(temp_path)[1]
    if not file_ext:
        file_ext = ".png" # Default to png if no extension

    # Create a new unique filename based on the user's profile_id
    new_filename = f"{target_profile_id}{file_ext}"
    
    # Construct the destination path
    base_dir = os.path.dirname(os.path.abspath(__file__))
    destination_path = os.path.join(base_dir, "data", "profile_images", new_filename)

    try:
        # Copy the uploaded file to its new permanent location
        os.rename(temp_path, destination_path)
    except Exception as e:
        return {"status": "error", "message": f"Failed to save image file: {e}"}

    # Update the profile with the new filename
    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}"

# --- End of MCP Matchmaker Tools ---

# --- Start of Gradio App Setup ---

#  Gradio interface for printing headers
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."
)

# --- Start of New Profile Questionnaire Interface ---
new_profile_demo = gr.Interface(
    fn=new_profile,
    inputs=None, # No direct input from user for this one, it's triggered by the agent
    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)"
)
# --- End of New Profile Questionnaire Interface ---

# --- Start of Update Profile Answers Interface ---
update_profile_answers_demo = gr.Interface(
    fn=update_profile_answers,
    inputs=[gr.Textbox(label="Answers Payload (JSON string)", lines=5)], # Agent provides this as a JSON string
    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."
)
# --- End of Update Profile Answers Interface ---

# --- Start of Get Matches Interface ---
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."
)
# --- End of Get Matches Interface ---

# --- Start of Get Profile Interface ---
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)."
)
# --- End of Get Profile Interface ---

# --- Start of Send Message Interface ---
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)"
)
# --- End of Send Message Interface ---

# --- Start of Get Messages Interface ---
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."
)
# --- End of Get Messages Interface ---

# --- Start of Upload Profile Picture Interface ---
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."
)
# --- End of Upload Profile Picture Interface ---

# Adjusted TabbedInterface to include the new tool
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__":
    # Construct the absolute path to the allowed directory, relative to this script's location
    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:** How to build 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="MatchMaiker Video Demo", autoplay=True)
        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"])