Severian commited on
Commit
4af80bb
·
verified ·
1 Parent(s): 98b6105

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -67
app.py CHANGED
@@ -1,7 +1,8 @@
 
1
  #!/usr/bin/env python3
2
  """
3
- 🎨 Figma MCP Server - Hébergé sur Hugging Face Spaces
4
- Serveur MCP pour contrôler Figma via Claude/Cursor avec la vraie API REST
5
  """
6
  import gradio as gr
7
  import asyncio
@@ -9,25 +10,25 @@ import json
9
  import logging
10
  from PIL import Image
11
  import base64
12
- import io
13
 
14
  # Configuration du logging
15
  logging.basicConfig(level=logging.INFO)
16
  logger = logging.getLogger(__name__)
17
 
18
- # Import de tous les outils MCP depuis le dossier tools
19
- # Gradio détectera automatiquement toutes les fonctions avec docstrings/type hints
20
  try:
21
  from tools import *
22
- logger.info("✅ Tous les outils MCP importés avec succès")
23
  except Exception as e:
24
- logger.error(f"❌ Erreur d'import des outils MCP: {e}")
25
  raise
26
 
27
- # === CONFIGURATION DE L'APPLICATION GRADIO ===
28
 
29
  def setup_demo():
30
- """Configure l'interface Gradio pour le serveur MCP"""
31
 
