Skip to content

Commit fb1c510

Browse files
committed
Keep the tutorial handler a plain function with a separate state holder
1 parent 804043b commit fb1c510

2 files changed

Lines changed: 13 additions & 12 deletions

File tree

docs/advanced/caching.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ One caveat on paginated lists: the protocol requires the **same `cacheScope` on
3939

4040
On a 2026-07-28 session, `Client` honors the hints for you: it has a built-in response cache, on by default. A result that arrives carrying a `ttlMs` is stored, and an identical call within that TTL is served from the cache with no round trip. A result that carries *no* hint is not cached: hint-less results get `CacheConfig.default_ttl_ms`, which defaults to `0` (immediately stale), so a server that declares nothing sees exactly the call-for-call traffic it always did.
4141

42-
```python title="client.py" hl_lines="32 34 37"
42+
```python title="client.py" hl_lines="33 35 38"
4343
--8<-- "docs_src/caching/tutorial003.py"
4444
```
4545

docs_src/caching/tutorial003.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,30 +9,31 @@
99

1010

1111
@dataclass
12-
class Demo:
12+
class DemoState:
1313
fetches: int = 0
1414
now: float = 1_000_000.0
1515

16-
async def list_tools(
17-
self, ctx: ServerRequestContext[Any], params: PaginatedRequestParams | None
18-
) -> ListToolsResult:
19-
self.fetches += 1
20-
return ListToolsResult(tools=[Tool(name="forecast", input_schema={"type": "object"})])
16+
17+
state = DemoState()
18+
19+
20+
async def list_tools(ctx: ServerRequestContext[Any], params: PaginatedRequestParams | None) -> ListToolsResult:
21+
state.fetches += 1
22+
return ListToolsResult(tools=[Tool(name="forecast", input_schema={"type": "object"})])
2123

2224

23-
demo = Demo()
2425
server = Server(
2526
"Weather",
26-
on_list_tools=demo.list_tools,
27+
on_list_tools=list_tools,
2728
cache_hints={"tools/list": CacheHint(ttl_ms=60_000, scope="public")},
2829
)
2930

3031

3132
async def main() -> None:
32-
async with Client(server, cache=CacheConfig(clock=lambda: demo.now)) as client:
33+
async with Client(server, cache=CacheConfig(clock=lambda: state.now)) as client:
3334
await client.list_tools() # fetch 1
3435
await client.list_tools() # fresh for 60s: served from the cache
35-
demo.now += 60.0
36+
state.now += 60.0
3637
await client.list_tools() # the TTL ran out: fetch 2
3738
await client.list_tools(cache_mode="refresh") # skip the cache read: fetch 3
38-
print(f"4 calls, {demo.fetches} fetches")
39+
print(f"4 calls, {state.fetches} fetches")

0 commit comments

Comments
 (0)