API Key Configuration Feature
Overview
Users can now configure their API keys directly through the TraceMind MCP Server UI. These user-provided keys will override environment variables for the current session.
What's New
1. Settings Tab (βοΈ)
A new Settings tab has been added as the first tab in the UI where users can:
- Enter their Google Gemini API Key
- Enter their HuggingFace Token
- Save keys for the current session
- Clear session keys and revert to environment variables
2. Session-Only Storage
- API keys are stored in Gradio's session state
- Keys are NOT persisted to disk or cookies
- Keys are automatically cleared when the browser session ends
- Each user session has its own isolated key storage
3. Automatic Key Validation
- Gemini API keys are validated when saved by creating a test client
- Invalid keys are rejected with clear error messages
- Users receive immediate feedback on key validity
How to Use
Option 1: Configure via UI (Recommended)
Navigate to Settings Tab
- Open the TraceMind MCP Server app
- Click on the "βοΈ Settings" tab (first tab)
Enter Your Keys
- Gemini API Key: Get from https://aistudio.google.com/app/apikey
- HuggingFace Token: Get from https://huggingface.co/settings/tokens
Save Keys
- Click "πΎ Save API Keys for This Session"
- Wait for validation confirmation
- Keys are now active for all tools
Use Any Tool
- Navigate to any other tab (Analyze Leaderboard, Debug Trace, etc.)
- Tools will automatically use your configured keys
- No additional configuration needed
Option 2: Environment Variables (Still Supported)
You can still use environment variables as before:
export GEMINI_API_KEY="your-key-here"
export HF_TOKEN="your-token-here"
Note: UI-configured keys always override environment variables.
Technical Details
Architecture Changes
1. UI Layer (app.py)
- Added Settings tab with key input forms
- Implemented session state management with
gr.State() - Updated all tool functions to accept API keys as parameters
- Added key validation and error handling
2. Tool Layer (mcp_tools.py)
- Updated all functions to accept optional
hf_tokenparameter - Modified
load_dataset()calls to use user-provided tokens - Added fallback to environment variables when no token provided
- Functions updated:
analyze_leaderboard()debug_trace()compare_runs()get_dataset()get_leaderboard_data()(MCP Resource)get_trace_data()(MCP Resource)
3. Client Layer (gemini_client.py)
GeminiClient.__init__()already supported optionalapi_keyparameter- No changes needed - already designed for key override
Key Features
Priority Order:
User-provided key (UI) > Environment variable > ErrorValidation:
- Gemini keys: Validated by creating test
GeminiClient - HF tokens: Accepted without validation (validated on first use)
- Gemini keys: Validated by creating test
Error Handling:
- Clear error messages when keys are missing
- Helpful prompts to configure keys in Settings tab
- Validation errors shown immediately
Session Management:
- Keys stored in
gr.State()(Gradio session state) - Isolated per-user in multi-user environments
- Automatically cleared on session end
- Keys stored in
Security Considerations
β Secure Practices
- No Persistence: Keys are never written to disk
- Session Isolation: Each user has isolated key storage
- Password Fields: Keys displayed as
type="password"(hidden) - No Logging: Keys not logged or exposed in error messages
β οΈ Security Notes
- HTTPS Required: Always use HTTPS in production to protect keys in transit
- Public Spaces: Be cautious using on public HuggingFace Spaces
- Shared Environments: Each browser session is isolated, but server has access
- Recommendation: Use environment variables for production deployments
Examples
Example 1: First-Time User
1. User opens app (no env vars set)
2. User sees "β οΈ Status: No API key configured" in Settings
3. User enters Gemini API key and HF token
4. User clicks "Save API Keys"
5. User sees "β
Gemini API key validated and saved"
6. User switches to "Analyze Leaderboard" tab
7. Tool works using user-provided keys
Example 2: Overriding Environment Variables
1. User has GEMINI_API_KEY set in environment
2. User wants to test with a different key
3. User enters new key in Settings tab
4. User clicks "Save API Keys"
5. All tools now use the new key (not the env var)
6. User clicks "Clear Session Keys" to revert
7. Tools now use environment variable again
Example 3: Error Handling
1. User enters invalid Gemini API key
2. User clicks "Save API Keys"
3. User sees "β Gemini API key invalid: [error message]"
4. User corrects the key and tries again
5. User sees "β
Gemini API key validated and saved"
API Changes
Function Signatures
All tool functions now accept optional API key parameters:
# Before
async def analyze_leaderboard(
gemini_client: GeminiClient,
leaderboard_repo: str = "...",
...
) -> str:
# After
async def analyze_leaderboard(
gemini_client: GeminiClient,
leaderboard_repo: str = "...",
...,
hf_token: Optional[str] = None # NEW
) -> str:
Backward Compatibility
- β All existing code continues to work
- β Environment variables still supported
- β No breaking changes to MCP protocol
- β Optional parameters have sensible defaults
Testing Checklist
- UI renders Settings tab correctly
- Gemini API key input works (password field)
- HF token input works (password field)
- Save button validates and stores keys
- Clear button reverts to environment variables
- All tools use user-provided Gemini key
- All tools use user-provided HF token
- Invalid Gemini key shows error
- Missing keys show helpful error messages
- Session isolation works in multi-user scenario
- Keys cleared on browser close
Future Enhancements
Key Persistence (Optional):
- Add opt-in browser localStorage support
- Warning about security implications
Multiple Key Profiles:
- Save multiple key configurations
- Quick switch between profiles
Usage Tracking:
- Show API usage per session
- Cost estimation based on usage
Token Expiration:
- Detect expired HF tokens
- Prompt for refresh
Troubleshooting
Keys Not Working
Problem: Tools show "No API key configured" error
Solutions:
- Check you clicked "Save API Keys" button
- Look for validation success message
- Try refreshing the page and re-entering keys
- Check browser console for errors
Validation Fails
Problem: "β Gemini API key invalid" error
Solutions:
- Verify key copied correctly (no extra spaces)
- Check key is active at https://aistudio.google.com/app/apikey
- Ensure you have API quota remaining
- Try generating a new key
Dataset Access Denied
Problem: "Error loading dataset: Access denied"
Solutions:
- Verify HF token is correct
- Check token has read permissions
- Ensure dataset is public or you have access
- Try using a new token
Support
For issues or questions:
- Check the Settings tab for status messages
- Review error messages in tool outputs
- Open an issue on GitHub with:
- Steps to reproduce
- Error messages (DO NOT include actual API keys)
- Browser and OS information