Hmz.Core.Mcp 0.1.3

dotnet add package Hmz.Core.Mcp --version 0.1.3
                    
NuGet\Install-Package Hmz.Core.Mcp -Version 0.1.3
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Hmz.Core.Mcp" Version="0.1.3" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Hmz.Core.Mcp" Version="0.1.3" />
                    
Directory.Packages.props
<PackageReference Include="Hmz.Core.Mcp" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Hmz.Core.Mcp --version 0.1.3
                    
#r "nuget: Hmz.Core.Mcp, 0.1.3"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Hmz.Core.Mcp@0.1.3
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Hmz.Core.Mcp&version=0.1.3
                    
Install as a Cake Addin
#tool nuget:?package=Hmz.Core.Mcp&version=0.1.3
                    
Install as a Cake Tool

Hmz.Core.Mcp

Exposes the Minimal API endpoints of an Hmz backend as permission-filtered MCP tools. Each tool call is re-dispatched as an HTTP request through the application's own pipeline (loopback) with the caller's own Authorization header, so every rule that already guards the endpoint (authentication, RequirePermission, resource policies, brand context, If-Match, ProblemDetails mapping) applies unchanged. The MCP route adds no second authorization path.

The package is opt-in. It depends on ModelContextProtocol.AspNetCore 2.4.x and Hmz.Core.SharedKernel (it reads PermissionRuleMetadata).

Wiring

builder.Services.AddOpenApi();
builder.Services.AddHmzMcpServer(builder.Configuration.GetSection("Mcp"));

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapHmzMcp("/mcp");   // maps nothing while Mcp:Enabled is false

