Blog Post
Smart AI Integration with the Model Context Protocol (MCP) ... part 5
Hi Mark Harrison (UK) - Any update on this ask.
the token validation logic in my code example is called on every tool invocation.
its also called at the beginning when it requests the list of tools.
you get the whole token from context.SecurityToken
OnTokenValidated = context =>
{
Console.WriteLine($"JWT Token: {context.SecurityToken}");
return Task.CompletedTask;
},
- alkondancJul 29, 2025
Microsoft
Hi Mark Harrison (UK) Thanks for the reply. Yes I saw this, the OnTokenValidated (an JwtBearerEvent), we will have the context which has the token and user claims.
Also, if I write a custom middleware like this, then also context is being accessible within the middleware.
Now, I was expecting the same in the Tool class as well. Even though we are registering using builder.Services.AddHttpContextAccessor(); If I tried injecting IHttpContextAccessor in my Tool class and try to access the HttpContext via it, it is always null.
I would need the user claims in the token to be passed on from my tool class to my business logic.
I tried IHttpContextAccessor, tried writing a middleware which will set the user claims to a class which is scoped. But that too didnt work, because by registering .WithTools<ToolClass>, we are registering our tool class as a singleton, so underlying scoping didnt work as well.
Any workaround that you could help with would be of much help.- Mark Harrison (UK)Jul 29, 2025
Microsoft
OK - i understand your issue. I dont have a solution.
I would post it here https://github.com/modelcontextprotocol/csharp-sdk/issues- alkondancJul 29, 2025
Microsoft
Hi Mark Harrison (UK) , thanks! Just checked the open issues in the SDK - Seems like the bug is closed.
Issue Resolution
Upgraded ModelContextProtocol.AspNetCore to "0.3.0-preview.3" and it started to work. I am having the HttpContext via HttpContextAccessor within Tool class.
Thanks again!