-
Notifications
You must be signed in to change notification settings - Fork 308
Add ModelContextProtocol.AspNetCore #160
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
Merged
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
f660bb8
Add ModelContextProtocol.AspNetCore
halter73 dfd1674
Update src/ModelContextProtocol.AspNetCore/ModelContextProtocol.AspNe…
halter73 90ee329
Update src/ModelContextProtocol.AspNetCore/ModelContextProtocol.AspNe…
eiriktsarpalis 3bfc535
Update src/ModelContextProtocol.AspNetCore/README.md
eiriktsarpalis 713890d
Merge branch 'main' into aspnet
eiriktsarpalis 228cfa1
Address PR feedback
halter73 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
62 changes: 0 additions & 62 deletions
62
samples/AspNetCoreSseServer/McpEndpointRouteBuilderExtensions.cs
This file was deleted.
Oops, something went wrong.
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 |
---|---|---|
@@ -1,10 +1,9 @@ | ||
using AspNetCoreSseServer; | ||
using ModelContextProtocol.AspNetCore; | ||
|
||
var builder = WebApplication.CreateBuilder(args); | ||
builder.Services.AddMcpServer().WithToolsFromAssembly(); | ||
var app = builder.Build(); | ||
|
||
app.MapGet("/", () => "Hello World!"); | ||
app.MapMcpSse(); | ||
app.MapMcp(); | ||
|
||
app.Run(); |
108 changes: 108 additions & 0 deletions
108
src/ModelContextProtocol.AspNetCore/McpEndpointRouteBuilderExtensions.cs
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,108 @@ | ||
using Microsoft.AspNetCore.Builder; | ||
using Microsoft.AspNetCore.Http; | ||
using Microsoft.AspNetCore.Routing; | ||
using Microsoft.AspNetCore.WebUtilities; | ||
using Microsoft.Extensions.DependencyInjection; | ||
using Microsoft.Extensions.Logging; | ||
using Microsoft.Extensions.Options; | ||
using ModelContextProtocol.Protocol.Messages; | ||
using ModelContextProtocol.Protocol.Transport; | ||
using ModelContextProtocol.Server; | ||
using ModelContextProtocol.Utils.Json; | ||
using System.Collections.Concurrent; | ||
using System.Security.Cryptography; | ||
|
||
namespace ModelContextProtocol.AspNetCore; | ||
|
||
/// <summary> | ||
/// Extension methods for <see cref="IEndpointRouteBuilder"/> to add MCP endpoints. | ||
/// </summary> | ||
public static class McpEndpointRouteBuilderExtensions | ||
{ | ||
/// <summary> | ||
/// Sets up endpoints for handling MCP "HTTP with SSE" transport. | ||
/// </summary> | ||
/// <param name="endpoints">The web application to attach MCP HTTP endpoints.</param> | ||
/// <param name="onSessionAsync">Provides an optional asynchronous callback for handling new MCP sessions.</param> | ||
/// <returns>Returns a builder for configuring additional endpoint conventions like authorization policies.</returns> | ||
public static IEndpointConventionBuilder MapMcp(this IEndpointRouteBuilder endpoints, Func<HttpContext, IMcpServer, Task>? onSessionAsync = null) | ||
{ | ||
ConcurrentDictionary<string, SseResponseStreamTransport> _sessions = new(StringComparer.Ordinal); | ||
|
||
var loggerFactory = endpoints.ServiceProvider.GetRequiredService<ILoggerFactory>(); | ||
var mcpServerOptions = endpoints.ServiceProvider.GetRequiredService<IOptions<McpServerOptions>>(); | ||
|
||
var routeGroup = endpoints.MapGroup(""); | ||
|
||
routeGroup.MapGet("/sse", async context => | ||
{ | ||
var response = context.Response; | ||
var requestAborted = context.RequestAborted; | ||
|
||
response.Headers.ContentType = "text/event-stream"; | ||
response.Headers.CacheControl = "no-cache"; | ||
|
||
var sessionId = MakeNewSessionId(); | ||
await using var transport = new SseResponseStreamTransport(response.Body, $"/message?sessionId={sessionId}"); | ||
eiriktsarpalis marked this conversation as resolved.
Show resolved
Hide resolved
|
||
await using var server = McpServerFactory.Create(transport, mcpServerOptions.Value, loggerFactory, endpoints.ServiceProvider); | ||
_sessions.TryAdd(sessionId, transport); | ||
halter73 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
try | ||
{ | ||
var transportTask = transport.RunAsync(cancellationToken: requestAborted); | ||
var serverTask = server.RunAsync(cancellationToken: requestAborted); | ||
if (onSessionAsync is not null) | ||
{ | ||
await onSessionAsync(context, server); | ||
} | ||
await serverTask; | ||
await transportTask; | ||
halter73 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
catch (OperationCanceledException) when (requestAborted.IsCancellationRequested) | ||
{ | ||
// RequestAborted always triggers when the client disconnects before a complete response body is written, | ||
// but this is how SSE connections are typically closed. | ||
halter73 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
finally | ||
{ | ||
_sessions.TryRemove(sessionId, out _); | ||
} | ||
}); | ||
|
||
routeGroup.MapPost("/message", async context => | ||
{ | ||
if (!context.Request.Query.TryGetValue("sessionId", out var sessionId)) | ||
{ | ||
await Results.BadRequest("Missing sessionId query parameter.").ExecuteAsync(context); | ||
return; | ||
} | ||
|
||
if (!_sessions.TryGetValue(sessionId.ToString(), out var transport)) | ||
halter73 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
await Results.BadRequest($"Session {sessionId} not found.").ExecuteAsync(context); | ||
return; | ||
} | ||
|
||
var message = await context.Request.ReadFromJsonAsync<IJsonRpcMessage>(McpJsonUtilities.DefaultOptions, context.RequestAborted); | ||
if (message is null) | ||
{ | ||
await Results.BadRequest("No message in request body.").ExecuteAsync(context); | ||
return; | ||
} | ||
|
||
await transport.OnMessageReceivedAsync(message, context.RequestAborted); | ||
context.Response.StatusCode = StatusCodes.Status202Accepted; | ||
await context.Response.WriteAsync("Accepted"); | ||
}); | ||
|
||
return routeGroup; | ||
} | ||
|
||
private static string MakeNewSessionId() | ||
{ | ||
// 128 bits | ||
Span<byte> buffer = stackalloc byte[16]; | ||
eiriktsarpalis marked this conversation as resolved.
Show resolved
Hide resolved
|
||
RandomNumberGenerator.Fill(buffer); | ||
return WebEncoders.Base64UrlEncode(buffer); | ||
} | ||
} |
22 changes: 22 additions & 0 deletions
22
src/ModelContextProtocol.AspNetCore/ModelContextProtocol.AspNetCore.csproj
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,22 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>net8.0</TargetFramework> | ||
<ImplicitUsings>enable</ImplicitUsings> | ||
<Nullable>enable</Nullable> | ||
<GenerateDocumentationFile>true</GenerateDocumentationFile> | ||
<IsPackable>true</IsPackable> | ||
<PackageId>ModelContextProtocol.AspNetCore</PackageId> | ||
jeffhandley marked this conversation as resolved.
Show resolved
Hide resolved
|
||
<Description>ASP.NET Core extensions for the C# Model Context Protocol (MCP) SDK.</Description> | ||
<PackageReadmeFile>README.md</PackageReadmeFile> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<FrameworkReference Include="Microsoft.AspNetCore.App" /> | ||
</ItemGroup> | ||
|
||
eiriktsarpalis marked this conversation as resolved.
Show resolved
Hide resolved
|
||
<ItemGroup> | ||
<ProjectReference Include="..\ModelContextProtocol\ModelContextProtocol.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,54 @@ | ||
# MCP C# ASP.NET Core SDK | ||
eiriktsarpalis marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
[](https://www.nuget.org/packages/ModelContextProtocol/absoluteLatest) | ||
eiriktsarpalis marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
The official C# SDK for the [Model Context Protocol](https://modelcontextprotocol.io/), enabling .NET applications, services, and libraries to implement and interact with MCP clients and servers. Please visit our [API documentation](https://modelcontextprotocol.github.io/csharp-sdk/api/ModelContextProtocol.html) for more details on available functionality. | ||
|
||
> [!NOTE] | ||
> This project is in preview; breaking changes can be introduced without prior notice. | ||
|
||
## About MCP | ||
|
||
The Model Context Protocol (MCP) is an open protocol that standardizes how applications provide context to Large Language Models (LLMs). It enables secure integration between LLMs and various data sources and tools. | ||
|
||
For more information about MCP: | ||
|
||
- [Official Documentation](https://modelcontextprotocol.io/) | ||
- [Protocol Specification](https://spec.modelcontextprotocol.io/) | ||
- [GitHub Organization](https://github.com/modelcontextprotocol) | ||
|
||
## Installation | ||
|
||
To get started, install the package from NuGet | ||
|
||
``` | ||
dotnet new web | ||
dotnet add package ModelContextProtocol.AspNetcore --prerelease | ||
``` | ||
|
||
## Getting Started | ||
halter73 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
```csharp | ||
// Program.cs | ||
using ModelContextProtocol; | ||
using ModelContextProtocol.AspNetCore; | ||
|
||
var builder = WebApplication.CreateBuilder(args); | ||
builder.WebHost.ConfigureKestrel(options => | ||
{ | ||
options.ListenLocalhost(3001); | ||
}); | ||
builder.Services.AddMcpServer().WithToolsFromAssembly(); | ||
var app = builder.Build(); | ||
|
||
app.MapMcp(); | ||
|
||
app.Run(); | ||
|
||
[McpServerToolType] | ||
public static class EchoTool | ||
{ | ||
[McpServerTool, Description("Echoes the message back to the client.")] | ||
public static string Echo(string message) => $"hello {message}"; | ||
} | ||
``` |
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.
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.