mcp-context-forge icon indicating copy to clipboard operation
mcp-context-forge copied to clipboard

[BUG]: UI - API Tokens - Last Used and Usage Stats not showing any data

Open IuliaGaitan opened this issue 10 months ago • 1 comments

🐞 Bug Summary

API Tokens Last Used and Usage Stats is not showing any data even though where used.


🧩 Affected Component

Select the area of the project impacted:

  • [ ] mcpgateway - API
  • [X] mcpgateway - UI (admin panel)
  • [ ] mcpgateway.wrapper - stdio wrapper
  • [ ] Federation or Transports
  • [ ] CLI, Makefiles, or shell scripts
  • [ ] Container setup (Docker/Podman/Compose)
  • [ ] Other (explain below)

🔁 Steps to Reproduce

  1. Go to http://localhost:8000/admin/#tokens
  2. Check Last Used
  3. Click Usage Stats

🤔 Results

Last Used is showing always Never. Usage Stats is not showing any data.

Image

🤔 Expected Behavior

Last Used should be updated each time the token is used. Usage Stats should show the correct data.


📓 Logs / Error Output

Paste any relevant stack traces or logs here. ⚠️ Do not paste secrets, credentials, or tokens.


🧠 Environment Info

You can retrieve most of this from the /version endpoint.

Key Value
Version or commit v0.128.0
Runtime Python 3.12.3
Platform / OS Linux 6.6.87.2-microsoft-standard-WSL2 (x86_64)
Container none

🧩 Additional Context (optional)

Related with #2390

IuliaGaitan avatar Jan 29 '26 15:01 IuliaGaitan

Thank you for the report.

Root cause identified:

  1. last_used not updating: API tokens created via /tokens are JWT tokens. When used, they pass JWT validation directly (auth.py:612) and the auth flow never reaches _lookup_api_token_sync() (auth.py:836) where last_used is updated. The database lookup was designed as a fallback for non-JWT tokens, but all API tokens are JWTs.

  2. Usage Stats empty: The log_token_usage() method that populates TokenUsageLog is defined but never called from production code.

Proposed Fix:

  1. Add helper function in auth.py after line 264:
def _update_api_token_last_used_sync(jti: str) -> None:
    """Update last_used timestamp for an API token."""
    with fresh_db_session() as db:
        from sqlalchemy import select
        from mcpgateway.db import EmailApiToken, utc_now
        
        result = db.execute(select(EmailApiToken).where(EmailApiToken.jti == jti))
        api_token = result.scalar_one_or_none()
        if api_token:
            api_token.last_used = utc_now()
  1. Call from _set_auth_method_from_payload() when API token is detected (~line 458):
if auth_provider == "api_token":
    request.state.auth_method = "api_token"
    jti = payload.get("jti")
    if jti:
        await asyncio.to_thread(_update_api_token_last_used_sync, jti)
    return
  1. Same for legacy API token branch (~line 472).

  2. For Usage Stats: Add middleware that calls log_token_usage() after request completion when request.state.auth_method == "api_token".

crivetimihai avatar Jan 30 '26 11:01 crivetimihai