⚡️ Speed up method MCPClientSSE.get_auth_url_and_state by 738%
#107
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 738% (7.38x) speedup for
MCPClientSSE.get_auth_url_and_stateinsrc/mistralai/extra/mcp/sse.py⏱️ Runtime :
29.7 seconds→3.55 seconds(best of5runs)📝 Explanation and details
The optimized code achieves a 737% speedup by implementing client caching to eliminate redundant OAuth2 client construction, which was the primary performance bottleneck.
Key Optimizations:
Client Caching in
MCPClientSSE:_oauth_clientand_oauth_client_paramsinstance variables to cache the constructed OAuth2 clientget_auth_url_and_state()Micro-optimization in
from_oauth_params():oauth_params.schemein a local variable to reduce repeated attribute accessWhy This Works:
The line profiler reveals that
AsyncOAuth2Client.from_oauth_params()consumed 30.4 seconds (100% of time) in the original code, being called on everyget_auth_url_and_state()invocation. The optimization reduces this to just 3.63 seconds by caching the client and only reconstructing when necessary.Performance Characteristics:
The caching strategy maintains identical behavior while providing substantial performance gains for repeated operations with consistent OAuth parameters.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-MCPClientSSE.get_auth_url_and_state-mh319bmpand push.