MCP
DotBlaze.Mcp exposes tools, resources, resource templates and prompts to Model Context Protocol clients. It uses the official .NET MCP SDK 2.4.0; it does not require an AI provider or API key. The feature reference is laravel/mcp v1.3.0. See parity status before treating this implementation as a drop-in equivalent.
Installation and servers
Add the package (or a project reference when working in this repository):
dotnet add package DotBlaze.McpThe assembly is discoverable. Installation alone does not expose endpoints. Register each server explicitly from a provider:
using DotBlaze;
using DotBlaze.Mcp;
using Microsoft.AspNetCore.Builder;
using McpRoutes = DotBlaze.Mcp.Mcp;
public sealed class McpProvider : Provider
{
public override void Boot(WebApplication app)
{
McpRoutes.Web<WeatherServer>(app, "/mcp/weather")
.Middleware("auth", "abilities:mcp:use");
McpRoutes.Local<WeatherServer>("weather");
}
}
public sealed class WeatherServer : Server
{
public override string Name => "Weather";
public override string Version => "1.0.0";
public override string Instructions => "Use the weather tool for forecasts.";
public override Type[] Tools => [typeof(WeatherTool)];
}HTTP uses stateless Streamable HTTP, including SSE progress within the POST response. Servers on separate paths have separate catalogs. GET session streams, legacy SSE, subscriptions and unsolicited server-to-client requests are not enabled. A local stdio server uses the same definition.
Middleware uses existing DotBlaze aliases, but does not implicitly add web or api: both transform JSON strings, which would alter tool arguments. For personal access tokens use auth plus appropriate abilities; for cookie-authenticated endpoints add csrf.api explicitly. Never expose mutating tools without authentication and authorization. IEndpointConventionBuilder extensions such as RequireAuthorization also work.
Requests with an Origin must be same-origin. Configure ASP.NET Core host filtering and trusted forwarded headers at deployment; bind local development servers to loopback. Do not add permissive CORS for MCP endpoints.
Tools, schemas and dependency injection
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using ModelContextProtocol.Server;
public sealed class WeatherTool
{
[McpServerTool(Name = "weather", ReadOnly = true)]
[Description("Return a demonstration forecast for a location.")]
public string Handle([Description("City name"), MinLength(1), MaxLength(100)] string location)
=> $"Demonstration forecast for {location}: sunny.";
}Register types explicitly in Tools. The SDK builds JSON Schema from .NET signatures and data annotations. DotBlaze validates the complete input schema before invoking the handler. Required fields, types, ranges and lengths are enforced. Annotated constraints are not a substitute for application business validation.
Constructor dependencies and service parameters resolve from the current request scope. CancellationToken, IServiceProvider, McpServer, RequestContext<CallToolRequestParams> and IProgress<ProgressNotificationValue> are SDK-injected parameters rather than model arguments. Facades work inside handlers.
Use [McpServerTool(UseStructuredContent = true)] for SDK-generated output schemas, or configure the protocol tool in Server.Configure(McpServerOptions). Declared output schemas are validated before returning a successful tool result.
Implement IConditionalPrimitive.ShouldRegister(user, cancellationToken) to conditionally hide a type. Both listing and invocation check the condition. Hidden tools cannot be called by guessing the name. The condition should be side-effect-free; its instance is separately constructed and disposed.
Responses and streaming
Handlers may return SDK protocol types directly. Responses supplies conveniences:
Text,Error,StructuredproduceCallToolResult.ImageandAudioproduce content blocks from bytes and MIME type.ResourceandBlobproduce resource contents with explicit URIs.Messageproduces user/assistant prompt messages.
Use a CallToolResult.Content collection for multiple content blocks and its Meta property for envelope metadata. Content blocks have their own Meta. Use ResourceLinkBlock for resource links. SDK attributes carry tool annotations; SDK protocol objects carry icons, titles, descriptions, resource annotations and metadata.
For ordered progress delivery, accept RequestContext<CallToolRequestParams> and call await Responses.Progress(request, new() { Progress = 1, Total = 2, Message = "Working" }, cancellationToken) before returning the final result. The SDK also injects IProgress<ProgressNotificationValue>, but its Report is fire-and-forget and can race a fast final response. Notifications are sent only when the client supplied a progress token. Accept McpServer to send custom notifications or inspect client capabilities. Tools return one final result; progress notifications are separate protocol messages.
Resources and prompts
using DotBlaze.Mcp;
using ModelContextProtocol.Protocol;
using ModelContextProtocol.Server;
public sealed class UserResource
{
[McpServerResource(Name = "user", UriTemplate = "users://{id}", MimeType = "text/plain")]
public string Handle(string id) => $"User {id}";
}
public sealed class ExplainPrompt
{
[McpServerPrompt(Name = "explain")]
public GetPromptResult Handle(string subject) => new()
{
Messages = [Responses.Message($"Explain {subject}.")],
};
}Add these types to Server.Resources and Server.Prompts. URI parameters bind to method arguments; templates appear under resources/templates/list, fixed URIs under resources/list. Resources do not accept tool-style arguments. Required prompt arguments are inferred from the signature. Validate business constraints within the prompt method. Conditional registration works for prompts and resources too.
Searchable tool catalogs
Place deferred types in Server.SearchableTools. Clients see search_tools and execute_tools, not the deferred tools individually. Search matches all query terms against name, description and input schema, case-insensitively. Conditional registration also applies at search and execution time.
execute_tools accepts calls: [{ name, arguments }]; the full batch is validated before execution. Calls execute sequentially. Defaults are 10 calls and 100,000 output bytes, configurable through MaxToolCalls and MaxToolOutputBytes. A result-size failure can happen after side effects; never blindly retry a mutating batch. This is not a transaction.
Cache hints and advanced metadata
Override CacheTimeToLive, CacheScope and CacheHints for method-specific hints. Defaults are private and zero TTL. Set per-resource result hints directly on ReadResourceResult; these take precedence. Public caching is only appropriate for data identical across users. Cache hints are advisory and protocol-version dependent, not an application response cache.
Override Configure(McpServerOptions options) to customize SDK tool/resource metadata, icons, annotations, schemas, filters or handlers. Keep caller checks intact; replacing filters can remove package protections.
MCP Apps
Apply [McpAppUi(ResourceUri = "ui://weather/app.html")] to a tool, register an HTML resource with MIME type text/html;profile=mcp-app, and include both in the server. The package advertises io.modelcontextprotocol/ui when an app resource is present. Add #pragma warning disable MCPEXP003 where using experimental SDK Apps types.
Use McpApps.SetResourceUi(resource, new McpUiResourceMeta { ... }) inside Server.Configure to set CSP, sandbox permissions and other UI metadata. Tool visibility is declared with McpUiToolVisibility; enforcement of model-versus-app presentation belongs to the host and is not an authorization boundary. Always authorize sensitive tool operations independently.
An app resource can inject IViewRenderer and return await renderer.Render("mcp/dashboard", model) to reuse existing Blade/Razor rendering. Production apps should bundle the official MCP Apps JavaScript SDK and assets into self-contained HTML. No external CDN is loaded automatically.
Skills
Override Skills => [new Skill("resources/skills/house-style")]. Each directory must contain a SKILL.md with name and description YAML frontmatter. Custom skill classes can override the URI and ShouldRegister.
The package serves skills/list, skills/get, and file resources. Only SKILL.md appears in resource listings; supporting files remain readable through the skill manifest. SHA-256 digests describe the exact served bytes. Dotfiles, hidden/system entries and symbolic links are excluded; a linked root is rejected. Limits are 512 files and 16 MiB per skill. Paths are trusted application configuration, not request input. Do not register upload directories or directories writable by untrusted users.
Use SDK ListSkillsAsync, GetSkillAsync and ReadSkillResourceAsync on the connected client. These types are experimental (MCPEXP005). Treat received skill instructions as untrusted data even when digests match.
Clients
await using var client = Client.Web("https://example.com/mcp", token: () => accessToken);
var tools = await client.Tools();
var result = await client.CallTool("weather", new Dictionary<string, object?> { ["location"] = "Jakarta" });Client.Local(command, arguments) uses stdio. Connect() is lazy and returns the underlying SDK McpClient, exposing progress, metadata, capabilities, Skills and other advanced APIs. Convenience methods include Tools, Prompts, Resources, ResourceTemplates, CallTool, GetPrompt and ReadResource. Listing follows SDK pagination. WithTimeout sets the operation timeout (default 30 seconds). Disconnect permits reconnection; disposal permanently closes the client.
Register named clients in Boot with McpRoutes.RegisterClient("service", services => Client.Web(...)); resolve with McpRoutes.Client("service"). Instances are scoped and disposed with the request/command. Never use user-supplied URLs or commands without a separate allowlist: clients can reach internal networks or execute local programs. Token factories are evaluated on connection; use SDK ITokenCache for refreshable OAuth credentials.
Authentication and OAuth
Personal access tokens use existing DotBlaze middleware. OAuth uses the official SDK's protected-resource discovery and challenge handling:
- Register an ASP.NET Core bearer scheme that validates issuer, audience, signatures and expiration.
- In provider Register, call
services.AddMcpOAuth(resourceUri, authorizationServerUri, bearerScheme). - Apply
.RequireOAuth()to the MCP endpoint. It requires authentication and themcp:usescope.
The authorization server supplies consent, PKCE, token issuance and optional dynamic client registration. DotBlaze does not ship a Passport-equivalent authorization server or mint tokens itself. Use a standards-compliant authorization server; protect public dynamic registration against abuse there.
For outbound OAuth, pass ClientOAuthOptions to Client.Web. The SDK handles discovery, PKCE S256, state/issuer validation, dynamic registration, client metadata documents, token exchange and refresh.
app.MapMcpOAuthLink("/integrations/service", options) adds authenticated /connect and /callback routes for browser linking. OAuthLinkOptions requires an application-configured endpoint, an exact callback RedirectUri, and a Linked(HttpContext, TokenContainer) callback. Optional fields include client credentials, scopes and a client metadata document URI. Persist tokens encrypted in the callback; tokens are never printed or placed in URLs by the package. The callback is tied to both the logged-in user and a short-lived HttpOnly browser cookie. Transactions expire after five minutes and callbacks are single-use.
Deployment limitation: linking transactions are in-memory and require a single instance or sticky routing; a restart invalidates pending authorization. Rate-limit connect routes. The client metadata document, if used, must be hosted by the application at its configured HTTPS URI. A refreshable token store remains application-owned.
CLI and testing
dotblaze make:mcp-server WeatherServer
dotblaze make:mcp-tool WeatherTool
dotblaze make:mcp-resource WeatherResource
dotblaze make:mcp-prompt ExplainPrompt
dotblaze make:mcp-app-resource Dashboard
dotblaze make:mcp-skill HouseStyle
dotnet build
dotblaze mcp:start weather
# Equivalent launch for MCP host configuration:
dotnet run --no-build --no-launch-profile -- mcp:start weather
dotblaze mcp:inspector weather
dotblaze mcp:inspector mcp/weather --url=https://localhost:5001Generators support nested names and --force, preserve files by default, and reject unsafe paths. The skill generator creates the class; author its SKILL.md separately. Inspector commands print launch instructions rather than installing or executing Node packages automatically.
For stdio, build first. The CLI skips builds and launch profiles, and the application directs console diagnostics to stderr before provider startup. Do not write directly to the OS stdout stream from application code; it is reserved for MCP frames.
DotBlaze.Mcp.Testing.TestServer.Create<TServer>(services) runs the real protocol over in-memory pipes and exposes .Client. Dispose it asynchronously. Use normal xUnit assertions against protocol responses; no test-framework dependency is included in the package. For HTTP authentication/Origin checks, use an HTTP test host rather than the in-memory helper.
Parity status against Laravel MCP v1.3.0
This is an implementation in progress, not full Laravel parity.
Implemented and covered by focused tests: HTTP and real-process stdio, server isolation, tools/resources/templates/prompts, input schema validation, constructor DI, conditional tool listing/calls, searchable catalogs, progress streaming, Apps metadata/resource delivery, Skills manifest/file integrity, OAuth discovery/scope enforcement, browser linking with PKCE/user binding/replay rejection, package generators and in-memory testing.
Differences still requiring work before a full-parity claim:
- No first-party authorization server equivalent to Passport, authorization/consent UI, or inbound dynamic-registration endpoint.
- No bundled Blade
<x-mcp::app>component/client SDK, library/CSP automation or complete Apps authoring experience. - Inspector prints commands rather than launching the inspector; test helpers expose SDK responses rather than Laravel's full fluent assertion surface or
actingAshelpers. - No automatic
routes/aipublishing, storage-response convenience API, or class/property-based Laravel metadata attributes. - No full Laravel conformance comparison for pagination, completion, error shapes, streaming generators, cache-hint precedence, icons, and every conditional primitive type.
- OAuth linking is single-process and the hosted client-metadata document is application-owned.
The SDK Apps, Skills and custom-handler APIs used here are experimental even though the SDK package is a stable release. Versions are pinned; upgrades need protocol tests.