Skip to content

Conversation

@codeflash-ai
Copy link

@codeflash-ai codeflash-ai bot commented Apr 29, 2025

📄 15% (0.15x) speedup for FastMCP.resource in src/mcp/server/fastmcp/server.py

⏱️ Runtime : 434 microseconds 379 microseconds (best of 532 runs)

📝 Explanation and details

Here is the optimized version of your program.
Most time in profiling is spent on the initial resource() call and returning the decorator, not on expensive string ops.
However, we can still speed up the following.

  • Check callables faster and earlier.
  • Compile the URI param-regex once, outside the decorator, as a module constant.
  • Cache and re-use inspect.signature and regex parsing where possible: small local helpers and local vars.
  • Avoid creating unnecessary sets/variables if not needed.
  • Use (mime_type or "text/plain") only once.
  • Flatten logic to avoid repeated checks.

Below, only relevant lines are changed and all comments are preserved per your instructions.

Optimization techniques used.

  • Precompiled the URI regex.
  • Avoid recomputing inspect.signature and regex parse results.
  • Use single-or evaluation for mime_type default.
  • Flattened branching for quicker exit.
  • Saves memory and some CPU if this method is called often.

Further speedup would require changing code structure or API, which was not requested.
The function output and comments are unchanged except for efficiency.

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 🔘 None Found
🌀 Generated Regression Tests 1013 Passed
⏪ Replay Tests 🔘 None Found
🔎 Concolic Coverage Tests 2 Passed
📊 Tests Coverage 100.0%
🌀 Generated Regression Tests Details
import inspect
import logging
import re
from collections.abc import AsyncIterator, Callable
from contextlib import AbstractAsyncContextManager, asynccontextmanager
from typing import Any, Literal, TypeVar
from unittest.mock import MagicMock

# imports
import pytest  # used for our unit tests
from pydantic import AnyUrl
from src.mcp.server.fastmcp.server import FastMCP


# Mock classes to simulate the environment
class FunctionResource:
    def __init__(self, uri, name, description, mime_type, fn):
        self.uri = uri
        self.name = name
        self.description = description
        self.mime_type = mime_type
        self.fn = fn

class ResourceManager:
    def __init__(self, warn_on_duplicate_resources=False):
        self.resources = {}
        self.warn_on_duplicate_resources = warn_on_duplicate_resources

    def add_template(self, fn, uri_template, name, description, mime_type):
        self.resources[uri_template] = fn
from src.mcp.server.fastmcp.server import FastMCP

# unit tests

@pytest.fixture
def server():
    return FastMCP()

def test_register_simple_uri(server):
    """Test registering a function with a simple static URI."""
    @server.resource("resource://simple")
    def simple_resource():
        return "Simple Resource"

def test_register_parameterized_uri(server):
    """Test registering a function with a parameterized URI."""
    @server.resource("resource://{param}")
    def param_resource(param):
        return f"Resource with {param}"


def test_decorator_misuse(server):
    """Test error when decorator is used without calling it."""
    with pytest.raises(TypeError):
        @server.resource
        def misuse_resource():
            return "Misused Resource"

def test_duplicate_resource_registration(server):
    """Test registering the same function with the same URI."""
    @server.resource("resource://duplicate")
    def duplicate_resource():
        return "Duplicate Resource"

    @server.resource("resource://duplicate")
    def duplicate_resource_again():
        return "Duplicate Resource Again"

def test_register_async_function(server):
    """Test registering an asynchronous function."""
    @server.resource("resource://async")
    async def async_resource():
        return "Async Resource"

def test_large_number_of_resources(server):
    """Test registering a large number of resources."""
    for i in range(1000):
        @server.resource(f"resource://large{i}")
        def large_resource():
            return f"Resource {i}"

def test_complex_return_type(server):
    """Test registering a function with a complex return type."""
    @server.resource("resource://complex")
    def complex_resource():
        return {"key": "value"}
# codeflash_output is used to check that the output of the original code is the same as that of the optimized code.

from src.mcp.server.fastmcp.server import FastMCP

def test_FastMCP_resource():
    FastMCP.resource(FastMCP(name=None, instructions=None), '', name=None, description=None, mime_type=None)

To edit these changes git checkout codeflash/optimize-FastMCP.resource-ma339978 and push.

Codeflash

Here is the optimized version of your program.  
**Most time in profiling is spent on the initial resource() call and returning the decorator, not on expensive string ops.**  
However, we can still speed up the following.

- **Check callables faster and earlier.**
- **Compile the URI param-regex once, outside the decorator, as a module constant.**
- **Cache and re-use inspect.signature and regex parsing where possible: small local helpers and local vars.**
- **Avoid creating unnecessary sets/variables if not needed.**
- **Use (mime_type or "text/plain") only once.**
- **Flatten logic to avoid repeated checks.**

Below, only relevant lines are changed and all comments are preserved per your instructions.



**Optimization techniques used**.
- Precompiled the URI regex.
- Avoid recomputing inspect.signature and regex parse results.
- Use single-or evaluation for `mime_type` default.
- Flattened branching for quicker exit.
- Saves memory and some CPU if this method is called often.

**Further speedup would require changing code structure or API, which was not requested.**  
The function output and comments are unchanged except for efficiency.
@codeflash-ai codeflash-ai bot added the ⚡️ codeflash Optimization PR opened by Codeflash AI label Apr 29, 2025
@codeflash-ai codeflash-ai bot requested a review from Saga4 April 29, 2025 22:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

⚡️ codeflash Optimization PR opened by Codeflash AI

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant