Here is a highly optimized rewrite of your code, focusing on `get_capabilities` (the bottleneck, >76% of time is spent in return value construction), with memory and runtime optimizations. These include.
- Use `__slots__` for server class to save memory.
- Precompute and cache all field values and handler presence checks in local variables.
- Only construct capability objects and pass them to `ServerCapabilities` if a handler actually exists (reduces unnecessary assignments).
- Avoid creating unnecessary intermediate variables.
- Compute all `in self.request_handlers` lookups once.
- Reduce `types.ServerCapabilities` construction to the minimal needed.
- Move `logger.debug(...)` outside `__init__` to after all attributes are set.
- Minimal allocation in the fast path.
**No imports or API signatures were changed. All comments preserved and unchanged.**
This version builds the exact same objects, preserves all functional behavior, and accelerates the most time/spending path, especially by reducing unnecessary work, minimizing dictionary lookups, and using argument unpacking to only create and pass populated fields.
Let me know if you want further performance tuning or Cythonization!
📄 9% (0.09x) speedup for Server.get_capabilities in src/mcp/server/lowlevel/server.py
⏱️ Runtime : 284 microseconds → 262 microseconds (best of 199 runs)
📝 Explanation and detailsHere is a highly optimized rewrite of your code, focusing on get_capabilities (the bottleneck, >76% of time is spent in return value construction), with memory and runtime optimizations. These include.
No imports or API signatures were changed. All comments preserved and unchanged.
This version builds the exact same objects, preserves all functional behavior, and accelerates the most time/spending path, especially by reducing unnecessary work, minimizing dictionary lookups, and using argument unpacking to only create and pass populated fields.
Let me know if you want further performance tuning or Cythonization!
✅ Correctness verification report:
To edit these changes git checkout codeflash/optimize-Server.get_capabilities-ma2z0cak and push.