Skip to content

MCP Tools: No mechanism to pass user JWT token through ADK session.state to MCP server context #1402

Closed

Description

@pandasanjay

Description

Scenario

  • Our MCP Tools are intended for internal use and rely on API calls that require a user JWT token for authentication.
  • The ADK session.state can hold the JWT token, but the current implementation of MCP tools does not have direct access to the Context.
  • Even if some context access is possible, there is no mechanism to propagate the JWT token from the ADK session to the MCP server context.

Impact

  • MCP Tools cannot authenticate API requests on behalf of the user, blocking essential functionality.
  • There is a gap between where the JWT token resides (ADK session.state) and where it is needed (MCP server context).

Text-Based Flow Diagram

+----------+     +--------------------------+     +-------------+     +--------------------+     +-------------+
|   User   | --> | ADK Session              | --> |  MCP Tool   | -X->| MCP Server Context | --> | Backend API |
+----------+     | (JWT Token Stored Here)  |     |             |     | (Needs JWT Token)  |     | (Needs JWT) |
                   +--------------------------+     +-------------+     +--------------------+     +-------------+
                                                            |
                                                            |
                                                            V
                                                      Problem Area:
                                                      MCP Tool cannot pass JWT
                                                      from ADK Session to
                                                      MCP Server Context.
                                                      The "-X->" indicates the broken path.

Where Things Fall Apart

  • The MCP Tool does not have a mechanism to retrieve the JWT token from the ADK Session.
  • Consequently, there is no way to provide this JWT token to the MCP Server Context, which needs it to make authenticated calls to the Backend API.

Proposed solution - #1198

Activity

  1. added
    tools
    on Jun 14, 2025
  2. Jacksunwei commented on Jun 14, 2025

    @Jacksunwei
    Collaborator

    @seanzhou1023 is this something that you're working on?

  3. pandasanjay commented on Jun 14, 2025

    @pandasanjay
    Author

    Just few more context where and why we need it:

    I’m developing a multi-user MAS where agents can autonomously schedule background tasks on behalf of users. To ensure secure access and prevent unauthorized usage of user resources, I’m implementing JWT tokens in the sessions at the user state level. This ensures that user identities and their conversation sessions are isolated and not confused with others.

    The approach works seamlessly with ADK tools using CallbackContext or ToolContext. However, it doesn’t function as expected when applied to MCP as this information needed passed to MCP STDIO session to used as Env variable.

    But for other MCP transports like Streamable HTTP,need to explore some way to pass this existing token, instead of re authenticating.

  4. added theissue type on Jul 2, 2025
  5. muliu commented on Jul 15, 2025

    @muliu

    I also have such a requestment.

    The MCP Server used by the Agent requires authentication (check the Authorization Token in the HTTP header sent to the MCP Server)

    Assuming I already have a Token, the question now is: In ADK, what method should I use to transfer the Token to MCP Server?

  6. added
    mcp
    on Aug 21, 2025
  7. self-assigned this
    on Oct 15, 2025
  8. added
    request clarification
    needs review
    and removed
    request clarification
    on Nov 18, 2025
  9. klateefa commented on Nov 19, 2025

    @klateefa

    @pandasanjay Thanks for reporting we have noted the feature request . This feature is currently under review. Thank you for your understanding.

  10. jeevanragula commented on Nov 19, 2025

    @jeevanragula

    @klateefa Can we know if this is feature is being considered? We are also looking for the same feature where we need to pass the JWT token header to MCP Server calls.

    I see in mcp_tool.py file, tool_context is not being used anywhere in this method. Is this useful to pass the request headers to MCP server tool call?

      async def _get_headers(
          self, tool_context: ToolContext, credential: AuthCredential
      ) -> Optional[dict[str, str]]:
        """Extracts authentication headers from credentials.
    
        Args:
            tool_context: The tool context of the current invocation.
            credential: The authentication credential to process.
    
        Returns:
            Dictionary of headers to add to the request, or None if no auth.
    
        Raises:
            ValueError: If API key authentication is configured for non-header location.
        """
        headers: Optional[dict[str, str]] = None
        if credential:
          if credential.oauth2:
            headers = {"Authorization": f"Bearer {credential.oauth2.access_token}"}
          elif credential.http:
            # Handle HTTP authentication schemes
            if (
                credential.http.scheme.lower() == "bearer"
                and credential.http.credentials.token
            ):
              headers = {
                  "Authorization": f"Bearer {credential.http.credentials.token}"
              }
            elif credential.http.scheme.lower() == "basic":
              # Handle basic auth
              if (
                  credential.http.credentials.username
                  and credential.http.credentials.password
              ):
    
                credentials = f"{credential.http.credentials.username}:{credential.http.credentials.password}"
                encoded_credentials = base64.b64encode(
                    credentials.encode()
                ).decode()
                headers = {"Authorization": f"Basic {encoded_credentials}"}
            elif credential.http.credentials.token:
              # Handle other HTTP schemes with token
              headers = {
                  "Authorization": (
                      f"{credential.http.scheme} {credential.http.credentials.token}"
                  )
              }
          elif credential.api_key:
            if (
                not self._credentials_manager
                or not self._credentials_manager._auth_config
            ):
              error_msg = (
                  "Cannot find corresponding auth scheme for API key credential"
                  f" {credential}"
              )
              logger.error(error_msg)
              raise ValueError(error_msg)
            elif (
                self._credentials_manager._auth_config.auth_scheme.in_
                != APIKeyIn.header
            ):
              error_msg = (
                  "MCPTool only supports header-based API key authentication."
                  " Configured location:"
                  f" {self._credentials_manager._auth_config.auth_scheme.in_}"
              )
              logger.error(error_msg)
              raise ValueError(error_msg)
            else:
              headers = {
                  self._credentials_manager._auth_config.auth_scheme.name: (
                      credential.api_key
                  )
              }
          elif credential.service_account:
            # Service accounts should be exchanged for access tokens before reaching this point
            logger.warning(
                "Service account credentials should be exchanged before MCP"
                " session creation"
            )
    
        return headers
    
  11. wukath commented on Jan 15, 2026

    @wukath
    Collaborator

    @pandasanjay @muliu @jeevanragula We've added a header_provider param (https://github.com/google/adk-python/blob/main/src/google/adk/tools/mcp_tool/mcp_toolset.py#L96) that you can use to insert headers into the MCP session - it is a Callable that takes in a ReadonlyContext where you could retrieve your JWT token.

    It could look something like this:

    def jwt_header_provider(context: ReadonlyContext) -> Dict[str, str]:
        """
        Retrieves the JWT token from the ADK session state and adds it to the
        Authorization header.
        """
        headers = {}
        user_token = context.state.get("user_jwt_token") # Key used to store JWT in session state
    
        if user_token:
            headers["Authorization"] = f"Bearer {user_token}"
            print("DEBUG: Authorization header added with JWT token.")
        else:
            print("Warning: 'user_jwt_token' not found in ADK session state.")
    
        return headers
    
    McpToolset(
                connection_params=StreamableHTTPConnectionParams(
                    url='http://localhost:3000/mcp',
                ),
                header_provider=jwt_header_provider,
            )
    

    Let me know if that works for your use case?

  12. adk-bot commented on Jan 22, 2026

    @adk-bot
    Collaborator

    This issue has been automatically marked as stale because it has not had recent activity for 7 days after a maintainer requested clarification. It will be closed if no further activity occurs within 7 days.

  13. added
    stale
    request clarification
    on Jan 22, 2026
  14. adk-bot commented on Jan 29, 2026

    @adk-bot
    Collaborator

    This has been automatically closed because it has been marked as stale for over 7 days.

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

Metadata

Metadata

Labels

mcpneeds reviewrequest clarificationstaletools

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions