麦克。AspNetCore。多主机
在单个ASP中使用不同的工具集和配置托管多个MCP(模型上下文协议)服务器。NET核心应用程序。
特性
- 多个MCP主机:在单个应用程序中运行多个隔离的MCP服务器
- 每主机DI容器:每个主机都有自己的隔离依赖注入容器
- 服务桥接:与MCP主机共享主应用程序的服务
- 灵活的配置:使用不同的工具、提示和资源独立配置每个主机
- 发现端点:列出所有可用MCP主机的可选端点
- 安全助手:跨原产地保护的原产地验证
安装
dotnet add package Mcp.AspNetCore.MultiHost快速开始
var builder = WebApplication.CreateBuilder(args);
// Register MCP hosts
builder.Services.AddMcpMultiHost(options =>
{
options.AddHost("admin", host =>
{
host.WithRoutePrefix("/mcp/admin")
.ConfigureMcpServer(mcp => mcp
.WithHttpTransport()
.WithTools());
});
options.AddHost("user", host =>
{
host.WithRoutePrefix("/mcp/user")
.ConfigureMcpServer(mcp => mcp
.WithHttpTransport()
.WithTools());
});
});
var app = builder.Build();
// Map all MCP hosts
app.MapMcpMultiHost();
app.Run();配置
主机配置
每个主机都使用fluent builder API进行配置:
options.AddHost("myhost", host =>
{
// Required: Set the route prefix
host.WithRoutePrefix("/mcp/myhost");
// Required: Configure MCP server
host.ConfigureMcpServer(mcp => mcp
.WithHttpTransport()
.WithTools()
.WithPrompts());
// Optional: Add host-specific services
host.ConfigureHostServices(services =>
{
services.AddSingleton();
});
// Optional: Configure endpoint conventions
host.ConfigureEndpoints(endpoints =>
{
endpoints.RequireAuthorization("AdminPolicy");
});
// Optional: Custom service bridging
host.BridgeServices(bridge =>
{
bridge.ForwardAspNetCoreDefaults();
bridge.ForwardSingleton();
});
});发现端点
启用发现端点以列出所有可用的MCP主机:
app.MapMcpMultiHost(options =>
{
options.MapDiscoveryEndpoint = true;
options.DiscoveryEndpointPath = "/mcp/_hosts"; // default
});响应格式:
{
"hosts": [
{ "name": "admin", "routePrefix": "/mcp/admin" },
{ "name": "user", "routePrefix": "/mcp/user" }
]
}服务桥接
默认情况下,以下ASP。NET Core服务会自动桥接到每个主机:
ILoggerFactory(与ILogger支持)IConfigurationIHostEnvironmentIHostApplicationLifetimeIHttpContextAccessor(如果已注册)
自定义桥接
覆盖默认桥接行为:
host.BridgeServices(bridge =>
{
// Include ASP.NET Core defaults
bridge.ForwardAspNetCoreDefaults();
// Forward additional singletons
bridge.ForwardSingleton();
// Forward with factory
bridge.Forward(sp => sp.GetRequiredService());
});安全
原产地验证
保护MCP端点免受未经授权的跨源请求:
host.ConfigureEndpoints(endpoints =>
{
endpoints.RequireSameOriginOrAllowed("https://trusted.example.com");
});此筛选器:
- 允许没有Origin标头的请求(非浏览器客户端)
- 允许同源请求
- 允许明确列出的来源
- 使用403 Forbidden阻止所有其他跨源请求
授权
应用ASP。NET Core对MCP端点的授权:
host.ConfigureEndpoints(endpoints =>
{
endpoints.RequireAuthorization("MyPolicy");
});访问注册表
注入 IMcpHostRegistry 在运行时访问已注册的主机:
app.MapGet("/admin/hosts", (IMcpHostRegistry registry) =>
{
return registry.Hosts.Select(h => new { h.Name, h.RoutePrefix });
});需求
- .NET 8.0或更高版本
- 模型上下文协议。AspNetCore 0.8.0-评测.1或更高版本
建筑
每个MCP主机都与其自己的主机隔离运行:
- DI容器
- 服务注册
- 工具定义
- 提示模板
服务可以通过桥接从主应用程序共享,但每个主机都维护自己的特定于主机的服务实例。
Main Application
|
+--------------+--------------+
| | |
[Host A] [Host B] [Host C]
/mcp/a /mcp/b /mcp/c
| | |
Tools A Tools B Tools C许可证
麻省理工学院
贡献
欢迎投稿!请打开问题或提交拉取请求。
