Skip to content

How to get session_id in tool #485

Description

@bhxiaoxinba

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

Activity

  1. ghostidentity commented on Apr 18, 2025

    @ghostidentity

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

  2. shiwenbin1617 commented on Apr 25, 2025

    @shiwenbin1617

    mark

  3. NICK-DUAN commented on Apr 30, 2025

    @NICK-DUAN

    +1

  4. CrossNox commented on May 1, 2025

    @CrossNox
    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)
        ...
  5. amir-arad commented on May 16, 2025

    @amir-arad
    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
  6. added
    enhancementRequest for a new feature that's not currently supported
    ready for workEnough information for someone to start working on
    P1Significant bug affecting many users, highly requested feature
    on Oct 7, 2025
  7. maxisbey commented on Feb 19, 2026

    @maxisbey
    Contributor

    Now tracked in #2098.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P1Significant bug affecting many users, highly requested featureenhancementRequest for a new feature that's not currently supportedready for workEnough information for someone to start working on

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions