Don't block the event loop on sync resource and prompt functions (#2380)

This commit is contained in:
Max Isbey 2026-03-31 13:43:56 -04:00 • committed by GitHub
commit 3ce0f76e6e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,4 +1,5 @@
import json
import threading
from typing import Any
import pytest
@ -310,3 +311,22 @@ class TestResourceTemplateMetadata:
assert resource.meta == metadata
assert resource.meta["category"] == "inventory"
assert resource.meta["cacheable"] is True
@pytest.mark.anyio
async def test_sync_fn_runs_in_worker_thread():
"""Sync template functions must run in a worker thread, not the event loop."""
main_thread = threading.get_ident()
fn_thread: list[int] = []
def blocking_fn(name: str) -> str:
fn_thread.append(threading.get_ident())
return f"hello {name}"
template = ResourceTemplate.from_function(fn=blocking_fn, uri_template="test://{name}")
resource = await template.create_resource("test://world", {"name": "world"}, Context())
assert isinstance(resource, FunctionResource)
assert await resource.read() == "hello world"
assert fn_thread[0] != main_thread