1414
1515from __future__ import annotations
1616
17+ import base64
1718import inspect
1819import logging
1920from typing import Any
2324from typing import Union
2425import warnings
2526
27+ from fastapi .openapi .models import APIKeyIn
2628from google .genai .types import FunctionDeclaration
2729from mcp .types import Tool as McpBaseTool
2830from typing_extensions import override
3739from ..base_authenticated_tool import BaseAuthenticatedTool
3840# import
3941from ..tool_context import ToolContext
40- from .mcp_auth_utils import get_mcp_auth_headers
4142from .mcp_session_manager import MCPSessionManager
4243from .mcp_session_manager import retry_on_errors
4344
@@ -194,12 +195,7 @@ async def _run_async_impl(
194195 Any: The response from the tool.
195196 """
196197 # Extract headers from credential for session pooling
197- auth_scheme = (
198- self ._auth_config .auth_scheme
199- if hasattr (self , "_auth_config" ) and self ._auth_config
200- else None
201- )
202- auth_headers = get_mcp_auth_headers (auth_scheme , credential )
198+ auth_headers = await self ._get_headers (tool_context , credential )
203199 dynamic_headers = None
204200 if self ._header_provider :
205201 dynamic_headers = self ._header_provider (
@@ -221,6 +217,90 @@ async def _run_async_impl(
221217 response = await session .call_tool (self ._mcp_tool .name , arguments = args )
222218 return response .model_dump (exclude_none = True , mode = "json" )
223219
220+ async def _get_headers (
221+ self , tool_context : ToolContext , credential : AuthCredential
222+ ) -> Optional [dict [str , str ]]:
223+ """Extracts authentication headers from credentials.
224+
225+ Args:
226+ tool_context: The tool context of the current invocation.
227+ credential: The authentication credential to process.
228+
229+ Returns:
230+ Dictionary of headers to add to the request, or None if no auth.
231+
232+ Raises:
233+ ValueError: If API key authentication is configured for non-header location.
234+ """
235+ headers : Optional [dict [str , str ]] = None
236+ if credential :
237+ if credential .oauth2 :
238+ headers = {"Authorization" : f"Bearer { credential .oauth2 .access_token } " }
239+ elif credential .http :
240+ # Handle HTTP authentication schemes
241+ if (
242+ credential .http .scheme .lower () == "bearer"
243+ and credential .http .credentials .token
244+ ):
245+ headers = {
246+ "Authorization" : f"Bearer { credential .http .credentials .token } "
247+ }
248+ elif credential .http .scheme .lower () == "basic" :
249+ # Handle basic auth
250+ if (
251+ credential .http .credentials .username
252+ and credential .http .credentials .password
253+ ):
254+
255+ credentials = f"{ credential .http .credentials .username } :{ credential .http .credentials .password } "
256+ encoded_credentials = base64 .b64encode (
257+ credentials .encode ()
258+ ).decode ()
259+ headers = {"Authorization" : f"Basic { encoded_credentials } " }
260+ elif credential .http .credentials .token :
261+ # Handle other HTTP schemes with token
262+ headers = {
263+ "Authorization" : (
264+ f"{ credential .http .scheme } { credential .http .credentials .token } "
265+ )
266+ }
267+ elif credential .api_key :
268+ if (
269+ not self ._credentials_manager
270+ or not self ._credentials_manager ._auth_config
271+ ):
272+ error_msg = (
273+ "Cannot find corresponding auth scheme for API key credential"
274+ f" { credential } "
275+ )
276+ logger .error (error_msg )
277+ raise ValueError (error_msg )
278+ elif (
279+ self ._credentials_manager ._auth_config .auth_scheme .in_
280+ != APIKeyIn .header
281+ ):
282+ error_msg = (
283+ "McpTool only supports header-based API key authentication."
284+ " Configured location:"
285+ f" { self ._credentials_manager ._auth_config .auth_scheme .in_ } "
286+ )
287+ logger .error (error_msg )
288+ raise ValueError (error_msg )
289+ else :
290+ headers = {
291+ self ._credentials_manager ._auth_config .auth_scheme .name : (
292+ credential .api_key
293+ )
294+ }
295+ elif credential .service_account :
296+ # Service accounts should be exchanged for access tokens before reaching this point
297+ logger .warning (
298+ "Service account credentials should be exchanged before MCP"
299+ " session creation"
300+ )
301+
302+ return headers
303+
224304
225305class MCPTool (McpTool ):
226306 """Deprecated name, use `McpTool` instead."""
0 commit comments