René's URL Explorer Experiment


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

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@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-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:a504dfe3-38e1-3e04-c187-378ef6d3fb34
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idB3C2:A0835:3AA58A8:4CDBCF2:6A5D0E91
html-safe-nonce990a90e0eb3003e1a4291156f1dde6bd01583b86409fede77221722c11535bbb
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJCM0MyOkEwODM1OjNBQTU4QTg6NENEQkNGMjo2QTVEMEU5MSIsInZpc2l0b3JfaWQiOiIxMzI1NzMyMzI4NzQ5NDY5MzI5IiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0=
visitor-hmace2decfe8c610310a65439eef1a28f0fb1f157476fc6f6019069cdbfff42310cf
hovercard-subject-tagissue:3468822917
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/modelcontextprotocol/python-sdk/1414/issue_layout
twitter:imagehttps://opengraph.githubassets.com/39956f05186f0effb4f8b9723ce10fd5b5ac1da7baf7f6694598ae452085f218/modelcontextprotocol/python-sdk/issues/1414
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/39956f05186f0effb4f8b9723ce10fd5b5ac1da7baf7f6694598ae452085f218/modelcontextprotocol/python-sdk/issues/1414
og:image:altQuestion 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:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernameabernardini-inc
hostnamegithub.com
expected-hostnamegithub.com
None5290d7e14309ad1e76106a9c4237bd1041517e83ea182c8ab756752cb0c6940b
turbo-cache-controlno-preview
go-importgithub.com/modelcontextprotocol/python-sdk git https://github.com/modelcontextprotocol/python-sdk.git
octolytics-dimension-user_id182288589
octolytics-dimension-user_loginmodelcontextprotocol
octolytics-dimension-repository_id862584018
octolytics-dimension-repository_nwomodelcontextprotocol/python-sdk
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id862584018
octolytics-dimension-repository_network_root_nwomodelcontextprotocol/python-sdk
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
release9c975978430e9ad293956f2bbdaf153b1bd84a99
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://github.com/modelcontextprotocol/python-sdk/issues/1414#start-of-content
https://github.com/
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmodelcontextprotocol%2Fpython-sdk%2Fissues%2F1414
GitHub CopilotWrite better code with AIhttps://github.com/features/copilot
GitHub Copilot appDirect agents from issue to mergehttps://github.com/features/ai/github-app
MCP RegistryNewIntegrate external toolshttps://github.com/mcp
ActionsAutomate any workflowhttps://github.com/features/actions
CodespacesInstant dev environmentshttps://github.com/features/codespaces
IssuesPlan and track workhttps://github.com/features/issues
Code ReviewManage code changeshttps://github.com/features/code-review
GitHub Advanced SecurityFind and fix vulnerabilitieshttps://github.com/security/advanced-security
Code securitySecure your code as you buildhttps://github.com/security/advanced-security/code-security
Secret protectionStop leaks before they starthttps://github.com/security/advanced-security/secret-protection
Why GitHubhttps://github.com/why-github
Documentationhttps://docs.github.com
Bloghttps://github.blog
Changeloghttps://github.blog/changelog
Marketplacehttps://github.com/marketplace
View all featureshttps://github.com/features
Enterpriseshttps://github.com/enterprise
Small and medium teamshttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
App Modernizationhttps://github.com/solutions/use-case/app-modernization
DevSecOpshttps://github.com/solutions/use-case/devsecops
DevOpshttps://github.com/solutions/use-case/devops
CI/CDhttps://github.com/solutions/use-case/ci-cd
View all use caseshttps://github.com/solutions/use-case
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
View all industrieshttps://github.com/solutions/industry
View all solutionshttps://github.com/solutions
AIhttps://github.com/resources/articles?topic=ai
Software Developmenthttps://github.com/resources/articles?topic=software-development
DevOpshttps://github.com/resources/articles?topic=devops
Securityhttps://github.com/resources/articles?topic=security
View all topicshttps://github.com/resources/articles
Customer storieshttps://github.com/customer-stories
Events & webinarshttps://github.com/resources/events
Ebooks & reportshttps://github.com/resources/whitepapers
Business insightshttps://github.com/solutions/executive-insights
GitHub Skillshttps://skills.github.com
Documentationhttps://docs.github.com
Customer supporthttps://support.github.com
Community forumhttps://github.com/orgs/community/discussions
Trust centerhttps://github.com/trust-center
Partnershttps://github.com/partners
View all resourceshttps://github.com/resources
GitHub SponsorsFund open source developershttps://github.com/open-source/sponsors
Security Labhttps://securitylab.github.com
Maintainer Communityhttps://maintainers.github.com
Acceleratorhttps://github.com/open-source/accelerator
GitHub Starshttps://stars.github.com
Archive Programhttps://archiveprogram.github.com
Topicshttps://github.com/topics
Trendinghttps://github.com/trending
Collectionshttps://github.com/collections
Enterprise platformAI-powered developer platformhttps://github.com/enterprise
GitHub Advanced SecurityEnterprise-grade security featureshttps://github.com/security/advanced-security
Copilot for BusinessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/enterprise/premium-support
Pricinghttps://github.com/pricing
Search syntax tipshttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
documentationhttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmodelcontextprotocol%2Fpython-sdk%2Fissues%2F1414
Sign up https://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=modelcontextprotocol%2Fpython-sdk
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/1414
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/1414
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/1414
Please reload this pagehttps://github.com/modelcontextprotocol/python-sdk/issues/1414
modelcontextprotocol https://github.com/modelcontextprotocol
python-sdkhttps://github.com/modelcontextprotocol/python-sdk
Notifications https://github.com/login?return_to=%2Fmodelcontextprotocol%2Fpython-sdk
Fork 3.7k https://github.com/login?return_to=%2Fmodelcontextprotocol%2Fpython-sdk
Star 23.7k https://github.com/login?return_to=%2Fmodelcontextprotocol%2Fpython-sdk
Code https://github.com/modelcontextprotocol/python-sdk
Issues 259 https://github.com/modelcontextprotocol/python-sdk/issues
Pull requests 306 https://github.com/modelcontextprotocol/python-sdk/pulls
Actions https://github.com/modelcontextprotocol/python-sdk/actions
Projects https://github.com/modelcontextprotocol/python-sdk/projects
Models https://github.com/modelcontextprotocol/python-sdk/models
Security and quality 6 https://github.com/modelcontextprotocol/python-sdk/security
Insights https://github.com/modelcontextprotocol/python-sdk/pulse
Code https://github.com/modelcontextprotocol/python-sdk
Issues https://github.com/modelcontextprotocol/python-sdk/issues
Pull requests https://github.com/modelcontextprotocol/python-sdk/pulls
Actions https://github.com/modelcontextprotocol/python-sdk/actions
Projects https://github.com/modelcontextprotocol/python-sdk/projects
Models https://github.com/modelcontextprotocol/python-sdk/models
Security and quality https://github.com/modelcontextprotocol/python-sdk/security
Insights https://github.com/modelcontextprotocol/python-sdk/pulse
How can I access the bearer token inside my MCP tool?https://github.com/modelcontextprotocol/python-sdk/issues/1414#top
authIssues and PRs related to Authentication / OAuthhttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22auth%22
questionFurther information is requestedhttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22question%22
https://github.com/abernardini-inc
abernardini-inchttps://github.com/abernardini-inc
on Sep 30, 2025https://github.com/modelcontextprotocol/python-sdk/issues/1414#issue-3468822917
authIssues and PRs related to Authentication / OAuthhttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22auth%22
questionFurther information is requestedhttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22question%22
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Viewport: width=device-width


URLs of crawlers that visited me.