File size: 32,550 Bytes
1b8d07e
 
 
a1c243a
c4472ea
1b8d07e
 
 
 
 
 
 
 
013d287
 
 
 
f1e41b8
013d287
 
 
 
 
 
 
 
 
 
a1c243a
 
1b8d07e
c4472ea
1b8d07e
f1e41b8
 
 
1b8d07e
 
 
 
 
 
17d1159
f1e41b8
1b8d07e
c4472ea
 
1b8d07e
 
a0a02f2
 
 
1b8d07e
 
a0a02f2
e5bc2ce
1b8d07e
 
 
013d287
1b8d07e
56acf73
 
 
 
1b8d07e
 
 
 
56acf73
1b8d07e
56acf73
013d287
1b8d07e
 
666da4c
1b8d07e
a1c243a
1b8d07e
a1c243a
1b8d07e
 
 
 
666da4c
1b8d07e
666da4c
013d287
1b8d07e
666da4c
 
 
 
a1c243a
 
 
013d287
e5bc2ce
 
a0a02f2
e5bc2ce
a0a02f2
e5bc2ce
1b8d07e
 
a1c243a
1b8d07e
a1c243a
1b8d07e
a1c243a
1b8d07e
3a3a253
 
 
1b8d07e
 
 
a0a02f2
 
a1c243a
e5bc2ce
f1e41b8
 
 
 
 
e5bc2ce
f1e41b8
a0a02f2
f1e41b8
a0a02f2
f1e41b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff0c7d8
 
 
 
 
 
 
f1e41b8
e5bc2ce
a0a02f2
 
935d8e1
f1e41b8
 
 
 
 
 
 
1b8d07e
 
 
 
 
 
 
a1c243a
 
a0a02f2
a1c243a
3a3a253
 
d1bad6c
 
a1c243a
 
 
 
17d9a60
a1c243a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b8d07e
a1c243a
1b8d07e
 
 
 
 
 
 
 
 
a1c243a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
462be19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b8d07e
 
a38a5ac
bc6f537
 
 
 
 
 
 
 
 
ff4ef71
bc6f537
ff4ef71
 
a0a02f2
 
 
 
1b8d07e
a1c243a
a0a02f2
de198d3
 
 
 
 
 
 
 
 
 
 
 
a901439
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1c243a
a0a02f2
a1c243a
 
4d15a0e
a1c243a
 
 
a0a02f2
a1c243a
 
 
7946fb5
a1c243a
a0a02f2
b33c1fc
 
a0a02f2
b33c1fc
a0a02f2
b33c1fc
a0a02f2
 
 
 
b33c1fc
a0a02f2
 
 
 
b33c1fc
a0a02f2
 
 
 
b33c1fc
 
a0a02f2
b33c1fc
a1c243a
b33c1fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0a02f2
b33c1fc
 
 
 
a1c243a
 
a0a02f2
 
1b8d07e
a0a02f2
1b8d07e
 
a0a02f2
1b8d07e
a0a02f2
1b8d07e
 
a0a02f2
1b8d07e
a0a02f2
63b1816
5deec59
a0a02f2
013d287
 
 
a0a02f2
5deec59
013d287
 
a0a02f2
1b8d07e
013d287
a0a02f2
4d15a0e
013d287
 
 
febc8d9
1b8d07e
a0a02f2
 
1b8d07e
 
a0a02f2
 
f1e41b8
a0a02f2
f1e41b8
1b8d07e
 
a0a02f2
f1e41b8
a0a02f2
f1e41b8
a0a02f2
f1e41b8
 
 
 
 
 
 
 
a0a02f2
013d287
a0a02f2
013d287
 
 
 
1b8d07e
a0a02f2
 
1b8d07e
a1c243a
 
013d287
a1c243a
 
 
1b8d07e
a0a02f2
 
1b8d07e
 
a0a02f2
1b8d07e
a0a02f2
 
1b8d07e
4d15a0e
a1c243a
a0a02f2
1b8d07e
a0a02f2
a1c243a
a0a02f2
 
a1c243a
 
a0a02f2
1b8d07e
a0a02f2
 
 
1b8d07e
a0a02f2
 
a1c243a
1b8d07e
a0a02f2
f1e41b8
 
 
 
a0a02f2
 
 
f1e41b8
a0a02f2
f1e41b8
a0a02f2
 
1b8d07e
a1c243a
8737852
a1c243a
8523d41
f1e41b8
 
8523d41
f1e41b8
8523d41
a1c243a
 
 
 
