Title: How can I access the bearer token inside my MCP tool? · Issue #1414 · modelcontextprotocol/python-sdk · GitHub
Open Graph Title: How can I access the bearer token inside my MCP tool? · Issue #1414 · modelcontextprotocol/python-sdk
X Title: How can I access the bearer token inside my MCP tool? · Issue #1414 · modelcontextprotocol/python-sdk
Description: 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_doc...
Open Graph Description: 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 acce...
X Description: 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 ...
Opengraph URL: https://github.com/modelcontextprotocol/python-sdk/issues/1414
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"How can I access the bearer token inside my MCP tool?","articleBody":"### Question\n\nHi everyone,\n\nI created a multi-client RAG system to organize client documents.\n\nCurrently, authentication works correctly using the keys stored in the .env file.\n\nHowever, 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.\n\nI tried passing ctx: Context or AccessToken, but it always appears empty.\n\nHere is my code:\n\n```python\nimport argparse\nfrom typing import Dict, Any\nfrom pydantic import AnyHttpUrl # type:ignore\nfrom mcp.server.auth.settings import AuthSettings # type:ignore\nfrom mcp.server.auth.provider import AccessToken, TokenVerifier # type:ignore\nfrom mcp.server.fastmcp import Context, FastMCP # type:ignore\nimport sys\nimport time\nimport json\n\nfrom config.logger import logger\nfrom src.client_manager import MultiClientManager\n\n\n# --- Inizializza il manager multi-cliente ---\ntry:\n client_manager = MultiClientManager()\n logger.info(\"🏢 Multi-Client Manager inizializzato\")\nexcept Exception as e:\n logger.error(f\"❌ Errore inizializzazione manager: {e}\")\n sys.exit(1)\n\nclass EnvironmentMultiClientTokenVerifier(TokenVerifier):\n \"Token verifier che mappa token univoci ai client_id.\"\n\n def __init__(self):\n # Carica i token da variabili d'ambiente\n # Formato: MCP_TOKEN_\u003cCLIENT_ID\u003e=token_value\n self.token_to_client = {}\n \n # Scansiona tutte le variabili d'ambiente che iniziano con MCP_TOKEN_\n for key, value in os.environ.items():\n if key.startswith(\"MCP_TOKEN_\"):\n client_id = key[10:].upper() \n self.token_to_client[value] = client_id\n \n if not self.token_to_client:\n raise ValueError(\"Nessun token trovato! Definisci variabili MCP_TOKEN_\u003cCLIENT_ID\u003e\")\n\n async def verify_token(self, token: str) -\u003e AccessToken | None:\n \"Verifica il token e restituisce il client_id associato.\"\n client_id = self.token_to_client.get(token)\n\n if client_id:\n access_token = AccessToken(\n token=token,\n client_id=client_id,\n scopes=[\"user\"]\n )\n return access_token\n \n return None\n\n\n# Initialize FastMCP server\nmcp = FastMCP(\n \"rag-server-multiclient-auth\",\n # Token verifier for authentication\n token_verifier=EnvironmentMultiClientTokenVerifier(),\n # Auth settings for RFC 9728 Protected Resource Metadata\n auth=AuthSettings(\n issuer_url=AnyHttpUrl(\"https://auth.example.com\"), # Authorization Server URL\n resource_server_url=AnyHttpUrl(\"http://localhost:8000\"), # This server's URL\n required_scopes=[\"user\"],\n ),\n)\n\n# --- MCP Tools ---\n@mcp.tool()\ndef search_documents(query: str, limit: int) -\u003e Dict[str, Any]:\n \"Search documents for a specific client using RAG pipeline\n \n Args:\n query: The search query\n limit: Maximum number of results to return\n \"\n\n\t# Get the client id from Beraer token or args params pass\n\tclient_id = 'Client1'\n\n logger.info(f\"🔍 Searching for client '{client_id}': '{query}' (limit: {limit})\")\n start_time = time.time()\n \n try:\n results = client_manager.search_client_documents(\n client_id=client_id,\n query=query, \n top_k=limit\n )\n \n search_time = time.time() - start_time\n \n return {\n \"client_id\": client_id,\n \"query\": query,\n \"results\": results,\n \"total_found\": len(results),\n \"execution_time\": f\"{search_time:.2f}s\",\n \"status\": \"success\"\n }\n \n except Exception as e:\n error_msg = f\"Error during search for client {client_id}: {str(e)}\"\n logger.error(error_msg)\n search_time = time.time() - start_time\n \n return {\n \"client_id\": client_id,\n \"query\": query,\n \"results\": [],\n \"total_found\": 0,\n \"execution_time\": f\"{search_time:.2f}s\",\n \"status\": \"error\",\n \"error\": error_msg\n }\n \n\nif __name__ == \"__main__\":\n mcp.run(transport='sse')\n```\n\n**Question:**\nIs there a way to access the bearer token within a MCP tool function like `search_documents`?\n\nThanks in advance for any help!\n\n\n### Additional Context\n\npython=3.12.3\nmcp==1.14.1\n","author":{"url":"https://github.com/abernardini-inc","@type":"Person","name":"abernardini-inc"},"datePublished":"2025-09-30T11:00:38.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":2},"url":"https://github.com/1414/python-sdk/issues/1414"}
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:a504dfe3-38e1-3e04-c187-378ef6d3fb34 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | B3C2:A0835:3AA58A8:4CDBCF2:6A5D0E91 |
| html-safe-nonce | 990a90e0eb3003e1a4291156f1dde6bd01583b86409fede77221722c11535bbb |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJCM0MyOkEwODM1OjNBQTU4QTg6NENEQkNGMjo2QTVEMEU5MSIsInZpc2l0b3JfaWQiOiIxMzI1NzMyMzI4NzQ5NDY5MzI5IiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | e2decfe8c610310a65439eef1a28f0fb1f157476fc6f6019069cdbfff42310cf |
| hovercard-subject-tag | issue:3468822917 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/modelcontextprotocol/python-sdk/1414/issue_layout |
| twitter:image | https://opengraph.githubassets.com/39956f05186f0effb4f8b9723ce10fd5b5ac1da7baf7f6694598ae452085f218/modelcontextprotocol/python-sdk/issues/1414 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/39956f05186f0effb4f8b9723ce10fd5b5ac1da7baf7f6694598ae452085f218/modelcontextprotocol/python-sdk/issues/1414 |
| og:image:alt | 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 acce... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | abernardini-inc |
| hostname | github.com |
| expected-hostname | github.com |
| None | 5290d7e14309ad1e76106a9c4237bd1041517e83ea182c8ab756752cb0c6940b |
| turbo-cache-control | no-preview |
| go-import | github.com/modelcontextprotocol/python-sdk git https://github.com/modelcontextprotocol/python-sdk.git |
| octolytics-dimension-user_id | 182288589 |
| octolytics-dimension-user_login | modelcontextprotocol |
| octolytics-dimension-repository_id | 862584018 |
| octolytics-dimension-repository_nwo | modelcontextprotocol/python-sdk |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 862584018 |
| octolytics-dimension-repository_network_root_nwo | modelcontextprotocol/python-sdk |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 9c975978430e9ad293956f2bbdaf153b1bd84a99 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
Links:
Viewport: width=device-width