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
<PackageReference Include="Hmz.Core.Mcp" Version="0.1.3" />
<PackageVersion Include="Hmz.Core.Mcp" Version="0.1.3" />
<PackageReference Include="Hmz.Core.Mcp" />
paket add Hmz.Core.Mcp --version 0.1.3
#r "nuget: Hmz.Core.Mcp, 0.1.3"
#:package Hmz.Core.Mcp@0.1.3
#addin nuget:?package=Hmz.Core.Mcp&version=0.1.3
#tool nuget:?package=Hmz.Core.Mcp&version=0.1.3
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 anmcp.invalid_argumentserror 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, defaulttrue), or nothing is sent. - The server reads
Mcp:HeaderArgumentsand every registered source once per host. - Startup validation rejects invalid names and headers, duplicates across configuration and
sources (naming both), the reserved names
bodyandifMatch, 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 (
SearchCatalogProductsbecomessearch_catalog_products), orWithMcpTool(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 whenEndpointAccessOperationTransformeralready wrote it. WithWritePermission, a mutating tool's access line continues withMCP writes also require permission X.(or readsAccess: MCP writes require permission X.when the endpoint declares none). _meta["hmz.core/access"](tools/list) andaccess(describe_operation): the structuredMcpToolAccessInfo{ rule?, permissions[], signedInOnly, writePermission?, description? }, built from the permission requirements andPermissionRuleMetadataof the endpoint (several rules are joined withand), so a client can decide before it calls.- Input:
{ <path params>, <query params>, <header arguments>?, ifMatch?, body? }, closed (additionalProperties: false).ifMatchexists only where the operation documents anIf-Matchheader (RequiresStrongIfMatch/RequiresOpaqueIfMatch). Header arguments (such asbrandIdortenantId) 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(fromMcpToolCatalog) is public for guard tests:Name,EndpointName,HttpMethod,Route,ReadOnly,Access,WriteOptIn(a mutating tool markedAllowMcpWrite()or named inWriteTools),AcceptsIfMatchandEndpoint(theRouteEndpoint, with its metadata). The policies stay internal.- Annotations: GET and read-only POST are
readOnlyHint; DELETE isdestructiveHint; PUT isidempotentHint; none is open-world. WhileWrites=None(or, withSelected, without opt-in), tools that are not read-only are neither listed nor callable. tools/listevaluates each endpoint's combined policy (IAuthorizeDataplusAuthorizationPolicymetadata) for the caller withIAuthorizationService, 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 = truewith{ status, code, title, detail?, errors?, traceId? }read from the ProblemDetails body (codeis the ProblemDetailscodeextension, orhttp.<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, andmcp.write_forbidden(403, the caller lacksWritePermission). An unknown, filtered or write-while-Writes=Nonetool is the JSON-RPC errorUnknown 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:
- Every endpoint declares its own permission (
RequirePermission("CM.PRODUCT.UPDATE")); the dispatched call enforces it as for any client. Mcp:Writes = SelectedandAllowMcpWrite()on the few mutating endpoints an agent may use (or name them inMcp:WriteTools). Everything else stays read-only.Mcp:WritePermission(for exampleMCP.TOOLS.WRITE) so that writing through an AI is a permission of its own, granted per user. The check goes through the app's ownPermissionAuthorizationHandler(AddPermissionAuthorization()and anIPermissionChecker) in the MCP request scope; with no handler registered the requirement cannot succeed and every write is denied.- Concurrency stays with the API: read the resource (
get_xreturnsetag), then call the write tool withifMatchset to that ETag. A stale tag comes back as the API's412tool 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 theIncludeTagsallow-list).Discovery: three tools,search_operations(query, limit?),describe_operation(name)andcall_operation(name, arguments), over the same permission-filtered catalog. A tool aboveMaxSchemaBytesis 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 | 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
- Hmz.Core.SharedKernel (>= 0.1.21)
- Microsoft.AspNetCore.OpenApi (>= 10.0.11)
- Microsoft.OpenApi (>= 2.12.2)
- ModelContextProtocol.AspNetCore (>= 2.4.0)
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.