c4472ea
56acf73
a1c243a
 
 
 
7946fb5
a1c243a
1b8d07e
 
a0a02f2
1b8d07e
e5bc2ce
1b8d07e
a0a02f2
 
1b8d07e
 
a0a02f2
1b8d07e
 
e5bc2ce
a0a02f2
e5bc2ce
 
a0a02f2
e5bc2ce
 
 
 
 
a0a02f2
 
e5bc2ce
 
a0a02f2
 
e5bc2ce
 
1b8d07e
a0a02f2
1b8d07e
 
 
 
 
 
 
666da4c
1b8d07e
 
17d1159
 
 
 
 
 
a0a02f2
 
 
 
 
 
 
 
 
 
 
 
 
c1d74c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c7fc38
 
 
 
c1d74c6
7c7fc38
17d1159
7c7fc38
a0a02f2
 
 
17d1159
a0a02f2
 
 
 
 
 
 
7c7fc38
a0a02f2
 
 
 
17d1159
e5bc2ce
 
 
 
f1e41b8
e5bc2ce
 
 
f1e41b8
666da4c
e5bc2ce
 
1b8d07e
 
 
 
 
 
 
 
 
 
 
 
 
 
a1c243a
 
 
 
 
 
 
 
 
 
 
 
1b8d07e
 
a1c243a
1b8d07e
 
a1c243a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b8d07e
462be19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b8d07e
 
 
a1c243a
 
 
 
 
 
 
1b8d07e
a1c243a
 
 
 
 
 
 
 
1b8d07e
 
 
 
a1c243a
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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
import gradio as gr
import os
import sys
import json
from typing import List, Dict, Any

# Ajout du répertoire racine au path pour permettre les imports absolus 'src.xxx'
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))

from src.mcp_server import tools
from src.mcp_server.playground import get_playground_ui_handlers
from src.core.builder.proposal_generator import proposal_generator

# --- Configuration des Modèles ---
# Modèles simplifiés et performants pour le code
COMMON_MODELS = [
    "openai/gpt-oss-120b",
    "moonshotai/Kimi-K2-Instruct-0905"
]

PROVIDER_MODELS = {
    "together": COMMON_MODELS,
    "hyperbolic": COMMON_MODELS,
    "None": COMMON_MODELS,
    # Fallback pour les autres
    "default": COMMON_MODELS
}

# --- Wrappers pour Gradio UI (Exposed as MCP Tools) ---
# Ces wrappers permettent d'avoir une UI conviviale tout en exposant les fonctions via MCP avec des noms explicites pour les agents.

def step_1_initialisation_and_proposal(project_name, description, model_id, provider_id):
    """
    STEP 1: Starts a new tool project and uses AI to propose draft code.
    
    Call this AFTER `step_0...`. It initializes the project and sets the optional HF_TOKEN.
    
    This is the entry point for creating a new MCP tool. It returns a draft_id and a code proposal based on the description.
    
    Args:
        project_name: The technical name of the tool (e.g., 'weather-fetcher').
        description: A natural language description of what the tool should do, or a raw Swagger/OpenAPI JSON specification.
        model_id: The LLM model to use for code generation (default : 'moonshotai/Kimi-K2-Instruct-0905').
        provider_id: The inference provider to use. Options: 'together', 'hyperbolic'.
    """
    # 1. Initialisation du projet (type 'adhoc' par défaut)
    init_result = tools.init_project(project_name, description, type="adhoc")
    draft_id = init_result.get("draft_id", "")
    
    # 2. AI Proposal Generation
    gr.Info("AI code generation in progress...")
    print(f"🤖 Generating proposal for: {project_name} (Model: {model_id}, Provider: {provider_id})...")
    proposal = proposal_generator.generate_from_description(project_name, description, model=model_id, provider=provider_id)
    
    gr.Info("Proposal generated! Please validate in the next tab.")
    
    # 3. Retourne les données pour mettre à jour l'UI
    # Gère le cas où 'requirements' n'est pas renvoyé par le LLM
    reqs = proposal.get("requirements", [])
    out_comp = proposal.get("output_component", "text")
    
    # Conversion des objets complexes en string JSON pour l'UI Code
    inputs_str = json.dumps(proposal["inputs"], indent=2)
    reqs_str = json.dumps(reqs, indent=2)

    return (
        init_result,                # out_init (JSON)
        draft_id,                   # draft_id_logic (Textbox)
        proposal["python_code"],    # python_code (Code)
        inputs_str,                 # inputs_dict (Code)
        proposal["output_desc"],    # output_desc (Textbox)
        reqs_str,                   # requirements_box (Code)
        out_comp                    # output_component_ui (Dropdown)
    )

