mirror of
https://github.com/PrefectHQ/fastmcp.git
synced 2026-08-28 02:10:38 +02:00
Add session-scoped state persistence (#2873)
This commit is contained in:
parent
266abef49e
commit
c8c84ff911
13 changed files with 744 additions and 167 deletions
42
examples/persistent_state/server.py
Normal file
42
examples/persistent_state/server.py
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
"""Example: Persistent session-scoped state.
|
||||
|
||||
This demonstrates using Context.get_state() and set_state() to store
|
||||
data that persists across tool calls within the same MCP session.
|
||||
|
||||
Run with:
|
||||
uv run python examples/persistent_state/server.py
|
||||
"""
|
||||
|
||||
from fastmcp import FastMCP
|
||||
from fastmcp.server.context import Context
|
||||
|
||||
server = FastMCP("StateExample")
|
||||
|
||||
|
||||
@server.tool
|
||||
async def set_value(key: str, value: str, ctx: Context) -> str:
|
||||
"""Store a value in session state."""
|
||||
await ctx.set_state(key, value)
|
||||
return f"Stored '{key}' = '{value}'"
|
||||
|
||||
|
||||
@server.tool
|
||||
async def get_value(key: str, ctx: Context) -> str:
|
||||
"""Retrieve a value from session state."""
|
||||
value = await ctx.get_state(key)
|
||||
if value is None:
|
||||
return f"Key '{key}' not found"
|
||||
return f"'{key}' = '{value}'"
|
||||
|
||||
|
||||
@server.tool
|
||||
async def list_session_info(ctx: Context) -> dict[str, str | None]:
|
||||
"""Get information about the current session."""
|
||||
return {
|
||||
"session_id": ctx.session_id,
|
||||
"transport": ctx.transport,
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
server.run(transport="streamable-http")
|
||||
Loading…
Add table
Add a link
Reference in a new issue