MapHmzMcp maps the Streamable HTTP route, stateless, with RequireSignedInUser() (RequireAuthorization() plus the declaration EndpointAccess.FindUndeclared looks for; the app's default policy and scheme) and hides it from the API description. Call it after UseAuthorization. The OpenAPI document (AddOpenApi) is required: the tools are built from the endpoint metadata plus the operation of that document, matched by operation id (= endpoint name, so every tool endpoint needs WithName).

API versioning

With Asp.Versioning.OpenApi (AddApiVersioning().AddOpenApi()) the documents are named after the version groups (GroupNameFormat, "'v'V" gives v1; the default VVV gives 1.0); set Mcp:OpenApiDocumentNames to them (["v1"] is the default, ["v1", "v2"] reads both). The documents are read through the framework's build-time IDocumentProvider, so no document endpoint has to be mapped and no shim is needed; with a plain AddOpenApi("v1") the keyed document provider is used as before. A route parameter with the apiVersion constraint (/api/v{version:apiVersion}/products) is not an argument: its value comes from the document path of the operation (/api/v1/products), and an operation that several documents carry uses the first configured one. If no document is found, the error lists the registered names.

Options (Mcp section)

Option Default Meaning
Enabled false false: the MCP route is not mapped
Writes None None: only read-only tools are listed and callable; Selected: also the mutating tools marked AllowMcpWrite() or named in WriteTools; All: every mutating tool
WriteTools empty Tool or endpoint names (case-insensitive) of the mutating tools exposed when Writes=Selected
WritePermission null Permission code that MCP writes additionally require; mutating tools are hidden from callers without it and refused with mcp.write_forbidden (see Write access)
IncludeTags empty Allow-list of OpenAPI tags; empty exposes no tool
ExcludeTools empty Tool names or endpoint names that are not ready
Mode Direct Direct, Discovery or Direct, Discovery
ReadOnlyPostSuffix /search A POST whose route ends with it is read-only; empty turns it off
MaxSchemaBytes 16384 Cap of one tool's input plus output schema; above it the tool is discovery-only
HeaderArguments empty Optional arguments sent as request headers of the dispatched call, for request scopes (see Header arguments); modules can also contribute them in code
OpenApiDocumentNames ["v1"] OpenAPI documents to read, one per API version
LoopbackBaseAddress null Base address of the loopback call; null: first address of the server
ToolHeaderName App-Mcp-Tool Header that carries the tool name on the dispatched request
MaxResponseBytes 1048576 Larger responses become a tool error
CallTimeout 00:00:30 Time limit of one dispatched call

Options are validated at startup. A host that must not expose MCP in an environment leaves Mcp:Enabled at false (the default).

Header arguments

An application that reads a request scope from a header (brand, tenant, workspace, region) lets a caller choose it per tool call. Every tool then offers the argument, and the value is sent in the header of the dispatched call. The scope is the application's concept, so the module that owns it contributes the argument, the way each module contributes its permissions:

public sealed class TenantHeaderArgumentSource : IMcpHeaderArgumentSource
{
    public string Source => "Tenancy";

    public IReadOnlyList<McpHeaderArgument> Arguments { get; } =
        [new() { Name = "tenantId", HeaderName = TenantHeaders.TenantId, Description = "Tenant to act in." }];
}

services.AddSingleton<IMcpHeaderArgumentSource, TenantHeaderArgumentSource>();

The same arguments can be configured instead, with no code:

"Mcp": {
  "HeaderArguments": [
    { "Name": "tenantId", "HeaderName": "App-Tenant-Id" },
    { "Name": "workspaceId", "HeaderName": "App-Workspace-Id", "ForwardIncoming": false, "Description": "Workspace to act in." }
  ]
}
  • A value is a non-empty string or an integer (schema type: ["string", "integer"]); an integer keeps its JSON text. Anything else (boolean, object, list, decimal, empty string, control characters) is an mcp.invalid_arguments error and nothing is dispatched: an explicit but unusable scope never falls back to another one.
  • Absent or null: the same header of the MCP request is forwarded (ForwardIncoming, default true), or nothing is sent.
  • The server reads Mcp:HeaderArguments and every registered source once per host.
  • Startup validation rejects invalid names and headers, duplicates across configuration and sources (naming both), the reserved names body and ifMatch, and headers the server sets itself (Authorization, If-Match, trace context, ToolHeaderName). A route or query parameter with a header argument's name makes that endpoint unmapped.
  • The header still has to be authorized by the endpoint: the argument only chooses the scope the application then checks for the caller, as for a direct HTTP call.

Endpoint metadata

group.MapPost("legacy", ...).ExcludeFromMcp("Replaced by SearchProducts.");
group.MapGet("x", ...).WithMcpTool(name: "my_tool", description: "Text", readOnly: true);
group.MapPost("lookup", ...).AsMcpReadOnly();   // POST that only reads
group.MapPut("{id}", ...).AllowMcpWrite();      // mutating tool exposed when Writes=Selected

Tools

  • Name: the endpoint name in snake_case (SearchCatalogProducts becomes search_catalog_products), or WithMcpTool(name).
  • Description: OpenAPI summary and description plus the access line of SharedKernel EndpointAccess.Describe (Access: Requires permission <rule>., Access: Any signed-in user; ...), added once even when EndpointAccessOperationTransformer already wrote it. With WritePermission, a mutating tool's access line continues with MCP writes also require permission X. (or reads Access: MCP writes require permission X. when the endpoint declares none).
  • _meta["hmz.core/access"] (tools/list) and access (describe_operation): the structured McpToolAccessInfo { rule?, permissions[], signedInOnly, writePermission?, description? }, built from the permission requirements and PermissionRuleMetadata of the endpoint (several rules are joined with and), so a client can decide before it calls.
  • Input: { <path params>, <query params>, <header arguments>?, ifMatch?, body? }, closed (additionalProperties: false). ifMatch exists only where the operation documents an If-Match header (RequiresStrongIfMatch / RequiresOpaqueIfMatch). Header arguments (such as brandId or tenantId) exist only when configured; see Header arguments. Component schemas are copied into the tool's own $defs. Path values are escaped (a catch-all keeps its /) and the segments . and .. are refused, so a call always reaches its own endpoint.
  • Output schema: { status, etag?, body } around the 200/201 JSON schema.
  • McpToolDescriptor (from McpToolCatalog) is public for guard tests: Name, EndpointName, HttpMethod, Route, ReadOnly, Access, WriteOptIn (a mutating tool marked AllowMcpWrite() or named in WriteTools), AcceptsIfMatch and Endpoint (the RouteEndpoint, with its metadata). The policies stay internal.
  • Annotations: GET and read-only POST are readOnlyHint; DELETE is destructiveHint; PUT is idempotentHint; none is open-world. While Writes=None (or, with Selected, without opt-in), tools that are not read-only are neither listed nor callable.
  • tools/list evaluates each endpoint's combined policy (IAuthorizeData plus AuthorizationPolicy metadata) for the caller with IAuthorizationService, so a caller sees only what the policy lets them use. The dispatched call checks again.

Results

  • 2xx: structuredContent { status, etag?, body } and a short text block. A 304 is not an error.
  • Any other status: IsError = true with { status, code, title, detail?, errors?, traceId? } read from the ProblemDetails body (code is the ProblemDetails code extension, or http.<status>). An API failure is never a JSON-RPC error.
  • Argument and dispatch problems are tool errors with mcp.* codes: mcp.invalid_arguments, mcp.loop_guard, mcp.timeout, mcp.dispatch_failed, mcp.response_too_large, and mcp.write_forbidden (403, the caller lacks WritePermission). An unknown, filtered or write-while-Writes=None tool is the JSON-RPC error Unknown tool.

Automatic exclusions

Each is recorded with a reason: anonymous endpoints, ExcludeFromDescription, multipart or form bodies, file or stream responses, a policy that names a scheme other than the default one (for example ApiKey), endpoints under the MCP route, and ExcludeFromMcp(reason).

Write access

Recommended setup for an app that lets AI clients change data:

  1. Every endpoint declares its own permission (RequirePermission("CM.PRODUCT.UPDATE")); the dispatched call enforces it as for any client.
  2. Mcp:Writes = Selected and AllowMcpWrite() on the few mutating endpoints an agent may use (or name them in Mcp:WriteTools). Everything else stays read-only.
  3. Mcp:WritePermission (for example MCP.TOOLS.WRITE) so that writing through an AI is a permission of its own, granted per user. The check goes through the app's own PermissionAuthorizationHandler (AddPermissionAuthorization() and an IPermissionChecker) in the MCP request scope; with no handler registered the requirement cannot succeed and every write is denied.
  4. Concurrency stays with the API: read the resource (get_x returns etag), then call the write tool with ifMatch set to that ETag. A stale tag comes back as the API's 412 tool error.

Tools the host adds

Tools registered with WithTools<T>() next to the catalog pass the same gate. A host tool is read-only only when it declares [McpServerTool(ReadOnly = true)] (readOnlyHint); any other is write-capable: exposed only as Writes/WriteTools allow (by its tool name), and with WritePermission hidden from tools/list and refused with mcp.write_forbidden for a caller without it. The SDK shapes a host tool's result: a primitive return value comes back as a text block without structuredContent; return a JSON-serializable object (with UseStructuredContent) when a client should get structured output like the catalog tools' envelope.

Modes

  • Direct: one tool per endpoint. A client narrows the list with /mcp?tags=a,b (inside the IncludeTags allow-list).
  • Discovery: three tools, search_operations(query, limit?), describe_operation(name) and call_operation(name, arguments), over the same permission-filtered catalog. A tool above MaxSchemaBytes is reachable only here.

Dispatcher

IEndpointDispatcher sends the request. The default LoopbackEndpointDispatcher calls the host's own address with the named HttpClient LoopbackEndpointDispatcher.HttpClientName, forwards Authorization, the brand header, If-Match and traceparent, and adds App-Mcp-Tool: <name>. It never dispatches to the MCP route (McpRoute guard, also applied before any replacement dispatcher is called). Register your own IEndpointDispatcher (or configure the named client's primary handler) to change it; tests route it to a TestServer handler.

Coverage test

McpToolCatalog builds the catalog once, lazily. One assertion keeps an application honest: every endpoint is a tool or is excluded with a reason.

var snapshot = await app.Services.GetRequiredService<McpToolCatalog>().GetAsync();
snapshot.Unmapped.Should().BeEmpty(snapshot.DescribeUnmapped());

snapshot.Entries lists every endpoint with its disposition and reason; snapshot.Excluded lists the exclusions.

Logging and telemetry

One [LoggerMessage] per call (tool, endpoint name, status, duration); arguments, bodies and tokens are never logged. Activities of the source Hmz.Core.Mcp (McpTelemetry.ActivitySourceName) start only when a listener exists.

Not included (yet)

RFC 9728 protected-resource metadata for interactive OAuth clients, and upload or download tools.

Product 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on Hmz.Core.Mcp:

Package Downloads
Hmz.Core.Testing.Mcp

Functional-test client for Hmz.Core.Mcp hosts: connect over Streamable HTTP to a test server, list tools, call a tool and read the dispatched status, ETag, body and error code.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.1.3 47 11/21/2026
0.1.1 55 11/17/2026
0.1.0 52 11/16/2026