def step_2_logic_definition(draft_id: str, python_code: str, inputs: Any, output_desc: str, requirements: List[str], output_component: str = "text"):
    """
    STEP 2: Validates and saves the tool code.
    
    Call this AFTER `step_1...`. It saves the Python implementation into the draft before deployment.
    
    Args:
        draft_id: The unique ID of the project draft (returned by Step 1).
        python_code: The complete Python source code for the tool function.
        inputs: A dictionary (or JSON string) describing the input parameters (e.g. {"city": "Name of the city"}).
        output_desc: A description of what the tool returns.
        requirements: A list of Python dependencies (pip packages) required by the code (e.g. ["requests", "pandas"]).
        output_component: The type of Gradio component for output (text, image, audio, etc.).
    """
    # Pour l'interface UI, inputs est un dict.
    # Pour l'API MCP, inputs peut être un dict ou une string JSON.
    # tools.define_logic gère les deux cas maintenant.
    
    # On s'assure que inputs est bien transmis
    print(f"DEBUG [step_2_logic_definition]: inputs type={type(inputs)}")
    
    result = tools.define_logic(draft_id, python_code, inputs, output_desc, requirements, output_component)
    
    if "error" not in result:
        gr.Info("Code validated and saved! Ready to deploy.")
    else:
        gr.Info(f"Error: {result['error']}")
        
    return result

def step_3_deployment(draft_id):
    """
    STEP 3: Deploys the tool to a Hugging Face Space.
    
    Call this AFTER `step_2...`. It creates a new public Space (or updates it) with the tool's code.
    
    It requires the draf_id that you got from previous steps. 
    When success, it gives some info to give to the user to help him add the resulting MCP server in his clients.
    
    Args:
        draft_id: The unique ID of the project draft (from Step 1).
    """
    gr.Info("Deployment in progress... This may take a few minutes.")
    # Simplification: Always public, always new (overwrite/create), space name = project name
    result = tools.deploy_to_space(draft_id, visibility="public", space_target="new", target_space_name=None)
    
    status_msg = ""
    space_url_val = ""
    mcp_url_val = ""
    claude_config_val = ""
    
    if "error" not in result:
        space_url_val = result.get('url', '')
        gr.Info(f"Deployment successful! URL: {space_url_val}")
        
        status_msg = "### 🚀 Deployment successful!"
        
        # Construction de l'URL MCP
        mcp_url_val = space_url_val
        tool_name = "my-tool"
        
        try:
            if "huggingface.co/spaces/" in space_url_val:
                parts = space_url_val.split("huggingface.co/spaces/")
                if len(parts) > 1:
                    path = parts[1].strip("/")
                    if "/" in path:
                        user, space = path.split("/", 1)
                        tool_name = space
                        # Format direct url : https://user-space.hf.space
                        # Note: pour mcp-remote on utilise le endpoint /gradio_api/mcp/
                        mcp_url_val = f"https://{user}-{space}.hf.space/gradio_api/mcp/"
        except Exception:
            pass
            
        # Construction de la config Claude
        config_dict = {
            "mcpServers": {
                tool_name: {
                    "command": "npx",
                    "args": [
                        "mcp-remote",
                        mcp_url_val,
                        "--transport",
                        "streamable-http"
                    ]
                }
            }
        }
        claude_config_val = json.dumps(config_dict, indent=2)
        
        # Ajout d'un message proactif pour l'agent
        result["instructions_for_agent"] = (
            f"Deployment successful! Please inform the user that the tool is deployed on Hugging Face Spaces: {space_url_val} "
            f"and available via MCP: {mcp_url_val}. "
            "IMPORTANT: Tell the user it takes about 30 seconds for the Space to start up and become operational."
        )

    else:
        gr.Info(f"Deployment failed: {result.get('error')}")
        status_msg = f"### ❌ Deployment failed\n\nError: {result.get('error')}"
    
    # Retourne : 
    # 1. JSON result (pour out_deploy)
    # 2. Markdown status
    # 3. Space URL
    # 4. MCP URL
    # 5. Claude Config Code
    return json.dumps(result, indent=2), status_msg, space_url_val, mcp_url_val, claude_config_val

# Récupération des handlers du playground
reload_tools_handler, chat_response_handler = get_playground_ui_handlers()

# --- Exposition des outils MCP (API pure) ---
# Ces fonctions sont exposées directement aux LLMs via MCP, en plus de l'UI

