Add cache_hints constructor map for SEP-2549 caching hints (#3015)
This commit is contained in:
parent
c85836a081
commit
533c6a8226
4 changed files with 519 additions and 4 deletions
0
docs_src/caching/__init__.py
Normal file
0
docs_src/caching/__init__.py
Normal file
19
docs_src/caching/tutorial001.py
Normal file
19
docs_src/caching/tutorial001.py
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
from mcp.server import CacheHint, MCPServer
|
||||
|
||||
mcp = MCPServer(
|
||||
"Weather",
|
||||
cache_hints={
|
||||
"tools/list": CacheHint(ttl_ms=60_000, scope="public"),
|
||||
"resources/read": CacheHint(ttl_ms=5_000),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def forecast(city: str) -> str:
|
||||
return f"Sunny in {city}"
|
||||
|
||||
|
||||
@mcp.resource("config://units")
|
||||
def units() -> str:
|
||||
return "metric"
|
||||
18
docs_src/caching/tutorial002.py
Normal file
18
docs_src/caching/tutorial002.py
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
from typing import Any
|
||||
|
||||
from mcp_types import ListToolsResult, PaginatedRequestParams, Tool
|
||||
|
||||
from mcp.server import CacheHint, Server, ServerRequestContext
|
||||
|
||||
TOOLS = [Tool(name="forecast", input_schema={"type": "object"})]
|
||||
|
||||
|
||||
async def list_tools(ctx: ServerRequestContext[Any], params: PaginatedRequestParams | None) -> ListToolsResult:
|
||||
return ListToolsResult(tools=TOOLS, ttl_ms=1_000)
|
||||
|
||||
|
||||
server = Server(
|
||||
"Weather",
|
||||
on_list_tools=list_tools,
|
||||
cache_hints={"tools/list": CacheHint(ttl_ms=60_000, scope="public")},
|
||||
)
|
||||
15
docs_src/caching/tutorial003.py
Normal file
15
docs_src/caching/tutorial003.py
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
from mcp import Client
|
||||
from mcp.server import CacheHint, MCPServer
|
||||
|
||||
mcp = MCPServer("Weather", cache_hints={"tools/list": CacheHint(ttl_ms=60_000, scope="public")})
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def forecast(city: str) -> str:
|
||||
return f"Sunny in {city}"
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
async with Client(mcp) as client:
|
||||
tools = await client.list_tools()
|
||||
print(f"{len(tools.tools)} tools, fresh for {tools.ttl_ms / 1000:.0f}s, scope={tools.cache_scope}")
|
||||
Loading…
Reference in a new issue