32
  with gr.Blocks(
33
  title="🎨 Figma MCP Server",
@@ -36,24 +37,24 @@ def setup_demo():
36
 
37
  gr.Markdown("""
38
  # 🎨 Figma MCP Server
39
- **Serveur MCP pour contrôler Figma via Claude/Cursor avec l'API REST**
40
 
41
  ## 📋 **Instructions de configuration :**
42
 
43
- ### 1. **Obtenir un token Figma :**
44
  - Aller sur [Figma Settings > Personal Access Tokens](https://www.figma.com/settings)
45
- - Créer un nouveau token
46
- - Copier le token (commence par `figd_` ou `figc_`)
47
 
48
- ### 2. **Obtenir l'ID d'un fichier :**
49
- - Ouvrir votre fichier Figma
50
- - Copier l'ID depuis l'URL : `https://www.figma.com/file/FILE_ID/nom-du-fichier`
51
 
52
- ### 3. **Configurer Claude/Cursor :**
53
  ```json
54
  {
55
  "mcpServers": {
56
- "figma": {
57
  "command": "sse",
58
  "args": ["https://aktraiser-sigma.hf.space/gradio_api/mcp/sse"]
59
  }
@@ -62,7 +63,7 @@ def setup_demo():
62
  ```
63
  """)
64
 
65
- # Interface de test (optionnelle)
66
  with gr.Tab("🧪 Test"):
67
  with gr.Row():
68
  token_input = gr.Textbox(
@@ -74,23 +75,23 @@ def setup_demo():
74
 
75
  with gr.Row():
76
  file_input = gr.Textbox(
77
- placeholder="ID du fichier",
78
- label="ID du fichier Figma"
79
  )
80
- file_btn = gr.Button("Configurer Fichier")
81
 
82
  status_output = gr.Textbox(label="Status", lines=3)
83
 
84
- # Actions de test
85
  with gr.Row():
86
  test_info_btn = gr.Button("📄 Info Fichier")
87
- test_comments_btn = gr.Button("📝 Commentaires")
88
- test_user_btn = gr.Button("👤 Info Utilisateur")
89
 
90
- # Nouveaux boutons pour les infos utilisateur détaillées
91
  with gr.Row():
92
- test_user_detailed_btn = gr.Button("👤 Profil Détaillé")
93
- test_teams_btn = gr.Button("🏢 Mes Équipes")
94
  test_permissions_btn = gr.Button("🔐 Permissions")
95
 
96
  with gr.Row():
@@ -99,7 +100,7 @@ def setup_demo():
99
  with gr.Row():
100
  test_limitations_btn = gr.Button("📚 Limitations API")
101
 
102
- # Connexions des événements
103
  token_btn.click(
104
  configure_figma_token,
105
  inputs=[token_input],
@@ -154,82 +155,82 @@ def setup_demo():
154
 
155
  gr.Markdown("""
156
  ---
157
- ### 🛠️ **Outils MCP disponibles (détection automatique) :**
158
 
159
  **📋 Configuration :**
160
  - `configure_figma_token(token)` - Configure le token d'accès
161
  - `configure_figma_file_id(file_id)` - Configure l'ID du fichier
162
 
163
  **📁 Navigation :**
164
- - `get_figma_file_info()` - Récupère les infos du fichier
165
- - `get_figma_comments()` - Récupère les commentaires
166
- - `get_figma_user_info()` - Info utilisateur connecté
167
-
168
- **👤 Compte utilisateur et équipe :**
169
- - `get_figma_user_detailed_info()` - Informations détaillées de l'utilisateur (profil complet)
170
- - `list_figma_user_teams()` - Liste toutes les équipes de l'utilisateur avec rôles et plans
171
- - `get_figma_team_info(team_id)` - Infos détaillées d'une équipe (plan, limites, stockage)
172
- - `get_figma_current_user_permissions()` - Permissions dans le fichier actuel (via Plugin API)
173
- - `get_figma_workspace_usage_stats()` - Statistiques d'utilisation de l'espace de travail
174
- - `list_figma_team_projects(team_id)` - Projets d'une équipe
175
  - `get_figma_api_limitations_info()` - Explique les limitations API Plugin vs REST
176
 
177
- **🎨 Création d'éléments de base (Figma Design) :**
178
  - `create_figma_rectangle(x, y, width, height, name, color)` - Crée un rectangle
179
  - `create_figma_frame(x, y, width, height, name)` - Crée un frame
180
- - `create_figma_text(x, y, text, name, font_size)` - Crée un texte
181
 
182
- **🟡 FigJam - Éléments de base :**
183
  - `create_figjam_sticky_note(x, y, text, width, height)` - Post-it (défaut: 240×240px)
184
- - `create_figjam_connector_between_elements(element1_name, element2_name, style)` - Connecteur entre éléments
185
- - `create_figjam_shape_with_text(x, y, shape_type, text, width, height)` - Forme avec texte (défaut: 208×208px)
186
  - `create_figjam_table(rows, columns, x, y)` - Tableau interactif
187
- - `create_figjam_code_block(x, y, code, language)` - Bloc de code avec coloration syntaxique
188
 
189
- **📐 FigJam - Zones et organisation :**
190
  - `create_figjam_background_shape(x, y, width, height, color, title, corner_radius)` - Zone de fond rectangulaire
191
  - `create_figjam_organized_zone(title, x, y, width, height, max_stickies)` - Zone avec grille de post-its
192
  - `create_figjam_workshop_template(template_type, x, y)` - Templates d'atelier complets
193
 
194
- **🎭 FigJam - Stickers et réactions :**
195
- - `create_figjam_sticker(x, y, sticker_type, size)` - Stickers/emoji pour réactions
196
 
197
- **🎯 Types disponibles :**
198
  - **Formes:** rectangle, circle, triangle, diamond, star, hexagon
199
  - **Stickers:** thumbs_up, thumbs_down, heart, star, fire, rocket, bulb, warning, check, cross, question, idea, clock, money, target, celebrate, thinking, confused
200
  - **Templates:** retrospective, brainstorm, user_journey
201
 
202
- **💡 Workflow recommandé :**
203
- 1. Créer une zone de fond avec `create_figjam_background_shape()`
204
- 2. Ajouter des post-its avec `create_figjam_sticky_note()`
205
- 3. Connecter les éléments avec `create_figjam_connector_between_elements()`
206
- 4. Ajouter des stickers pour les réactions avec `create_figjam_sticker()`
207
 
208
- **✨ Toutes les fonctions génèrent du code JavaScript prêt à utiliser dans un plugin Figma !**
209
 
210
  ---
211
 
212
  ## 📚 **Documentation Gradio MCP**
213
  Selon la [documentation officielle](https://www.gradio.app/guides/building-mcp-server-with-gradio) :
214
- - Gradio détecte **automatiquement** toutes les fonctions avec docstrings et type hints
215
- - Il suffit de `mcp_server=True` dans `.launch()`
216
- - Pas besoin d'exposition manuelle des outils
217
  """)
218
 
219
  return demo
220
 
221
- # === LANCEMENT DE L'APPLICATION ===
222
 
223
  if __name__ == "__main__":
224
  try:
225
  demo = setup_demo()
226
 
227
- logger.info("🚀 Démarrage du serveur MCP Figma...")
228
 
229
- # Configuration pour Hugging Face Spaces avec MCP
230
- # Gradio détectera automatiquement toutes les fonctions importées
231
  demo.launch(
232
- mcp_server=True, # 🔑 Active le serveur MCP avec détection automatique !
233
  server_name="0.0.0.0",
234
  server_port=7860,
235
  share=False,
@@ -237,5 +238,5 @@ if __name__ == "__main__":
237
  )
238
 
239
  except Exception as e:
240
- logger.error(f"❌ Erreur lors du lancement: {e}")
241
- raise
 
1
+
2
  #!/usr/bin/env python3
3
  """
4
+ 🎨 Figma MCP Server - Hosted on Hugging Face Spaces
5
+ MCP Server to control Figma via Claude/Cursor with real REST API
6
  """
7
  import gradio as gr
8
  import asyncio
 
10
  import logging
11
  from PIL import Image
12
  import base64
13
+ I import
14
 
15
  # Configuration du logging
16
  logging.basicConfig(level=logging.INFO)
17
  logger = logging.getLogger(__name__)
18
 
19
+ # Import all MCP tools from the tools folder
20
+ # Gradio will automatically detect all functions with docstrings/type hints
21
  try:
22
  from tools import *
23
+ logger.info( "✅ All MCP tools successfully imported" )
24
  except Exception as e:
25
+ logger.error( f"❌ Error importing MCP tools: {e} " )
26
  raise
27
 
28
+ # === GRADIO APPLICATION CONFIGURATION ===
29
 
30
  def setup_demo():
31
+ "Configure the Gradio interface for the MCP server"
32
 
33
  with gr.Blocks(
34
  title="🎨 Figma MCP Server",
 
37
 
38
  gr.Markdown("""
39
  # 🎨 Figma MCP Server
40
+ **MCP Server to control Figma via Claude/Cursor with REST API**
41
 
42
  ## 📋 **Instructions de configuration :**
43
 
44
+ ### 1. **Get a Figma token:**
45
  - Aller sur [Figma Settings > Personal Access Tokens](https://www.figma.com/settings)
46
+ - Create a new token
47
+ - Copy the token (starts with `figd_` or `figc_`)
48
 
49
+ ### 2. **Getting the ID of a file:**
50
+ - Open your Figma file
51
+ - Copy the ID from the URL: `https://www.figma.com/file/FILE_ID/file-name`
52
 
53
+ ### 3. **Configure Claude/Cursor:**
54
  ```json
55
  {
56
  "mcpServers": {
57
+ "figure": {
58
  "command": "sse",
59
  "args": ["https://aktraiser-sigma.hf.space/gradio_api/mcp/sse"]
60
  }
 
63
  ```
64
  """)
65
 
66
+ # Test interface (optional)
67
  with gr.Tab("🧪 Test"):
68
  with gr.Row():
69
  token_input = gr.Textbox(
 
75
 
76
  with gr.Row():
77
  file_input = gr.Textbox(
78
+ placeholder= "file ID" ,
79
+ label= "Figma file ID"
80
  )
81
+ file_btn = gr.Button( "Configure File" )
82
 
83
  status_output = gr.Textbox(label="Status", lines=3)
84
 
85
+ # Test actions
86
  with gr.Row():
87
  test_info_btn = gr.Button("📄 Info Fichier")
88
+ test_comments_btn = gr.Button( "📝 Comments" )
89
+ test_user_btn = gr.Button( "👤 User Info" )
90
 
91
+ # New buttons for detailed user info
92
  with gr.Row():
93
+ test_user_detailed_btn = gr.Button( "👤 Detailed Profile" )
94
+ test_teams_btn = gr.Button( "🏢 My Teams" )
95
  test_permissions_btn = gr.Button("🔐 Permissions")
96
 
97
  with gr.Row():
 
100
  with gr.Row():
101
  test_limitations_btn = gr.Button("📚 Limitations API")
102
 
103
+ # Event Connections
104
  token_btn.click(
105
  configure_figma_token,
106
  inputs=[token_input],
 
155
 
156
  gr.Markdown("""
157
  ---
158
+ ### 🛠️ **Available MCP tools (auto-detection):**
159
 
160
  **📋 Configuration :**
161
  - `configure_figma_token(token)` - Configure le token d'accès
162
  - `configure_figma_file_id(file_id)` - Configure l'ID du fichier
163
 
164
  **📁 Navigation :**
165
+ - `get_figma_file_info()` - Gets file info
166
+ - `get_figma_comments()` - Retrieves comments
167
+ - `get_figma_user_info()` - Logged in user info
168
+
169
+ **👤 User account and team:**
170
+ - `get_figma_user_detailed_info()` - Detailed user information (full profile)
171
+ - `list_figma_user_teams()` - Lists all user's teams with roles and plans
172
+ - `get_figma_team_info(team_id)` - Detailed team info (plan, limits, storage)
173
+ - `get_figma_current_user_permissions()` - Permissions in the current file (via Plugin API)
174
+ - `get_figma_workspace_usage_stats()` - Workspace usage statistics
175
+ - `list_figma_team_projects(team_id)` - Projects of a team
176
  - `get_figma_api_limitations_info()` - Explique les limitations API Plugin vs REST
177
 
178
+ **🎨 Creation of basic elements (Figma Design):**
179
  - `create_figma_rectangle(x, y, width, height, name, color)` - Crée un rectangle
180
  - `create_figma_frame(x, y, width, height, name)` - Crée un frame
181
+ - `create_figma_text(x, y, text, name, font_size)` - Creates a text
182
 
183
+ **🟡 FigJam - Basic Elements:**
184
  - `create_figjam_sticky_note(x, y, text, width, height)` - Post-it (défaut: 240×240px)
185
+ - `create_figjam_connector_between_elements(element1_name, element2_name, style)` - Connector between elements
186
+ - `create_figjam_shape_with_text(x, y, shape_type, text, width, height)` - Shape with text (default: 208×208px)
187
  - `create_figjam_table(rows, columns, x, y)` - Tableau interactif
188
+ - `create_figjam_code_block(x, y, code, language)` - Code block with syntax highlighting
189
 
190
+ **📐 FigJam - Zones and organization:**
191
  - `create_figjam_background_shape(x, y, width, height, color, title, corner_radius)` - Zone de fond rectangulaire
192
  - `create_figjam_organized_zone(title, x, y, width, height, max_stickies)` - Zone avec grille de post-its
193
  - `create_figjam_workshop_template(template_type, x, y)` - Templates d'atelier complets
194
 
195
+ **🎭 FigJam - Stickers and reactions:**
196
+ - `create_figjam_sticker(x, y, sticker_type, size)` - Stickers/emoji for reactions
197
 
198
+ **🎯 Available types:**
199
  - **Formes:** rectangle, circle, triangle, diamond, star, hexagon
200
  - **Stickers:** thumbs_up, thumbs_down, heart, star, fire, rocket, bulb, warning, check, cross, question, idea, clock, money, target, celebrate, thinking, confused
201
  - **Templates:** retrospective, brainstorm, user_journey
202
 
203
+ **💡 Recommended workflow:**
204
+ 1. Create a background area with `create_figjam_background_shape()`
205
+ 2. Add sticky notes with `create_figjam_sticky_note()`
206
+ 3. Connect the elements with `create_figjam_connector_between_elements()`
207
+ 4. Add stickers for reactions with `create_figjam_sticker()`
208
 
209
+ **✨ All functions generate JavaScript code ready to use in a Figma plugin!**
210
 
211
  ---
212
 
213
  ## 📚 **Documentation Gradio MCP**
214
  Selon la [documentation officielle](https://www.gradio.app/guides/building-mcp-server-with-gradio) :
215
+ - Gradio **automatically** detects all functions with docstrings and type hints
216
+ - Just set `mcp_server=True` in `.launch()`
217
+ - No need for manual exposure of tools
218
  """)
219
 
220
  return demo
221
 
222
+ # === LAUNCHING THE APPLICATION ===
223
 
224
  if __name__ == "__main__":
225
  try:
226
  demo = setup_demo()
227
 
228
+ logger.info( "🚀 Starting MCP Figma server..." )
229
 
230
+ # Configuration for Hugging Face Spaces with MCP
231
+ # Gradio will automatically detect all imported functions
232
  demo.launch(
233
+ mcp_server= True , # 🔑 Enables MCP server with auto-detection!
234
  server_name="0.0.0.0",
235
  server_port=7860,
236
  share=False,
 
238
  )
239
 
240
  except Exception as e:
241
+ logger.error( f"❌ Error launching: {e} " )
242
+ raise