kshitijthakkar commited on
Commit
86f2cd8
Β·
1 Parent(s): 4b91aa4

feat: Add Settings screen for API key configuration with security

Browse files

- Add Settings tab to Gradio UI for judges to configure their own API keys
- Prevents credit issues during hackathon evaluation
- Uses api_name=False to prevent key exposure via Gradio API
- Supports session-only override of HF Spaces Secrets
- Update README with comprehensive judge instructions
- Clarify HF token permissions: Read for datasets, Write for push_dataset_to_hub
- Show current key status (masked) in Settings UI
- Add reset to defaults functionality

Files changed (2) hide show
  1. README.md +61 -0
  2. app.py +156 -0
README.md CHANGED
@@ -409,6 +409,67 @@ Top N Models: 5
409
 
410
  Click "πŸ” Analyze" and get AI-powered insights from live data!
411
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
412
  ## MCP Integration
413
 
414
  ### How It Works
 
409
 
410
  Click "πŸ” Analyze" and get AI-powered insights from live data!
411
 
412
+ ## 🎯 For Hackathon Judges & Visitors
413
+
414
+ ### Using Your Own API Keys (Recommended)
415
+
416
+ This MCP server has pre-configured API keys in HuggingFace Spaces Secrets for quick testing. However, **to prevent credit issues during evaluation**, we strongly recommend using your own API keys:
417
+
418
+ #### Option 1: Configure in MCP Server UI (Simplest)
419
+
420
+ 1. **Open the MCP Server Space**: https://huggingface.co/spaces/MCP-1st-Birthday/TraceMind-mcp-server
421
+ 2. Navigate to the **βš™οΈ Settings** tab
422
+ 3. Enter your own **Gemini API Key** and **HuggingFace Token**
423
+ 4. Click **"Save & Override Keys"**
424
+ 5. βœ… Your keys will be used for all MCP tool calls in this session
425
+
426
+ **Then you can**:
427
+ - Use any tool in the tabs above
428
+ - Connect from TraceMind-AI (it will automatically use your keys configured here)
429
+ - Test with Claude Desktop (will use your keys)
430
+
431
+ #### Option 2: For TraceMind-AI Integration
432
+
433
+ If you're testing the complete TraceMind platform (Track 2 - MCP in Action):
434
+
435
+ 1. **Configure MCP Server** (as described above)
436
+ 2. **Open TraceMind-AI**: https://huggingface.co/spaces/MCP-1st-Birthday/TraceMind
437
+ 3. Navigate to **βš™οΈ Settings** in TraceMind-AI
438
+ 4. Enter your API keys there as well
439
+ 5. βœ… Both apps will use your keys
440
+
441
+ ### Why Two Settings Screens?
442
+
443
+ - **TraceMind-AI** (Track 2) is the user-facing UI - calls MCP server for intelligent analysis
444
+ - **TraceMind MCP Server** (Track 1) is the backend service - provides MCP tools
445
+ - They run in **separate browser sessions** β†’ need separate configuration
446
+ - Configuring both ensures your keys are used throughout the evaluation flow
447
+
448
+ ### Getting Free API Keys
449
+
450
+ Both APIs have generous free tiers perfect for hackathon evaluation:
451
+
452
+ **Google Gemini API Key**:
453
+ - Go to https://ai.google.dev/
454
+ - Click "Get API Key" β†’ Create project β†’ Generate key
455
+ - **Free tier**: 1,500 requests/day
456
+
457
+ **HuggingFace Token**:
458
+ - Go to https://huggingface.co/settings/tokens
459
+ - Click "New token" β†’ Name it (e.g., "TraceMind Access")
460
+ - **Permissions**:
461
+ - Select "Read" for viewing datasets (sufficient for most tools)
462
+ - Select "Write" if you want to use `push_dataset_to_hub` tool to upload synthetic datasets
463
+ - **Recommended**: Use "Write" permissions for full functionality
464
+ - No rate limits for public dataset access
465
+
466
+ ### Default Configuration (If You Don't Configure)
467
+
468
+ If you don't configure your own keys, the MCP server will use our pre-configured keys from HuggingFace Spaces Secrets. This is fine for quick testing, but please note:
469
+ - Uses our API credits
470
+ - May hit rate limits during high traffic
471
+ - Recommended only for brief testing
472
+
473
  ## MCP Integration
