-
Notifications
You must be signed in to change notification settings - Fork 1.6k
How to get session_id in tool #485
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Im having the same issue also, i can see the session_id is being passed |
mark |
+1 |
from mcp.server.fastmcp import Context, FastMCP
...
def _get_session_id(ctx: Context) -> int:
"""Get a unique session from the context."""
return id(ctx.session)
...
@mcp.tool()
async def your_tool(ctx: Context = None):
"""Some cool description"""
session_id = _get_session_id(ctx)
... |
def get_session_id(ctx: Context) -> str:
"""
Get a consistent session ID from an MCP context regardless of transport.
Args:
ctx: The MCP context object
Returns:
A unique session identifier that persists for the duration of the session
"""
if not ctx or not hasattr(ctx, 'session') or not ctx.session:
raise ValueError("Invalid context - missing session")
session = ctx.session
# Check if we already assigned a session ID
internal_attr_name = '__session_id'
if hasattr(session, internal_attr_name):
return getattr(session, internal_attr_name)
session_id = f"s_{id(session):x}_{random.randint(0, 255):02x}"
setattr(session, internal_attr_name, session_id)
return session_id |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
in the function of @mcp.tool , i want to get session_id, how i can get it?
The text was updated successfully, but these errors were encountered: