Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,14 @@
<PackageVersion Include="Microsoft.AspNetCore.DataProtection.EntityFrameworkCore" Version="10.0.14" />
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
<!-- Background jobs. Keep each BackWave package at the same version. -->
<PackageVersion Include="BackWave" Version="1.7.0" />
<PackageVersion Include="BackWave.Dashboard" Version="1.7.0" />
<PackageVersion Include="BackWave.Hosting" Version="1.7.0" />
<PackageVersion Include="BackWave.OpenTelemetry" Version="1.7.0" />
<PackageVersion Include="BackWave.Postgres" Version="1.7.0" />
<PackageVersion Include="BackWave.Testing" Version="1.7.0" />
<PackageVersion Include="BackWave" Version="1.9.0" />
<PackageVersion Include="BackWave.Dashboard" Version="1.9.0" />
<PackageVersion Include="BackWave.Hosting" Version="1.9.0" />
<PackageVersion Include="BackWave.OpenTelemetry" Version="1.9.0" />
<PackageVersion Include="BackWave.Postgres" Version="1.9.0" />
<PackageVersion Include="BackWave.Pro" Version="1.9.0" />
<PackageVersion Include="BackWave.Pro.Mcp" Version="1.9.0" />
<PackageVersion Include="BackWave.Testing" Version="1.9.0" />
<!-- Distributed Locking -->
<PackageVersion Include="DistributedLock.Postgres" Version="1.2.1" />
<!-- API Versioning -->
Expand Down
2 changes: 2 additions & 0 deletions FullstackTemplate.Server/FullstackTemplate.Server.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@
<PackageReference Include="BackWave.Hosting" />
<PackageReference Include="BackWave.OpenTelemetry" />
<PackageReference Include="BackWave.Postgres" />
<PackageReference Include="BackWave.Pro" />
<PackageReference Include="BackWave.Pro.Mcp" />
<PackageReference Include="DistributedLock.Postgres" />
<PackageReference Include="EFCore.NamingConventions" />
<PackageReference Include="FluentValidation" />
Expand Down
3 changes: 2 additions & 1 deletion FullstackTemplate.Server/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using FullstackTemplate.Server.Resources;
using FullstackTemplate.Server.Resources.Entrypoints;
using FullstackTemplate.Server.Resources.Entrypoints.Http.OpenApi;
using FullstackTemplate.Server.Resources.Entrypoints.Jobs;
using FullstackTemplate.Server.Resources.Extensions;
using Serilog;
using Serilog.Events;
Expand All @@ -25,7 +26,7 @@
var role = ServerRoles.From(builder.Configuration);

builder.AddServiceDefaults(); // OpenTelemetry, Serilog, health checks, resilience, service discovery
builder.ConfigureServices(role);
builder.ConfigureServices(role, role.ServesRequests() ? JobsMcp.Configure : null);
if (role.ServesRequests())
builder.AddEntrypoints();
builder.Services.AddHostedService<MigrationHostedService>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,15 +44,21 @@ public static void AddEntrypoints(this WebApplicationBuilder builder)
// HttpContext, the caller, and the tenant scope are the ones of that request.
builder.Services.AddMcpServer()
.WithHttpTransport(options => options.Stateless = true)
.WithToolsFromAssembly(typeof(EntrypointRegistration).Assembly)
.WithRequestFilters(filters =>
{
filters.AddListToolsFilter(McpToolAccess.ListFilter);
// The first call filter is the outermost, so a denial of the access filter becomes a tool error.
filters.AddCallToolFilter(McpCallTelemetry.Filter);
filters.AddCallToolFilter(McpDomainErrors.Filter);
filters.AddCallToolFilter(McpToolAccess.CallFilter);
});
.WithToolsFromAssembly(typeof(EntrypointRegistration).Assembly);
builder.Services.Configure<McpServerOptions>(options =>
{
// AddMcp of BackWave (JobsMcp) names the whole server BackWave. With no name, the SDK gives the name and
// version of the app.
options.ServerInfo = null;
// The first filter is the outermost. AddMcp of BackWave also adds filters, so the filters of the app go
// before them: each call gets the telemetry and the tool errors of the app, and a denial of the access
// filter becomes a permission_denied tool error.
var filters = options.Filters.Request;
filters.ListToolsFilters.Insert(0, McpToolAccess.ListFilter);
filters.CallToolFilters.Insert(0, McpToolAccess.CallFilter);
filters.CallToolFilters.Insert(0, McpDomainErrors.Filter);
filters.CallToolFilters.Insert(0, McpCallTelemetry.Filter);
});
// ReadFrom.Services in HostExtensions adds each ILogEventFilter of the services to the logger
builder.Services.AddSingleton<ILogEventFilter, McpProtocolErrorLogFilter>();

Expand Down
37 changes: 37 additions & 0 deletions FullstackTemplate.Server/Resources/Entrypoints/Jobs/JobsMcp.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
namespace FullstackTemplate.Server.Resources.Entrypoints.Jobs;

using BackWave.Pro.Mcp;
using Domain.Users;

/// <summary>
/// The BackWave tools on the MCP endpoint of the app. <see cref="Mcp.McpToolAccess"/> shows them only to a caller
/// that manages all tenants, because they see the jobs of all tenants.
/// </summary>
public static class JobsMcp
{
/// <summary>Sets the gates of BackWave.</summary>
public static void Configure(BackWaveProMcpOptions options)
{
// The view gate of BackWave covers the whole MCP server, also the tools of the app, so it allows each request.
// McpToolAccess gates the BackWave tools.
options.AuthorizeView = _ => ValueTask.FromResult(true);
options.AuthorizeRequeue = ManagesAllTenantsAsync;
options.AuthorizeCancel = ManagesAllTenantsAsync;
// AuthorizePauseQueue, AuthorizeTriggerSchedule, and AuthorizeSetConcurrencyLimit keep the default deny. A pause
// or a low concurrency limit holds the jobs of all tenants, and each run of the one schedule, the sweep of the
// bucket, lists the whole bucket.
// AuthorizeViewSensitiveData keeps the default deny, so that no payload or output goes into the context of a
// model. The message of the exception that failed a job is not gated.
options.ResolveActor = context =>
context.RequestServices.GetRequiredService<ICallerIdentityResolver>().Current switch
{
CallerIdentity.AllTenantsClient { CanManage: true, ClientId: var clientId } => $"client:{clientId}",
_ => throw new InvalidOperationException(
"A BackWave write on MCP passed the check with no client that manages all tenants."),
};
}

private static async ValueTask<bool> ManagesAllTenantsAsync(HttpContext context)
=> (await context.RequestServices.GetRequiredService<IPermissionGuard>().GetCallerAsync(context.RequestAborted))
.ManagesAllTenants;
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
namespace FullstackTemplate.Server.Resources.Entrypoints.Mcp;

using System.Reflection;
using BackWave.Pro.Mcp;
using Domain.Users;
using Exceptions;
using ModelContextProtocol.Protocol;
Expand All @@ -11,6 +13,8 @@ namespace FullstackTemplate.Server.Resources.Entrypoints.Mcp;
/// </summary>
public static class McpToolAccess
{
private static readonly Assembly BackWaveToolAssembly = typeof(BackWaveProMcpOptions).Assembly;

/// <summary>Hides each tool that the caller cannot use. It loads the caller once for the list.</summary>
public static McpRequestHandler<ListToolsRequestParams, ListToolsResult> ListFilter(
McpRequestHandler<ListToolsRequestParams, ListToolsResult> next) =>
Expand Down Expand Up @@ -51,7 +55,7 @@ public static McpRequestHandler<CallToolRequestParams, CallToolResult> CallFilte

/// <summary>
/// Stops startup when a tool has no <see cref="ToolAccessAttribute"/>, a kind that is not defined, or a permission
/// that does not exist.
/// that does not exist. A tool of BackWave needs no attribute.
/// </summary>
/// <exception cref="InvalidOperationException">A tool has no valid declaration. The message names each one.</exception>
public static void Validate(IEnumerable<McpServerTool> tools)
Expand All @@ -72,6 +76,8 @@ public static void Validate(IEnumerable<McpServerTool> tools)
=> new ToolRequirement.Needs(Permission.Of(permission)),
{ Kind: ToolAccessKind.Read } => new ToolRequirement.Read(),
{ Kind: ToolAccessKind.ManageAllTenants } => new ToolRequirement.ManageAllTenants(),
null when tool.Metadata.OfType<MethodInfo>().FirstOrDefault()?.DeclaringType?.Assembly == BackWaveToolAssembly
=> new ToolRequirement.ManageAllTenants(),
_ => null,
};

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
namespace FullstackTemplate.Server.Resources.Extensions;

using System.Diagnostics;
using BackWave.Pro.Mcp;
using Databases;
using Databases.DataProtection;
using Domain.Attachments;
Expand All @@ -16,12 +17,15 @@ namespace FullstackTemplate.Server.Resources.Extensions;
public static class WebAppServiceConfiguration
{
/// <summary>
/// Adds the core services: the database, the Data Protection key ring, the background jobs, the email sender, the domain event handlers, MediatR, the caches, and the tenant scope. It adds no transport.
/// Adds the core services: the database, the Data Protection key ring, the background jobs, the email sender, the domain event handlers, MediatR, the caches, and the tenant scope.
/// The integration tests call only this method. <c>AddEntrypoints</c> adds HTTP, gRPC, and MCP.
/// The core has no caller until <c>AddEntrypoints</c> replaces <see cref="NoPrincipalAccessor"/>. The worker groups
/// that run the jobs are added only when the <paramref name="role"/> runs jobs.
/// that run the jobs are added only when the <paramref name="role"/> runs jobs. The one transport that it can add is
/// the BackWave tools of MCP, because BackWave registers them in its own block. <c>Program</c> gives
/// <paramref name="jobsMcp"/>, the gates of the entrypoint, only to a process that serves requests.
/// </summary>
public static void ConfigureServices(this WebApplicationBuilder builder, ServerRole role)
public static void ConfigureServices(this WebApplicationBuilder builder, ServerRole role,
Action<BackWaveProMcpOptions>? jobsMcp = null)
{
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddFusionCache()
Expand Down Expand Up @@ -71,7 +75,7 @@ public static void ConfigureServices(this WebApplicationBuilder builder, ServerR
});
builder.EnrichNpgsqlDbContext<AppDbContext>();
builder.AddDataProtectionKeyRing();
builder.Services.AddBackgroundJobs(builder.Configuration, role);
builder.Services.AddBackgroundJobs(builder.Configuration, role, jobsMcp);
builder.Services.AddSingleton<IEmailSender, LogEmailSender>();

builder.Services.AddDomainEvents(typeof(Program).Assembly);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ namespace FullstackTemplate.Server.Resources.Jobs;

using BackWave.Generated;
using BackWave.Hosting;
using BackWave.Pro;
using BackWave.Pro.Mcp;
using Databases;
using Domain.ObjectDeletes;
using Extensions;
Expand All @@ -14,13 +16,14 @@ public static class BackgroundJobsRegistration
/// handlers, the client, the monitor, the writer of the jobs that a save queues, the scope of a job attempt, and the
/// operators of the jobs dashboard.
/// When the <paramref name="role"/> runs jobs, it also adds one worker group for each queue, and their check in
/// <c>/health</c>.
/// <c>/health</c>. With <paramref name="jobsMcp"/>, it also adds the BackWave tools to the MCP server, with the gates
/// that <paramref name="jobsMcp"/> sets.
/// </summary>
/// <exception cref="InvalidOperationException">
/// A setting of <see cref="ObjectDeleteOptions"/> or <see cref="ObjectSweepOptions"/> is out of its range.
/// </exception>
public static IServiceCollection AddBackgroundJobs(this IServiceCollection services, IConfiguration configuration,
ServerRole role)
ServerRole role, Action<BackWaveProMcpOptions>? jobsMcp = null)
{
var deletes = ObjectDeleteOptions.From(configuration);
services.AddSingleton(Options.Create(deletes));
Expand All @@ -36,10 +39,15 @@ public static IServiceCollection AddBackgroundJobs(this IServiceCollection servi
foreach (var group in JobGroups.For(BackWaveJobs.Module, deletes))
backWave.AddWorkerGroup(group);
}
if (jobsMcp is not null)
backWave.AddMcp(jobsMcp);
});
// A worker group that stops on a fault of the store makes the Server unhealthy, so that a person sees it
if (role.RunsJobs())
services.AddHealthChecks().AddCheck<BackWaveHealthCheck>("backwave");
// Only the jobs tools of MCP use BackWave Pro, so a process without them does not take on its license
if (jobsMcp is not null)
services.AddBackWavePro(configuration["BackWave:ProLicense"]);
services.AddSingleton<IJobWriter, JobWriter>();
services.AddScoped<JobScope>();
services.Configure<BackgroundJobsOptions>(configuration.GetSection(BackgroundJobsOptions.SectionName));
Expand Down
13 changes: 13 additions & 0 deletions docs/backend/background-jobs.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,19 @@ The BackWave dashboard is at `/backwave` of the app. The BFF sends the page to t

Only a process that serves requests serves the dashboard. The metrics panel of the dashboard shows the jobs that the process of the page ran, not the jobs of all processes. An Api process runs no job, so its panel shows no job metrics. For a deploy with more than one process, read the `backwave.*` metrics in the telemetry backend.

## The jobs tools on MCP

BackWave Pro adds its MCP tools to the MCP server of the app, so an agent reads and acts on the jobs at `/mcp`. `JobsMcp` sets which tools are on. See [MCP](endpoints.md#mcp).

- Only a client that can manage all tenants sees and calls the tools, because they show the jobs of all tenants. The dashboard is for operators, and an operator is never an agent.
- An agent can read the jobs, the queues, the schedules, the workflows, and the audit records, requeue a job, and cancel a job or a workflow.
- The tools refuse a pause of a queue, a trigger of a schedule, and a change of a concurrency limit, for the same reasons as the dashboard. A low concurrency limit holds the jobs of all tenants, as a pause does.
- The tools do not give the payload, the output, or the stack of a failure of a job, so that no secret or personal data goes into the context of a model. They do give the message of the exception that failed a job, so a job handler must not put personal data in an exception message.
- The audit record of a requeue or a cancel names the client, for example `client:my-ops-agent`.
- Only a process that serves requests adds the tools.

`BackWave:ProLicense` holds the license key of BackWave Pro. Only a process that adds the jobs tools of MCP adds BackWave Pro, so a Worker process and the integration tests run without it. BackWave Pro is free for a company with less than $1M of annual revenue. Above that, buy a license and set the key. The tests run with no key.

## Telemetry

- Each attempt is a trace of its own. Its root is the `process {queue}` span of BackWave. The span links to the `send {queue}` span of the save that queued the job, which has the `code.*` tags of the `QueueJob` call.
Expand Down
9 changes: 9 additions & 0 deletions docs/backend/endpoints.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,15 @@ The attribute repeats the permission of the handler. If the two differ, the resu
In the workshop example, `list_workshops` is a read tool ([`GetWorkshopListTool`](../../FullstackTemplate.Server/Examples/Workshops/Features/GetWorkshopList/GetWorkshopList.Mcp.cs)), and `cancel_workshop` names the permission of its handler ([`CancelWorkshopTool`](../../FullstackTemplate.Server/Examples/Workshops/Features/CancelWorkshop/CancelWorkshop.Mcp.cs)).
<!-- example:end -->

### The BackWave tools

`AddMcp` of BackWave Pro adds the tools of the jobs to the same MCP server, so they are on `/mcp` too. There is one MCP server for each process. `AddMcp` must be in the one `AddBackWave` block of the core, so `Program` gives `JobsMcp.Configure` to `ConfigureServices`, only for a process that serves requests. See [The jobs tools on MCP](background-jobs.md#the-jobs-tools-on-mcp).

- The BackWave tools have no `[ToolAccess]`. `McpToolAccess` gives each tool of the `BackWave.Pro.Mcp` assembly the rule of `ToolAccessKind.ManageAllTenants`, so only a client that can manage all tenants sees and calls them. A tool of another assembly with no `[ToolAccess]` still stops startup.
- BackWave has its own gates in `JobsMcp`. The view gate of BackWave covers the whole server, also the tools of the app, so it allows each request. The requeue and cancel gates also ask for a caller that can manage all tenants. The gates of a pause, a trigger of a schedule, a concurrency limit, and the payload and output of a job deny each request, so these tools are not in `tools/list`.
- BackWave adds its own filters. `AddEntrypoints` puts the filters of the app before them, so that each call to a BackWave tool gets the telemetry and the tool errors of the app.
- `AddMcp` names the server `BackWave`. `AddEntrypoints` removes the name, so the server keeps the name and the version of the app.

### MCP versions

MCP has no version segment. The contract of a tool is its name and its input schema.
Expand Down
Loading
Loading