Skip to content

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

Open
bhxiaoxinba opened this issue Apr 11, 2025 · 5 comments
Open

How to get session_id in tool #485

bhxiaoxinba opened this issue Apr 11, 2025 · 5 comments

Comments

@bhxiaoxinba
Copy link

in the function of @mcp.tool , i want to get session_id, how i can get it?

@ghostidentity
Copy link

Im having the same issue also, i can see the session_id is being passed

@shiwenbin1617
Copy link

mark

@NICK-DUAN
Copy link

+1

@CrossNox
Copy link

CrossNox commented May 1, 2025

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)
    ...

@amir-arad
Copy link

amir-arad commented May 16, 2025

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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants