D4S.Mcp.Server
1.0.0
dotnet add package D4S.Mcp.Server --version 1.0.0
NuGet\Install-Package D4S.Mcp.Server -Version 1.0.0
<PackageReference Include="D4S.Mcp.Server" Version="1.0.0" />
<PackageVersion Include="D4S.Mcp.Server" Version="1.0.0" />
<PackageReference Include="D4S.Mcp.Server" />
paket add D4S.Mcp.Server --version 1.0.0
#r "nuget: D4S.Mcp.Server, 1.0.0"
#:package D4S.Mcp.Server@1.0.0
#addin nuget:?package=D4S.Mcp.Server&version=1.0.0
#tool nuget:?package=D4S.Mcp.Server&version=1.0.0
D4S.Mcp.Server
Opt-in Entra authentication and caller authorization for stateless .NET 10 MCP HTTP servers. The authenticated application and the version-1 user context asserted by that application are separate identities.
Package placement
Install D4S.Mcp.Server in the ASP.NET Core application that hosts MCP tools. It is a separate
NuGet package and has no dependency on D4S.Agent, Foundry, or application-specific services.
D4S.Agent stays in the bot: its HTTP MCP client obtains the application token and, when enabled,
adds the current user's context headers. The server package validates both before a tool runs.
Bot (D4S.Agent) -- HTTPS + application token + user context --> MCP host (D4S.Mcp.Server)
|
Application tools
In the bot, configure the MCP URL, its API scope and UserContext.Enabled=true when the server
requires a person. In the MCP host, configure the token audience, allowed applications and user
tenants as shown below. These are independent applications with independent dependency graphs.
Knowledge Retrieval and SQL Query reference this shared project when building their container
images; running such an image requires no separate NuGet installation.
Trust boundary
Protected requests pass JWT validation, application authorization, and user-context header validation before MCP dispatch. The application token identifies the caller, not the person in the headers. An authorized caller is trusted to assert that person's context. This is not delegated authentication/ OBO, proof of Teams provenance, or a Graph user lookup. Application roles, document ACLs, business tools, confirmations and durable workflows belong to the consumer.
The initial profile supports .NET 10, public-cloud Entra, one issuer tenant per deployment, RS256-signed v2.0 app-only access tokens, and stateless Streamable HTTP. No cookie, query-token, platform-header, API-key, v1-token or interactive OAuth fallback is provided.
Minimal host
using D4S.Mcp.Server;
using ModelContextProtocol.AspNetCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddD4SMcpServerSecurity(
builder.Configuration.GetSection(McpServerSecurityOptions.SectionName));
builder.Services.AddMcpServer()
.WithHttpTransport(o => o.SessionMode = HttpServerSessionMode.Stateless)
.AddAuthorizationFilters()
.WithTools<MyTools>();
var app = builder.Build();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseD4SMcpRequestContext();
app.MapD4SMcp("/mcp");
app.Run();
Use the protected mapping; do not add an unprotected MapMcp alias. Missing/misordered context
middleware fails closed with 500 before dispatch. AllowAnonymous conventions cannot bypass the
middleware's explicit bearer/caller checks. MapD4SMcp() also supports the root endpoint.
Companion HTTP endpoints can reuse the boundary without becoming model tools:
app.MapPost("/internal/action", (IMcpRequestContextAccessor accessor) =>
{
var person = accessor.Current!.GetRequiredUser();
// Derive attribution from person.UserObjectId and person.TenantId.
return Results.Accepted();
}).RequireD4SMcpSecurity();
Other routes are not protected automatically. Keep health/readiness separate, minimal, and free of identity/options/diagnostics. The sample's readiness reports startup configuration, not a real token.
Configuration
{
"AllowedHosts": "<exact-server-hostname>",
"McpServerSecurity": {
"Enabled": true,
"TenantId": "<entra-tenant-guid>",
"Audience": "<api-application-client-guid>",
"AllowedCallers": [
{
"ClientId": "<caller-managed-identity-client-guid>",
"ServicePrincipalObjectId": "<caller-managed-identity-principal-guid>"
}
],
"UserContext": {
"Required": true,
"AllowedTenantIds": [ "<user-context-tenant-guid>" ]
}
}
}
Enabled defaults to false. Protected mappings require true; there is no Development bypass. Existing servers conditionally register/map the component only when enabled. Invalid enabled options fail startup. Options are copied into an immutable process-level snapshot; changes require restart/revision. Caller entries must have unique client/principal IDs and match as a pair, not independent sets.
UserContext.Required defaults to false. Six absent headers mean User=null. Any header present requires the complete valid context, even in optional mode. AllowedTenantIds must be explicit/nonempty when context is required and to accept any supplied context. Caller tenant never substitutes user tenant.
Entra prerequisites
- Register a single-tenant API resource with
api.requestedAccessTokenVersion=2and the optional access-token claimidtypon that resource. The server needs no client secret for validation. - Audience is the API application/client GUID, the expected v2 aud. The caller requests the API
scope, for example
api://<api-client-id>/.default; this scope is not the Audience setting. - Record each allowed caller's client ID and service-principal object ID. The server's MI used downstream is a different identity and does not grant ingress access to the caller.
- Check tenant token-issuance/assignment policies. This package uses a caller ACL and does not create roles, assignments, permissions or Azure RBAC grants. Tenant assignment requirements are additional deployment prerequisites, not privileges supplied by this component.
JwtBearer/IdentityModel checks signature, exact issuer/audience, exp and nbf using tenant-specific HTTPS metadata and standard key rollover/caching. Clock skew is 60 seconds. The token must have ver=2.0 and the configured tid. Authorization also requires idtyp=app, no scp, and the allowed (azp, oid) pair. Ambiguous claims and duplicate critical JSON fields are rejected. No instant revocation of an already-issued bearer is promised. ClaimsPrincipal injected by MCP remains the application; its roles must never be interpreted as roles of the asserted person.
Versioned user-context contract and tool access
Names are case-insensitive; each present header must have exactly one value. Repeated physical lines, identical duplicates and comma-concatenated values are rejected. Proxies must preserve or reject duplicates; an application cannot reconstruct duplicates silently removed upstream.
| Header | Validation |
|---|---|
| X-D4S-User-Context-Version | Exactly 1. |
| X-D4S-User-Object-Id | Nonempty GUID, 36-character D input; uppercase accepted; Guid formats canonically as lowercase D. |
| X-D4S-Tenant-Id | Same GUID rules; included in AllowedTenantIds; no fallback. |
| X-D4S-Conversation-Id-B64Url | Required nonblank strict UTF-8/canonical unpadded Base64url; 1,024 decoded bytes / 1,366 encoded characters maximum. |
| X-D4S-Channel-Id | Channel[:SubChannel], nonempty components using ASCII letters/digits/./-/_; 128 characters total maximum. |
| X-D4S-User-Name-B64Url | Optional strict UTF-8/Base64url; 256 decoded bytes / 342 encoded characters maximum. Missing/empty/blank name becomes null after validation. |
No trimming, truncation or Unicode normalization. Padding, classic Base64 characters, whitespace in encoded text, noncanonical pad bits, invalid UTF-8, U+0000-U+001F and U+007F-U+009F, CR/LF and U+2028/U+2029 are rejected. Extra headers never become roles or identity fields. The agent client derives these headers from the authenticated turn, including the documented Teams tenant fallback.
[McpServerToolType]
public sealed class MyTools
{
[McpServerTool]
public static object Execute(IMcpRequestContextAccessor accessor, string documentId)
{
var context = accessor.Current
?? throw new InvalidOperationException("No protected request context.");
var person = context.GetRequiredUser();
// context.Caller is the authenticated application; person is its asserted user.
return new { accepted = true };
}
}
The accessor is injected by DI and absent from the tool schema; JSON arguments cannot replace it. Caller/User properties are read-only and ToString omits their values. Current is cleared in finally, including failure/cancellation; concurrent requests and child execution contexts cannot inherit an ended request's identity. Background work must copy only needed values into its persistent command.
Transport, errors and logs
Only stateless HTTP is supported. Stateful/hybrid sessions, legacy SSE and per-session execution contexts fail startup validation. Each request is checked independently. Mcp-Session-Id is rejected and never authenticates anyone. POST responses can stream SSE without legacy /sse or /message. GET/DELETE session operations are unavailable in SDK 2.2.0 stateless mode. Unsupported routes/methods remain 404/405 and cannot dispatch tools.
| Failure | HTTP result |
|---|---|
| Missing/invalid bearer, signature/issuer/audience/time/version/tenant | 401, generic Bearer challenge |
| Excluded/non-app-only caller or disallowed user tenant | 403 |
| Required context missing, partial/invalid/duplicate/unknown-version context | 400, fixed invalid_mcp_user_context code |
| Session header | 400, fixed mcp_sessions_not_supported code |
| Origin header present | 403; browser cross-origin access is outside this profile |
| Context middleware missing/misordered | 500, no dispatch |
Oversized headers may receive 431 from the host. No fallback to a previous person or anonymous/key authentication. Missing trusted signing keys grants no access; cached valid keys may remain usable during metadata outages according to the Microsoft stack.
The dedicated bearer handler uses a fixed-message diagnostic sink because JwtBearer can log exception artifacts before its events run. Registration also filters Microsoft.AspNetCore.Hosting.Diagnostics below Warning for the host: automatic start/end logs include raw query strings even when query credentials are rejected. Other auth schemes retain their logging. Do not override these filters, enable IdentityModel PII logging, or log request headers/bodies containing bearer tokens or user-context values. Configure proxy/ingress/telemetry separately; the package cannot sanitize external logs or arbitrary tool logs.
Deployment, compatibility and release
Use external HTTPS ingress with allowInsecure=false, unchanged Authorization forwarding and HTTPS metadata/JWKS egress. Restrict accepted hosts and trust only actual proxies; forwarded headers alone do not prove TLS. Do not expose the container HTTP port directly. Easy Auth can be an additional layer, but its injected identity headers are not credentials for this component.
Knowledge Retrieval and SQL Query adopt Entra only through Enabled=true. Defaults preserve their old paths. SQL API key and Entra cannot be enabled together; change both settings in one migration revision. Existing tool schemas and Foundry/client credential behavior are unchanged. All Dockerfiles use src/MCP as build context; its .dockerignore excludes local/environment-specific settings and keys.
See tests and sample.
Local real-SDK/synthetic-signature tests do not certify Entra emission, MI permissions, Container Apps
configuration or Teams provenance. Remote validation needs a separately approved environment/plan.
Published on nuget.org by infra/azure-pipelines-mcp-server.yml (1.0.<run> from main). Smoke packs
use 1.0.0-smoke.<timestamp>; infra/azure-pipelines-mcp-hosting.yml verifies the hosting stack and its
consumers and keeps a candidate package as a pipeline artifact only.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 10.0.12)
- ModelContextProtocol.AspNetCore (>= 2.2.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 1.0.0 | 110 | 11/20/2026 |