474
 
475
  ### How It Works
app.py CHANGED
@@ -1293,6 +1293,162 @@ def create_gradio_ui():
1293
  **Tag**: `building-mcp-track-enterprise`
1294
  """)
1295
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1296
  return demo
1297
 
1298
  if __name__ == "__main__":
 
1293
  **Tag**: `building-mcp-track-enterprise`
1294
  """)
1295
 
1296
+ with gr.Tab("βš™οΈ Settings"):
1297
+ gr.Markdown("""
1298
+ # βš™οΈ API Key Configuration (Optional)
1299
+
1300
+ ## Default Configuration
1301
+
1302
+ This MCP server uses **pre-configured API keys from HuggingFace Spaces Secrets**.
1303
+
1304
+ For most users (especially MCP client demos with Claude Desktop), no configuration is needed!
1305
+
1306
+ ## For Hackathon Judges & Visitors
1307
+
1308
+ If you want to use **your own API keys** to prevent credit issues during evaluation:
1309
+
1310
+ 1. Enter your API keys below
1311
+ 2. Click **"Save & Override Keys"**
1312
+ 3. Your keys will be used for **this session only** (stored in browser memory, never saved to disk)
1313
+
1314
+ Then you can:
1315
+ - Use any tool in the tabs above
1316
+ - Connect from TraceMind-AI (the MCP tools will use your keys)
1317
+ - Test with Claude Desktop (will use your keys)
1318
+
1319
+ ## Security Notes
1320
+
1321
+ βœ… **Session-only storage**: Keys stored only in your browser session
1322
+ βœ… **No server persistence**: Keys never saved to disk or database
1323
+ βœ… **API endpoint security**: This form is NOT exposed via Gradio's "Use via API"
1324
+ βœ… **HTTPS encryption**: All API calls made over secure connections
1325
+
1326
+ ---
1327
+ """)
1328
+
1329
+ # Show current key status (masked)
1330
+ current_gemini = os.environ.get("GEMINI_API_KEY", "")
1331
+ current_hf = os.environ.get("HF_TOKEN", "")
1332
+
1333
+ gemini_display = f"`{current_gemini[:10]}...`" if current_gemini else "❌ Not configured"
1334
+ hf_display = f"`{current_hf[:7]}...`" if current_hf else "❌ Not configured"
1335
+
1336
+ gr.Markdown(f"""
1337
+ ### Current Configuration Status
1338
+
1339
+ - **Gemini API Key**: {gemini_display}
1340
+ - **HuggingFace Token**: {hf_display}
1341
+
1342
+ {"βœ… Using HuggingFace Spaces Secrets (default)" if current_gemini and current_hf else "⚠️ API keys not fully configured"}
1343
+ """)
1344
+
1345
+ gr.Markdown("### Override with Your Own Keys")
1346
+
1347
+ with gr.Row():
1348
+ with gr.Column():
1349
+ gemini_api_key_input = gr.Textbox(
1350
+ label="Google Gemini API Key",
1351
+ placeholder="Leave empty to use default, or enter AIza...",
1352
+ type="password",
1353
+ value="",
1354
+ info="Get your free API key at: https://ai.google.dev/"
1355
+ )
1356
+
1357
+ with gr.Row():
1358
+ with gr.Column():
1359
+ hf_token_input = gr.Textbox(
1360
+ label="HuggingFace Token",
1361
+ placeholder="Leave empty to use default, or enter hf_...",
1362
+ type="password",
1363
+ value="",
1364
+ info="Get your token at: https://huggingface.co/settings/tokens"
1365
+ )
1366
+
1367
+ with gr.Row():
1368
+ save_keys_btn = gr.Button("πŸ’Ύ Save & Override Keys", variant="primary", size="lg")
1369
+ reset_keys_btn = gr.Button("πŸ”„ Reset to Defaults", variant="secondary", size="lg")
1370
+
1371
+ settings_status = gr.Markdown("")
1372
+
1373
+ gr.Markdown("""
1374
+ ---
1375
+
1376
+ ### How to Get API Keys
1377
+
1378
+ #### Google Gemini API Key
1379
+
1380
+ 1. Go to [Google AI Studio](https://ai.google.dev/)
1381
+ 2. Click "Get API Key" in the top right
1382
+ 3. Create a new project or select an existing one
1383
+ 4. Generate an API key
1384
+ 5. Copy the key (starts with `AIza...`)
1385
+
1386
+ **Free Tier**: 1,500 requests per day, suitable for testing and demos
1387
+
1388
+ #### HuggingFace Token
1389
+
1390
+ 1. Go to [HuggingFace Settings](https://huggingface.co/settings/tokens)
1391
+ 2. Click "New token"
1392
+ 3. Give it a name (e.g., "TraceMind Access")
1393
+ 4. Select permissions:
1394
+ - **Read**: Sufficient for viewing datasets (leaderboard, traces, results)
1395
+ - **Write**: Required for `push_dataset_to_hub` tool (uploading synthetic datasets)
1396
+ 5. Create and copy the token (starts with `hf_...`)
1397
+
1398
+ **Recommended**: Use "Write" permissions for full MCP server functionality
1399
+ """)
1400
+
1401
+ # Event handlers for Settings tab
1402
+ def save_override_keys(gemini, hf):
1403
+ """Save user-provided API keys to session (override Spaces Secrets)"""
1404
+ messages = []
1405
+
1406
+ if gemini and gemini.strip():
1407
+ if gemini.startswith("AIza"):
1408
+ os.environ["GEMINI_API_KEY"] = gemini.strip()
1409
+ messages.append("βœ… **Gemini API key** saved and will be used for this session")
1410
+ logger.info("Gemini API key overridden by user for this session")
1411
+ else:
1412
+ messages.append("⚠️ **Invalid Gemini API key format** (should start with 'AIza')")
1413
+
1414
+ if hf and hf.strip():
1415
+ if hf.startswith("hf_"):
1416
+ os.environ["HF_TOKEN"] = hf.strip()
1417
+ messages.append("βœ… **HuggingFace token** saved and will be used for this session")
1418
+ logger.info("HuggingFace token overridden by user for this session")
1419
+ else:
1420
+ messages.append("⚠️ **Invalid HuggingFace token format** (should start with 'hf_')")
1421
+
1422
+ if not messages:
1423
+ messages.append("⚠️ No keys provided. Still using default keys from Spaces Secrets.")
1424
+
1425
+ messages.append("\n**Note**: Your keys are active for this browser session only.")
1426
+ messages.append("\n🎯 You can now use all MCP tools with your own API keys!")
1427
+
1428
+ return "\n\n".join(messages)
1429
+
1430
+ def reset_to_defaults():
1431
+ """Reset to Spaces Secrets (requires page refresh)"""
1432
+ return """
1433
+ ℹ️ To reset to default keys from Spaces Secrets, please **refresh this page**.
1434
+
1435
+ Your session overrides will be cleared and the default keys will be used again.
1436
+ """
1437
+
1438
+ # Wire up buttons with api_name=False for security
1439
+ save_keys_btn.click(
1440
+ fn=save_override_keys,
1441
+ inputs=[gemini_api_key_input, hf_token_input],
1442
+ outputs=[settings_status],
1443
+ api_name=False # βœ… CRITICAL: Prevents API key exposure via Gradio API
1444
+ )
1445
+
1446
+ reset_keys_btn.click(
1447
+ fn=reset_to_defaults,
1448
+ outputs=[settings_status],
1449
+ api_name=False # βœ… CRITICAL: Prevents exposure
1450
+ )
1451
+
1452
  return demo
1453
 
1454
  if __name__ == "__main__":