Question
Hi everyone,
I created a multi-client RAG system to organize client documents.
Currently, authentication works correctly using the keys stored in the .env file.
However, I'm trying to access the bearer token inside my search_documents tool, but I haven't been successful. I need the bearer token to retrieve the name of the associated client, as each client has their own personal bearer token.
I tried passing ctx: Context or AccessToken, but it always appears empty.
Here is my code:
importargparsefromtypingimportDict, AnyfrompydanticimportAnyHttpUrl# type:ignorefrommcp.server.auth.settingsimportAuthSettings# type:ignorefrommcp.server.auth.providerimportAccessToken, TokenVerifier# type:ignorefrommcp.server.fastmcpimportContext, FastMCP# type:ignoreimportsysimporttimeimportjsonfromconfig.loggerimportloggerfromsrc.client_managerimportMultiClientManager# --- Inizializza il manager multi-cliente ---try:
client_manager=MultiClientManager()
logger.info("🏢 Multi-Client Manager inizializzato")
exceptExceptionase:
logger.error(f"❌ Errore inizializzazione manager: {e}")
sys.exit(1)
classEnvironmentMultiClientTokenVerifier(TokenVerifier):
"Token verifier che mappa token univoci ai client_id."def__init__(self):
# Carica i token da variabili d'ambiente# Formato: MCP_TOKEN_<CLIENT_ID>=token_valueself.token_to_client= {}
# Scansiona tutte le variabili d'ambiente che iniziano con MCP_TOKEN_forkey, valueinos.environ.items():
ifkey.startswith("MCP_TOKEN_"):
client_id=key[10:].upper() self.token_to_client[value] =client_idifnotself.token_to_client:
raiseValueError("Nessun token trovato! Definisci variabili MCP_TOKEN_<CLIENT_ID>")
asyncdefverify_token(self, token: str) ->AccessToken|None:
"Verifica il token e restituisce il client_id associato."client_id=self.token_to_client.get(token)
ifclient_id:
access_token=AccessToken(
token=token,
client_id=client_id,
scopes=["user"]
)
returnaccess_tokenreturnNone# Initialize FastMCP servermcp=FastMCP(
"rag-server-multiclient-auth",
# Token verifier for authenticationtoken_verifier=EnvironmentMultiClientTokenVerifier(),
# Auth settings for RFC 9728 Protected Resource Metadataauth=AuthSettings(
issuer_url=AnyHttpUrl("https://auth.example.com"), # Authorization Server URLresource_server_url=AnyHttpUrl("http://localhost:8000"), # This server's URLrequired_scopes=["user"],
),
)
# --- MCP Tools ---@mcp.tool()defsearch_documents(query: str, limit: int) ->Dict[str, Any]:
"SearchdocumentsforaspecificclientusingRAGpipelineArgs:
query: Thesearchquerylimit: Maximumnumberofresultstoreturn
"
# Get the client id from Beraer token or args params passclient_id='Client1'logger.info(f"🔍 Searching for client '{client_id}': '{query}' (limit: {limit})")
start_time=time.time()
try:
results=client_manager.search_client_documents(
client_id=client_id,
query=query, top_k=limit
)
search_time=time.time() -start_timereturn {
"client_id": client_id,
"query": query,
"results": results,
"total_found": len(results),
"execution_time": f"{search_time:.2f}s",
"status": "success"
}
exceptExceptionase:
error_msg=f"Error during search for client {client_id}: {str(e)}"logger.error(error_msg)
search_time=time.time() -start_timereturn {
"client_id": client_id,
"query": query,
"results": [],
"total_found": 0,
"execution_time": f"{search_time:.2f}s",
"status": "error",
"error": error_msg
}
if__name__=="__main__":
mcp.run(transport='sse')Question:
Is there a way to access the bearer token within a MCP tool function like search_documents?
Thanks in advance for any help!
Additional Context
python=3.12.3
mcp==1.14.1
Question
Hi everyone,
I created a multi-client RAG system to organize client documents.
Currently, authentication works correctly using the keys stored in the .env file.
However, I'm trying to access the bearer token inside my search_documents tool, but I haven't been successful. I need the bearer token to retrieve the name of the associated client, as each client has their own personal bearer token.
I tried passing ctx: Context or AccessToken, but it always appears empty.
Here is my code:
Question:
Is there a way to access the bearer token within a MCP tool function like
search_documents?Thanks in advance for any help!
Additional Context
python=3.12.3
mcp==1.14.1