-
Notifications
You must be signed in to change notification settings - Fork 547
Add conceptual docs on accessing HttpContext #771
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+288
−2
Merged
Changes from 5 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
ac36141
Add doc with sample on accessing HttpContext
mikekistler e0c974b
Fix build errors
mikekistler 44c1979
Minor fixes
mikekistler c65a120
Apply suggestions from PR review
mikekistler c6ae222
Address PR review comments
mikekistler f578d88
Address PR review comments
mikekistler File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| --- | ||
| title: HTTP Context | ||
| author: mikekistler | ||
| description: How to access the HttpContext in the MCP C# SDK. | ||
| uid: httpcontext | ||
| --- | ||
|
|
||
| ## HTTP Context | ||
|
|
||
| When using the Streamable HTTP transport, an MCP server may need to access the underlying [HttpContext] for a request. | ||
| The [HttpContext] contains request metadata such as the HTTP headers, authorization context, and the actual path and query string for the request. | ||
|
|
||
| To access the [HttpContext], the MCP server should add the [IHttpContextAccessor] service to the application service collection (typically in Program.cs). | ||
| Then any classes, e.g. a class containing MCP tools, should accept an [IHttpContextAccessor] in their constructor and store this for use by its methods. | ||
| Methods then use the [HttpContext property][IHttpContextAccessor.HttpContext] of the accessor to get the current context. | ||
|
|
||
| [HttpContext]: https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.http.httpcontext | ||
| [IHttpContextAccessor]: https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.http.ihttpcontextaccessor | ||
| [IHttpContextAccessor.HttpContext]: https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.http.ihttpcontextaccessor.httpcontext | ||
|
|
||
| The following code snippet illustrates how to add the [IHttpContextAccessor] service to the application service collection: | ||
|
|
||
| [!code-csharp[](samples/Program.cs?name=snippet_AddHttpContextAccessor)] | ||
|
|
||
| Any class that needs access to the [HttpContext] can accept an [IHttpContextAccessor] in its constructor and store it for later use. | ||
| Methods of the class can then access the current [HttpContext] using the stored accessor. | ||
|
|
||
| The following code snippet shows the `ContextTools` class accepting an [IHttpContextAccessor] in its primary constructor | ||
| and the `GetHttpHeaders` method accessing the current [HttpContext] to retrieve the HTTP headers from the current request. | ||
|
|
||
| [!code-csharp[](samples/Tools/ContextTools.cs?name=snippet_AccessHttpContext)] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk.Web"> | ||
|
|
||
| <PropertyGroup> | ||
| <TargetFramework>net9.0</TargetFramework> | ||
| <Nullable>enable</Nullable> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| </PropertyGroup> | ||
|
|
||
| <PropertyGroup> | ||
| <GenerateAssemblyInfo>false</GenerateAssemblyInfo> | ||
| <GenerateTargetFrameworkAttribute>false</GenerateTargetFrameworkAttribute> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="../../../../src/ModelContextProtocol.AspNetCore/ModelContextProtocol.AspNetCore.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| @HostAddress = http://localhost:3001 | ||
|
|
||
| POST {{HostAddress}}/ | ||
| Accept: application/json, text/event-stream | ||
| Content-Type: application/json | ||
| MCP-Protocol-Version: 2025-06-18 | ||
|
|
||
| { | ||
| "jsonrpc": "2.0", | ||
| "id": 2, | ||
| "method": "tools/call", | ||
| "params": { | ||
| "name": "get_http_headers" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| using HttpContext.Tools; | ||
|
|
||
| var builder = WebApplication.CreateBuilder(args); | ||
|
|
||
| // Add services to the container. | ||
|
|
||
| builder.Services.AddMcpServer() | ||
| .WithHttpTransport() | ||
| .WithTools<ContextTools>(); | ||
|
|
||
| // <snippet_AddHttpContextAccessor> | ||
| builder.Services.AddHttpContextAccessor(); | ||
| // </snippet_AddHttpContextAccessor> | ||
|
|
||
| builder.Logging.AddConsole(options => | ||
| { | ||
| options.LogToStandardErrorThreshold = LogLevel.Information; | ||
| }); | ||
|
|
||
| var app = builder.Build(); | ||
|
|
||
| app.UseHttpsRedirection(); | ||
|
|
||
| app.MapMcp(); | ||
|
|
||
| app.Run(); |
23 changes: 23 additions & 0 deletions
23
docs/concepts/httpcontext/samples/Properties/launchSettings.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| { | ||
| "$schema": "https://json.schemastore.org/launchsettings.json", | ||
| "profiles": { | ||
| "http": { | ||
| "commandName": "Project", | ||
| "dotnetRunMessages": true, | ||
| "launchBrowser": false, | ||
| "applicationUrl": "http://localhost:3001", | ||
| "environmentVariables": { | ||
| "ASPNETCORE_ENVIRONMENT": "Development" | ||
| } | ||
| }, | ||
| "https": { | ||
| "commandName": "Project", | ||
| "dotnetRunMessages": true, | ||
| "launchBrowser": false, | ||
| "applicationUrl": "https://localhost:7191;http://localhost:3001", | ||
| "environmentVariables": { | ||
| "ASPNETCORE_ENVIRONMENT": "Development" | ||
| } | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| using Microsoft.AspNetCore.Http; | ||
| using ModelContextProtocol.Server; | ||
| using System.ComponentModel; | ||
| using System.Text.Json; | ||
|
|
||
| namespace HttpContext.Tools; | ||
|
|
||
|
|
||
| // <snippet_AccessHttpContext> | ||
| public class ContextTools(IHttpContextAccessor _httpContextAccessor) | ||
| { | ||
| [McpServerTool(UseStructuredContent = true)] | ||
| [Description("Retrieves the HTTP headers from the current request and returns them as a JSON object.")] | ||
| public object GetHttpHeaders() | ||
| { | ||
| var context = _httpContextAccessor.HttpContext; | ||
| if (context == null) | ||
| { | ||
| return "No HTTP context available"; | ||
| } | ||
|
|
||
| // Remainder of GetHttpHeaders method follows | ||
mikekistler marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| // </snippet_AccessHttpContext> | ||
|
|
||
| var headers = new Dictionary<string, string>(); | ||
| foreach (var header in context.Request.Headers) | ||
| { | ||
| headers[header.Key] = string.Join(", ", header.Value.ToArray()); | ||
| } | ||
|
|
||
| return headers; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,112 @@ | ||
| { | ||
| "cells": [ | ||
| { | ||
| "cell_type": "markdown", | ||
| "id": "37868ee2", | ||
| "metadata": { | ||
| "language_info": { | ||
| "name": "polyglot-notebook" | ||
| }, | ||
| "polyglot_notebook": { | ||
| "kernelName": "csharp" | ||
| } | ||
| }, | ||
| "source": [ | ||
| "## HTTP Context\n", | ||
| "\n", | ||
| "This project illustrates how to access the HttpContext from tool calls. See the [README](../README.md) for more details.\n" | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "markdown", | ||
| "id": "093a7d4f", | ||
| "metadata": {}, | ||
| "source": [ | ||
| "### Examples\n", | ||
| "\n", | ||
| "The following request illustrates a tool call that retrieves the HTTP headers from the [HttpContext] using the [IHttpContextAccessor].\n", | ||
| "\n", | ||
| "The server implements two other tools, `get_request_info` and `get_user_claims`. You can modify the code below to call these tools as well,\n", | ||
| "which illustrate how to access other parts of the [HttpContext].\n", | ||
| "\n", | ||
| "\n", | ||
| "[HttpContext]: https://docs.microsoft.com/dotnet/api/microsoft.aspnetcore.http.httpcontext\n", | ||
| "[IHttpContextAccessor]: https://docs.microsoft.com/dotnet/api/microsoft.aspnetcore.http.ihttpcontextaccessor" | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "code", | ||
| "execution_count": 4, | ||
| "id": "3324ec56", | ||
| "metadata": { | ||
| "language_info": { | ||
| "name": "polyglot-notebook" | ||
| }, | ||
| "polyglot_notebook": { | ||
| "kernelName": "pwsh" | ||
| } | ||
| }, | ||
| "outputs": [ | ||
| { | ||
| "name": "stdout", | ||
| "output_type": "stream", | ||
| "text": [ | ||
| "{\n", | ||
| " \"result\": {\n", | ||
| " \"content\": [\n", | ||
| " {\n", | ||
| " \"type\": \"text\",\n", | ||
| " \"text\": \"[]\"\n", | ||
| " }\n", | ||
| " ],\n", | ||
| " \"structuredContent\": {\n", | ||
| " \"result\": []\n", | ||
| " }\n", | ||
| " },\n", | ||
| " \"id\": 1,\n", | ||
| " \"jsonrpc\": \"2.0\"\n", | ||
| "}\n" | ||
| ] | ||
| } | ||
| ], | ||
| "source": [ | ||
| "curl -s -X POST http://localhost:3001 `\n", | ||
| "-H \"ProtocolVersion: 2025-06-18\" `\n", | ||
| "-H \"Accept: application/json, text/event-stream\" `\n", | ||
| "-H \"Content-Type: application/json\" `\n", | ||
| "-d '{\n", | ||
| " \"jsonrpc\": \"2.0\",\n", | ||
| " \"id\": 1,\n", | ||
| " \"method\": \"tools/call\",\n", | ||
| " \"params\": {\n", | ||
| " \"name\": \"get_user_claims\"\n", | ||
| " }\n", | ||
| "}' | Where-Object { $_ -like \"data:*\" } | ForEach-Object { $_.Substring(5) } | jq" | ||
| ] | ||
| } | ||
| ], | ||
| "metadata": { | ||
| "kernelspec": { | ||
| "display_name": ".NET (C#)", | ||
| "language": "C#", | ||
| "name": ".net-csharp" | ||
| }, | ||
| "language_info": { | ||
| "name": "polyglot-notebook" | ||
| }, | ||
| "polyglot_notebook": { | ||
| "kernelInfo": { | ||
| "defaultKernelName": "csharp", | ||
| "items": [ | ||
| { | ||
| "aliases": [], | ||
| "languageName": "csharp", | ||
| "name": "csharp" | ||
| } | ||
| ] | ||
| } | ||
| } | ||
| }, | ||
| "nbformat": 4, | ||
| "nbformat_minor": 5 | ||
| } |
8 changes: 8 additions & 0 deletions
8
docs/concepts/httpcontext/samples/appsettings.Development.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| { | ||
| "Logging": { | ||
| "LogLevel": { | ||
| "Default": "Information", | ||
| "Microsoft.AspNetCore": "Warning" | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| { | ||
| "Logging": { | ||
| "LogLevel": { | ||
| "Default": "Information", | ||
| "Microsoft.AspNetCore": "Warning" | ||
| } | ||
| }, | ||
| "AllowedHosts": "*" | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.