sigma / app.py
Aktraiser
probleme init
0f2b5e7
#!/usr/bin/env python3
"""
🎨 Figma MCP Server - Hébergé sur Hugging Face Spaces
Serveur MCP pour contrôler Figma via Claude/Cursor avec la vraie API REST
"""
import gradio as gr
import asyncio
import json
import logging
from PIL import Image
import base64
import io
# Configuration du logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Import de tous les outils MCP depuis le dossier tools
# Gradio détectera automatiquement toutes les fonctions avec docstrings/type hints
try:
from tools import *
logger.info("✅ Tous les outils MCP importés avec succès")
except Exception as e:
logger.error(f"❌ Erreur d'import des outils MCP: {e}")
raise
# === CONFIGURATION DE L'APPLICATION GRADIO ===
def setup_demo():
"""Configure l'interface Gradio pour le serveur MCP"""
with gr.Blocks(
title="🎨 Figma MCP Server",
theme=gr.themes.Soft(),
) as demo:
gr.Markdown("""
# 🎨 Figma MCP Server
**Serveur MCP pour contrôler Figma via Claude/Cursor avec l'API REST**
## 📋 **Instructions de configuration :**
### 1. **Obtenir un token Figma :**
- Aller sur [Figma Settings > Personal Access Tokens](https://www.figma.com/settings)
- Créer un nouveau token
- Copier le token (commence par `figd_` ou `figc_`)
### 2. **Obtenir l'ID d'un fichier :**
- Ouvrir votre fichier Figma
- Copier l'ID depuis l'URL : `https://www.figma.com/file/FILE_ID/nom-du-fichier`
### 3. **Configurer Claude/Cursor :**
```json
{
"mcpServers": {
"figma": {
"command": "sse",
"args": ["https://aktraiser-sigma.hf.space/gradio_api/mcp/sse"]
}
}
}
```
""")
# Interface de test (optionnelle)
with gr.Tab("🧪 Test"):
with gr.Row():
token_input = gr.Textbox(
placeholder="figd_...",
label="Token Figma",
type="password"
)
token_btn = gr.Button("Configurer Token")
with gr.Row():
file_input = gr.Textbox(
placeholder="ID du fichier",
label="ID du fichier Figma"
)
file_btn = gr.Button("Configurer Fichier")
status_output = gr.Textbox(label="Status", lines=3)
# Actions de test
with gr.Row():
test_info_btn = gr.Button("📄 Info Fichier")
test_comments_btn = gr.Button("📝 Commentaires")
test_user_btn = gr.Button("👤 Info Utilisateur")
# Nouveaux boutons pour les infos utilisateur détaillées
with gr.Row():
test_user_detailed_btn = gr.Button("👤 Profil Détaillé")
test_teams_btn = gr.Button("🏢 Mes Équipes")
test_permissions_btn = gr.Button("🔐 Permissions")
with gr.Row():
test_stats_btn = gr.Button("📊 Stats Workspace")
with gr.Row():
test_limitations_btn = gr.Button("📚 Limitations API")
# Connexions des événements
token_btn.click(
configure_figma_token,
inputs=[token_input],
outputs=[status_output]
)
file_btn.click(
configure_figma_file_id,
inputs=[file_input],
outputs=[status_output]
)
test_info_btn.click(
get_figma_file_info,
outputs=[status_output]
)
test_comments_btn.click(
get_figma_comments,
outputs=[status_output]
)
test_user_btn.click(
get_figma_user_info,
outputs=[status_output]
)
test_user_detailed_btn.click(
get_figma_user_detailed_info,
outputs=[status_output]
)
test_teams_btn.click(
list_figma_user_teams,
outputs=[status_output]
)
test_permissions_btn.click(
get_figma_current_user_permissions,
outputs=[status_output]
)
test_stats_btn.click(
get_figma_workspace_usage_stats,
outputs=[status_output]
)
test_limitations_btn.click(
get_figma_api_limitations_info,
outputs=[status_output]
)
gr.Markdown("""
---
### 🛠️ **Outils MCP disponibles (détection automatique) :**
**📋 Configuration :**
- `configure_figma_token(token)` - Configure le token d'accès
- `configure_figma_file_id(file_id)` - Configure l'ID du fichier
**📁 Navigation :**
- `get_figma_file_info()` - Récupère les infos du fichier
- `get_figma_comments()` - Récupère les commentaires
- `get_figma_user_info()` - Info utilisateur connecté
**👤 Compte utilisateur et équipe :**
- `get_figma_user_detailed_info()` - Informations détaillées de l'utilisateur (profil complet)
- `list_figma_user_teams()` - Liste toutes les équipes de l'utilisateur avec rôles et plans
- `get_figma_team_info(team_id)` - Infos détaillées d'une équipe (plan, limites, stockage)
- `get_figma_current_user_permissions()` - Permissions dans le fichier actuel (via Plugin API)
- `get_figma_workspace_usage_stats()` - Statistiques d'utilisation de l'espace de travail
- `list_figma_team_projects(team_id)` - Projets d'une équipe
- `get_figma_api_limitations_info()` - Explique les limitations API Plugin vs REST
**🎨 Création d'éléments de base (Figma Design) :**
- `create_figma_rectangle(x, y, width, height, name, color)` - Crée un rectangle
- `create_figma_frame(x, y, width, height, name)` - Crée un frame
- `create_figma_text(x, y, text, name, font_size)` - Crée un texte
**🟡 FigJam - Éléments de base :**
- `create_figjam_sticky_note(x, y, text, width, height)` - Post-it (défaut: 240×240px)
- `create_figjam_connector_between_elements(element1_name, element2_name, style)` - Connecteur entre éléments
- `create_figjam_shape_with_text(x, y, shape_type, text, width, height)` - Forme avec texte (défaut: 208×208px)
- `create_figjam_table(rows, columns, x, y)` - Tableau interactif
- `create_figjam_code_block(x, y, code, language)` - Bloc de code avec coloration syntaxique
**📐 FigJam - Zones et organisation :**
- `create_figjam_background_shape(x, y, width, height, color, title, corner_radius)` - Zone de fond rectangulaire
- `create_figjam_organized_zone(title, x, y, width, height, max_stickies)` - Zone avec grille de post-its
- `create_figjam_workshop_template(template_type, x, y)` - Templates d'atelier complets
**🎭 FigJam - Stickers et réactions :**
- `create_figjam_sticker(x, y, sticker_type, size)` - Stickers/emoji pour réactions
**🎯 Types disponibles :**
- **Formes:** rectangle, circle, triangle, diamond, star, hexagon
- **Stickers:** thumbs_up, thumbs_down, heart, star, fire, rocket, bulb, warning, check, cross, question, idea, clock, money, target, celebrate, thinking, confused
- **Templates:** retrospective, brainstorm, user_journey
**💡 Workflow recommandé :**
1. Créer une zone de fond avec `create_figjam_background_shape()`
2. Ajouter des post-its avec `create_figjam_sticky_note()`
3. Connecter les éléments avec `create_figjam_connector_between_elements()`
4. Ajouter des stickers pour les réactions avec `create_figjam_sticker()`
**✨ Toutes les fonctions génèrent du code JavaScript prêt à utiliser dans un plugin Figma !**
---
## 📚 **Documentation Gradio MCP**
Selon la [documentation officielle](https://www.gradio.app/guides/building-mcp-server-with-gradio) :
- Gradio détecte **automatiquement** toutes les fonctions avec docstrings et type hints
- Il suffit de `mcp_server=True` dans `.launch()`
- Pas besoin d'exposition manuelle des outils
""")
return demo
# === LANCEMENT DE L'APPLICATION ===
if __name__ == "__main__":
try:
demo = setup_demo()
logger.info("🚀 Démarrage du serveur MCP Figma...")
# Configuration pour Hugging Face Spaces avec MCP
# Gradio détectera automatiquement toutes les fonctions importées
demo.launch(
mcp_server=True, # 🔑 Active le serveur MCP avec détection automatique !
server_name="0.0.0.0",
server_port=7860,
share=False,
show_error=True
)
except Exception as e:
logger.error(f"❌ Erreur lors du lancement: {e}")
raise