Skip to content

Commit 1bfb06d

Browse files
committed
perf(server): avoid extra worker-thread hop when reading template resources
1 parent 77001c9 commit 1bfb06d

2 files changed

Lines changed: 40 additions & 1 deletion

File tree

‎src/mcp/server/mcpserver/resources/templates.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,9 @@ async def create_resource(
231231
if isinstance(result, InputRequiredResult):
232232
return result
233233

234+
async def _return_result() -> Any:
235+
return result
236+
234237
return FunctionResource(
235238
uri=uri, # type: ignore
236239
name=self.name,
@@ -240,7 +243,7 @@ async def create_resource(
240243
icons=self.icons,
241244
annotations=self.annotations,
242245
meta=self.meta,
243-
fn=lambda: result, # Capture result in closure
246+
fn=_return_result,
244247
)
245248
except (ResourceError, MCPError):
246249
raise

‎tests/server/mcpserver/resources/test_resource_template.py‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -520,3 +520,39 @@ def charts(year: str) -> list[_Chart]:
520520

521521
template = ResourceTemplate.from_function(charts, uri_template="charts://{year}")
522522
assert template.uri_template == "charts://{year}"
523+
524+
525+
@pytest.mark.anyio
526+
async def test_template_read_avoids_extra_worker_thread_hop(monkeypatch: pytest.MonkeyPatch) -> None:
527+
"""Reading a resource created from a template should not hop to a worker thread just to return the value."""
528+
import anyio.to_thread
529+
530+
hops = 0
531+
real_run_sync = anyio.to_thread.run_sync
532+
533+
async def counting_run_sync(func: Any, *args: Any, **kwargs: Any) -> Any:
534+
nonlocal hops
535+
hops += 1
536+
return await real_run_sync(func, *args, **kwargs)
537+
538+
monkeypatch.setattr(anyio.to_thread, "run_sync", counting_run_sync)
539+
540+
def sync_user(user_id: str) -> str:
541+
return f"user {user_id}"
542+
543+
async def async_order(order_id: str) -> str:
544+
return f"order {order_id}"
545+
546+
sync_template = ResourceTemplate.from_function(fn=sync_user, uri_template="users://{user_id}")
547+
async_template = ResourceTemplate.from_function(fn=async_order, uri_template="orders://{order_id}")
548+
549+
sync_resource = await sync_template.create_resource("users://1", {"user_id": "1"}, Context())
550+
assert isinstance(sync_resource, FunctionResource)
551+
assert await sync_resource.read() == "user 1"
552+
assert hops == 1
553+
554+
hops = 0
555+
async_resource = await async_template.create_resource("orders://1", {"order_id": "1"}, Context())
556+
assert isinstance(async_resource, FunctionResource)
557+
assert await async_resource.read() == "order 1"
558+
assert hops == 0

0 commit comments

Comments
 (0)