def step_0_configuration(hf_user: str = None, hf_token: str = None, default_space: str = None):
    """
    STEP 0: Configures the MCEPTION server environment.
    
    This step is needed to set up the Hugging Face environment. 
    After that follow steps 1, 2, 3 in this order and keep track of the draft_id that you will receive. 
    The process for each tool finishes when step 3 is a success.
    You have to follow all the steps for a tool before handling the next tool.
    
    Args:
        hf_user: The Hugging Face username or organization (namespace) where Spaces will be deployed.
        default_space: The name of the default toolbox Space to use if no specific target is provided during deployment (e.g. 'my-tools').
        hf_token: (IF OVERRIDE EXPLICITLY NEEDED) The Hugging Face Write Token. If not provided here, it must be set in the server's environment variables.
    """
    # Note: In a real app with multi-user, this should be session-scoped or persistent.
    # Here we set env vars for the current process.
    if hf_user:
        os.environ["HF_USER"] = hf_user
    if hf_token:
        os.environ["HF_TOKEN"] = hf_token
    if default_space:
        os.environ["DEFAULT_SPACE"] = default_space
    
    return {
        "status": "success", 
        "message": f"Configuration updated. User: {os.environ.get('HF_USER')}, Space: {os.environ.get('DEFAULT_SPACE')}"
    }

def expert_step1_propose_implementation(project_name: str, description: str):
    """
    [Expert Tool - Step 1] Generates a Python implementation proposal without initializing a UI draft.
    
    Use this tool if you are an AI agent wanting to generate code from a spec before deciding to create a draft.
    
    Args:
        project_name: Name of the intended tool.
        description: The tool description or Swagger/OpenAPI specification.
    """
    return tools.propose_implementation(project_name, description)

def expert_step2_define_logic(draft_id: str, python_code: str, inputs_json: str, output_desc: str, requirements_json: str = "[]"):
    """
    [Expert Tool - Step 2] Defines the logic for a tool using JSON strings for complex arguments.
    Use this tool instead of `step_2_logic_definition` to avoid schema validation issues with complex nested JSON inputs.
    
    Args:
        draft_id: The draft ID returned by init.
        python_code: The complete Python code.
        inputs_json: A JSON string representing the inputs dictionary (e.g. '{"arg": "desc"}').
        output_desc: Description of the output.
        requirements_json: A JSON string representing the list of requirements (e.g. '["requests"]').
    """
    import json
    try:
        inputs = json.loads(inputs_json)
    except:
        inputs = inputs_json # Fallback if already dict or invalid
        
    try:
        if requirements_json:
            requirements = json.loads(requirements_json)
        else:
            requirements = []
    except:
        requirements = [requirements_json] if requirements_json else []

    return tools.define_logic(draft_id, python_code, inputs, output_desc, requirements)

def util_delete_tool(space_name: str, tool_name: str):
    """
    [Utility Tool] Deletes an existing tool from a deployed Space.
    Use this to clean up test tools or remove deprecated ones.
    
    Args:
        space_name: Name of the Space (e.g. 'my-toolbox' or 'user/my-toolbox').
        tool_name: Name of the tool to delete (e.g. 'strawberry_counter').
    """
    return tools.delete_tool(space_name, tool_name)

def util_get_tool_code(space_name: str, tool_name: str):
    """
    [Utility Tool] Retrieves the source code of an existing tool from a deployed Space.
    Use this to inspect or improve an existing tool.
    
    Args:
        space_name: Name of the Space.
        tool_name: Name of the tool.
    """
    return tools.get_tool_code(space_name, tool_name)

# --- Construction de l'interface ---

with gr.Blocks(title="MCePtion") as demo:
    # Calcul dynamique de l'URL de l'image pour éviter les problèmes de CORS sur HF Spaces
    _space_id = os.environ.get("SPACE_ID")
    if _space_id:
        # Sur un Space : lien absolu vers le fichier raw
        _header_image_url = f"https://huggingface.co/spaces/{_space_id}/resolve/main/assets/images/header_bg.jpeg"
    else:
        # En local : lien local via Gradio
        _header_image_url = "/file=assets/images/header_bg.jpeg"

    # Bandeau haut (Image croppée à ~40% de hauteur, focus haut)
    gr.HTML(f"""
    <div style="width: 100%; overflow: hidden; margin-bottom: 20px;">
        <img src="{_header_image_url}" style="width: 100%; height: 260px; object-fit: cover; object-position: top; display: block; border-radius: 8px;" alt="MCePtion Header">
    </div>
    """)
    gr.Markdown("# 🏭 MCEPTION is the MCP of your MCPs")
    gr.Markdown("This server allows you to create and deploy other MCP servers on Hugging Face Spaces.")

    with gr.Tab("0. Setup & How-to"):
        gr.Markdown("## Global Configuration")
        
        # Détermination de l'utilisateur par défaut
        # Priorité : HF_USER > SPACE_AUTHOR_NAME > SPACE_ID > vide
        _default_user = os.environ.get("HF_USER")
        if not _default_user:
            _default_user = os.environ.get("SPACE_AUTHOR_NAME")
        if not _default_user and os.environ.get("SPACE_ID"):
            try:
                _default_user = os.environ.get("SPACE_ID").split("/")[0]
            except:
                pass

        hf_user_profile = gr.Textbox(
            label="HF User Profile / Namespace", 
            value=_default_user or "",
            placeholder="e.g. alihmaou",
            info="Your default Hugging Face username or organization."
        )
        default_mcp_space_name = gr.Textbox(
            label="Default Toolbox Name",
            value=os.environ.get("DEFAULT_SPACE", "mymcpserver"),
            placeholder="e.g. mymcpserver",
            info="Default Space (Toolbox) name for additions (will be concatenated with user)."
        )
    
        hf_token_input = gr.Textbox(
            label="HF Write Token (Optional override)",
            type="password",
            placeholder="hf_...",
            info="Deployment token. If empty, uses the server's HF_TOKEN environment variable."
        )
            
        # Button to apply config (simple update of global variables/env for the session)
        btn_save_config = gr.Button("Save Configuration")
        
        def save_config_ui(user: str, space: str, token: str):
            if user: os.environ["HF_USER"] = user
            if space: os.environ["DEFAULT_SPACE"] = space
            if token: os.environ["HF_TOKEN"] = token
            gr.Info("Configuration saved!")
            return f"Configuration saved! User: {user}, Default Space: {space}"
            
        config_status = gr.Markdown("")
        btn_save_config.click(save_config_ui, inputs=[hf_user_profile, default_mcp_space_name, hf_token_input], outputs=config_status)
            
        gr.Markdown("## How to use this MCePtion server?")
        
        with gr.Row():
            with gr.Column("User Guide"):
                gr.Markdown("""
                ## Human Interface User Guide
                
                ### 1. Tool Creation
                *   Go to tab **1. Initialization**.
                *   Provide a name and describe what you want (or paste a Swagger).
                *   Click on "Initialize & Generate".
                
                ### 2. Code Validation
                *   Go to tab **2. Logic Definition**.
                *   Check the generated Python code and dependencies.
                *   Click on "Validate Code" to validate.
                
                ### 3. Deployment
                *   Go to tab **3. Deployment**.
                *   Choose "New" to create a new Space or "Existing" to add to a Toolbox.
                *   Click on "Deploy".
                
                ### 4. Test
                *   Use the **4. Playground** tab to test your new tool after initialization (approx. 1 minute).
                """)
            
            with gr.Column():
                # Calcul dynamique des URLs pour affichage
                _c_space_id = os.environ.get("SPACE_ID", None)
                _c_space_host = os.environ.get("SPACE_HOST", "localhost:7860")
                
                if _c_space_id:
                    _c_space_url = f"https://huggingface.co/spaces/{_c_space_id}"
                    _c_mcp_url = f"https://{_c_space_host}/gradio_api/mcp/"
                    _c_server_name = _c_space_id.split("/")[-1] if "/" in _c_space_id else _c_space_id
                else:
                    _c_space_url = "http://localhost:7860"
                    _c_mcp_url = "http://localhost:7860/gradio_api/mcp/"
                    _c_server_name = "metamcp-local"

                _c_claude_config = {
                    "mcpServers": {
                        _c_server_name: {
                            "command": "npx",
                            "args": [
                                "mcp-remote",
                                _c_mcp_url,
                                "--transport",
                                "streamable-http"
                            ]
                        }
                    }
                }
                _c_claude_config_str = json.dumps(_c_claude_config, indent=2)
                gr.Markdown("""## MCP Integration Settings""")
                gr.Code(label="URL of this space :", value=_c_space_url, language=None, interactive=False, lines=1)
                gr.Code(label="URL of MCP endpoint :", value=_c_mcp_url, language=None, interactive=False, lines=1)
                gr.Code(label="Claude Desktop Configuration", value=_c_claude_config_str, language="json", interactive=False)

            

    with gr.Tab("1. Initialization"):
        gr.Markdown("Start by initializing a new project.")
        
        project_name = gr.Textbox(label="e.g. Project Name (e.g. strawberry-counter, city-weather)...")
        
        project_desc = gr.Textbox(
            label="Tool Description or Specification (Swagger/OpenAPI JSON)",
            lines=10,
            placeholder="Describe what the tool should do, or paste the content of a swagger.json file here to generate an API client automatically."
        )
        
        with gr.Accordion("AI Settings (Advanced)", open=False):
            provider_id = gr.Dropdown(
                label="Inference Provider", 
                choices=["sambanova", "together", "None", "hyperbolic", "fal-ai", "replicate", "novita", "nebius", "cerebras", "fireworks", "groq"], 
                value="together",
                info="Select a specific provider."
            )
            
            model_id = gr.Dropdown(
                label="LLM Model", 
                value="moonshotai/Kimi-K2-Instruct-0905",
                choices=COMMON_MODELS,
                allow_custom_value=True,
                info="Choose a code-optimized model or type a new one."
            )
            
            # Dynamic model update
            def update_models(provider: str):
                models = PROVIDER_MODELS.get(provider, PROVIDER_MODELS["default"])
                return gr.update(choices=models, value=models[0] if models else "")

            provider_id.change(update_models, inputs=[provider_id], outputs=[model_id])

        btn_init = gr.Button("Initialize Project & Propose Code (AI)")
        out_init = gr.JSON(label="Result (Copy the draft_id)")
        

    with gr.Tab("2. Logic Definition"):
        gr.Markdown("Verify and refine the Python code and interface of your tool.")
        
        # Display draft_id as read-only to ensure propagation
        draft_id_logic = gr.Textbox(label="Draft ID", interactive=False)
        
        with gr.Row():
            # Left Column: Code
            with gr.Column(scale=2):
                python_code = gr.Code(language="python", label="Python Code (e.g. def count_r(word): ...)")
            
            # Right Column: Requirements, Inputs, Outputs
            with gr.Column(scale=1):
                # 1. Requirements
                requirements_box = gr.Code(language="json", label="Requirements (JSON List)", value='[]')
                
                # 2. Inputs
                inputs_dict = gr.Code(language="json", label="Inputs (JSON)", value='{"word": "text"}')
                
                # 3. Outputs
                output_desc = gr.Textbox(label="Output Description")
                output_component_ui = gr.Dropdown(
                    label="Output Type (Gradio Component)", 
                    choices=["text", "image", "audio", "video", "html", "json", "file"],
                    value="text",
                    interactive=True
                )
            
        btn_logic = gr.Button("Validate Code")
        out_logic = gr.JSON(label="Result")
            
        btn_logic.click(
            step_2_logic_definition, 
            inputs=[draft_id_logic, python_code, inputs_dict, output_desc, requirements_box, output_component_ui], 
            outputs=out_logic,
            api_name="step_2_logic_definition"
        )

    with gr.Tab("3. Deployment"):
        gr.Markdown("Deploy your tool to Hugging Face Spaces.")
        with gr.Row():
            draft_id_deploy = gr.Textbox(label="Draft ID")
            # Simplification: No other inputs needed
        
        # Deployment plan summary (dynamically calculated)
        deployment_summary = gr.Markdown("Waiting for Draft ID...")
        
        def update_deployment_summary(draft_id: str):
            if not draft_id:
                return "Waiting..."
            
            # Simplified logic mirroring tools.deploy_to_space
            default_space = os.environ.get("DEFAULT_SPACE")
            target = default_space if default_space else "New Space (Project Name)"
            mode = "ADD (Toolbox)" if default_space else "CREATE (New Space)"
            
            return f"""
            ### 📋 Deployment Summary
            
            *   **Mode:** {mode}
            *   **Target:** `{target}`
            *   **Visibility:** Public
            
            If you use a `DEFAULT_SPACE`, the tool will be added to your existing toolbox without overwriting other tools.
            Otherwise, a new dedicated Space will be created.
            """

        btn_deploy = gr.Button("Deploy to Spaces", variant="primary")
        
        out_status = gr.Markdown("")
        
        with gr.Row():
            # Using gr.Code because gr.Textbox(show_copy_button=True) is not supported in this Gradio version
            out_space_url = gr.Code(language=None, label="Hugging Face Space URL", interactive=False, lines=1)
            out_mcp_url = gr.Code(language=None, label="MCP Endpoint URL", interactive=False, lines=1)
            
        out_claude_config = gr.Code(language="json", label="Claude Desktop Configuration (add to claude_desktop_config.json)")
        
        with gr.Accordion("JSON Details (Debug)", open=False):
            out_deploy = gr.Code(language="json", label="Raw Result")
        
        # Mise à jour du résumé quand le draft_id change
        draft_id_deploy.change(update_deployment_summary, inputs=[draft_id_deploy], outputs=[deployment_summary])
        
        # Fonction pour extraire l'URL MCP directe et préremplir le playground
        def auto_fill_playground(mcp_url_val: str):
            if not mcp_url_val:
                return gr.update()
            return mcp_url_val

    # Câblage global des événements (une fois tous les composants définis)
    # 1. Init -> Remplissage auto de l'onglet 2 (Logic) et copie de l'ID vers onglet 3 (Deploy)
    btn_init.click(
        step_1_initialisation_and_proposal, 
        inputs=[project_name, project_desc, model_id, provider_id], 
        outputs=[out_init, draft_id_logic, python_code, inputs_dict, output_desc, requirements_box, output_component_ui],
        api_name="step_1_initialisation_and_proposal"
    ).then(
        fn=lambda x: x,
        inputs=[draft_id_logic],
        outputs=[draft_id_deploy]
    )

    with gr.Tab("4. Test & Playground (Smolagents)"):
        gr.Markdown("Immediately test your deployed MCP server.")
        
        with gr.Column():
            mcp_url_input = gr.Textbox(
                label="MCP Server URL", 
                placeholder="e.g. https://your-user-your-space.hf.space/gradio_api/mcp/sse",
                scale=3
            )
            btn_reload = gr.Button("🔄 Load Tools", scale=1)
        
        status_msg = gr.Markdown("")
        
        # Table adapted for tool display (wrap=True)
        tool_table = gr.DataFrame(
            headers=["Tool name", "Description", "Params"], 
            label="Detected Tools",
            wrap=True,
            interactive=False
        )
        
        gr.Markdown("""
        ### ⚙️ Smolagents Configuration
        To use this tool with smolagents in your code:
        ```python
        from smolagents import MCPClient
        # Direct HTTP Mode (recommended)
        client = MCPClient(url="SERVER_URL", structured_output=False) 
        ```
        """)
        
        gr.Markdown("### 🤖 Chat with your MCP Agent")
        chatbot = gr.ChatInterface(
            fn=chat_response_handler
        )

        btn_reload.click(
            fn=reload_tools_handler,
            inputs=[mcp_url_input],
            outputs=[tool_table, status_msg]
        )
        
    with gr.Tab("README"):
        # Lecture du fichier README.md
        readme_content = ""
        try:
            with open("README.md", "r", encoding="utf-8") as f:
                readme_content = f.read()
            
            # Remove Hugging Face YAML frontmatter if present
            if readme_content.startswith("---"):
                try:
                    # Find the end of the frontmatter (second '---')
                    # We start searching from index 3 to skip the first '---'
                    end_index = readme_content.find("---", 3)
                    if end_index != -1:
                        # Slice content after the second '---' and strip leading whitespace
                        readme_content = readme_content[end_index + 3:].lstrip()
                except Exception:
                    pass
                    
        except Exception as e:
            readme_content = f"Unable to load README.md: {str(e)}"
        # Le conteneur Row pour aligner les 3 colonnes horizontalement
        with gr.Row():
            
            # 1. Colonne vide à gauche (1 part)
            # min_width=0 est important pour que la colonne puisse rétrécir si besoin
            with gr.Column(scale=1, min_width=0):
                pass 
            
            # 2. Colonne centrale avec le contenu (3 parts)
            with gr.Column(scale=3):
                gr.Markdown(readme_content)
                
            # 3. Colonne vide à droite (1 part)
            with gr.Column(scale=1, min_width=0):
                pass
    
    with gr.Tab("EXAMPLES"):
        # Lecture du fichier Examples.md
        example_content = ""
        try:
            with open("assets/Examples.MD", "r", encoding="utf-8") as f:
                example_content = f.read()
        except Exception as e:
            example_content = f"Unable to load Examples.md: {str(e)}"
        
        # Le conteneur Row pour aligner les 3 colonnes horizontalement
        with gr.Row():
            
            # 1. Colonne vide à gauche (1 part)
            # min_width=0 est important pour que la colonne puisse rétrécir si besoin
            with gr.Column(scale=1, min_width=0):
                pass 
            
            # 2. Colonne centrale avec le contenu (3 parts)
            with gr.Column(scale=3):
                gr.Markdown(example_content)
                
            # 3. Colonne vide à droite (1 part)
            with gr.Column(scale=1, min_width=0):
                pass

    # Câblage différé du déploiement (pour avoir accès à mcp_url_input défini dans le Tab 4)
    btn_deploy.click(
        step_3_deployment, 
        inputs=[draft_id_deploy], 
        outputs=[out_deploy, out_status, out_space_url, out_mcp_url, out_claude_config],
        api_name="step_3_deployment"
    ).then(
        fn=auto_fill_playground,
        inputs=[out_mcp_url],
        outputs=[mcp_url_input]
    )

    # Exposition explicite des outils pour les agents MCP sans UI
    # Cela permet à ChatGPT/Claude d'appeler ces fonctions directement
    # Note: Les fonctions liées à l'UI sont déjà exposées, mais celles-ci sont plus propres pour une API.
    # Gradio expose automatiquement les fonctions utilisées dans l'interface, mais on peut ajouter des endpoints API spécifiques.
    # Cependant, avec mcp_server=True, Gradio expose TOUT ce qui est triggué.
    # Pour être sûr que 'propose_implementation' est dispo, on l'ajoute via un composant invisible ou une API route si possible.
    # Dans la version actuelle de Gradio MCP, seules les fonctions liées à des événements sont exposées.
    # On va donc créer une "API Box" invisible pour exposer cet outil spécifique.
    
    with gr.Accordion("API Tools (Invisible)", visible=False):
        api_input_name = gr.Textbox()
        api_input_desc = gr.Textbox()
        api_output = gr.JSON()
        
        # Configuration Tool
        api_conf_user = gr.Textbox()
        api_conf_token = gr.Textbox()
        api_conf_space = gr.Textbox()
        btn_api_conf = gr.Button("Configure API")
        btn_api_conf.click(
            step_0_configuration,
            inputs=[api_conf_user, api_conf_token, api_conf_space],
            outputs=[api_output],
            api_name="step_0_configuration"
        )
        
        btn_api_propose = gr.Button("Propose Implementation API")
        btn_api_propose.click(
            expert_step1_propose_implementation,
            inputs=[api_input_name, api_input_desc],
            outputs=[api_output],
            api_name="expert_step1_propose_implementation" # Nom de l'outil pour le LLM
        )
        
        # Exposition de mcp_define_logic
        api_draft_id = gr.Textbox()
        api_code = gr.Textbox()
        api_inputs_json = gr.Textbox()
        api_out_desc = gr.Textbox()
        api_reqs_json = gr.Textbox()
        
        btn_api_define = gr.Button("Define Logic API")
        btn_api_define.click(
            expert_step2_define_logic,
            inputs=[api_draft_id, api_code, api_inputs_json, api_out_desc, api_reqs_json],
            outputs=[api_output],
            api_name="expert_step2_define_logic"
        )
        
        # Utils
        api_util_space = gr.Textbox()
        api_util_tool = gr.Textbox()
        
        btn_util_delete = gr.Button("Delete Tool API")
        btn_util_delete.click(
            util_delete_tool,
            inputs=[api_util_space, api_util_tool],
            outputs=[api_output],
            api_name="util_delete_tool"
        )
        
        btn_util_get = gr.Button("Get Tool Code API")
        btn_util_get.click(
            util_get_tool_code,
            inputs=[api_util_space, api_util_tool],
            outputs=[api_output],
            api_name="util_get_tool_code"
        )

# --- Définition des Ressources et Prompts MCP ---

# On active les décorateurs s'ils sont dispos
if hasattr(gr, "mcp"):
    @gr.mcp.resource("list://drafts")
    def list_active_drafts() -> str:
        """Returns a list of currently active project drafts."""
        # Note: In a real app, this would query the session manager
        return "Active Drafts: [draft_id_1, draft_id_2]"

    @gr.mcp.prompt()
    def help_create_tool(topic: str = "general") -> str:
        """
        Provides a prompt template to help users create a new tool.
        Args:
            topic: The topic of the tool (e.g. 'data', 'fun', 'utility')
        """
        return f"I want to create a new MCP tool related to {topic}. Can you guide me through the initialization, logic definition, and deployment steps using the available tools?"

# Point d'entrée
if __name__ == "__main__":
    # Lancement avec mcp_server=True pour exposer les outils aux LLMs
    demo.launch(server_name="0.0.0.0", server_port=7860, mcp_server=True, show_error=True)