Skip to content

Cross-application MCP server ​

CritterWatch ships a Model Context Protocol server (CritterWatch.Mcp) that lets AI agents query and operate the distributed system through the same data plane the SPA reads from. One MCP endpoint covers every monitored Wolverine / Marten / Polecat / Fisher service — the aggregator is CritterWatch itself.

This page covers the cross-application server. Per-application MCP servers (Marten.Mcp, Polecat.Mcp, WolverineFx.Mcp) ship in their own NuGet packages and expose store / runtime details inside a single service; this page is about the CritterWatch-level surface that spans all of them.

Commercial license required

The entire MCP surface is a paid-tier feature. Every MCP tool is license-gated — including the read/diagnostic tools — so there is no free MCP tier. Without a valid commercial license, every tool returns a "license missing" envelope. (Read-only monitoring through the SPA, by contrast, is always free.)

Looking for "how do I connect"?

If you're on the consumer side — pointing Claude Desktop, MCP Inspector, or a custom MCP agent at a running BFF — see MCP Quick Start for the connection examples, the discovery flow, the deny envelope, and tenant-scoped invocations. This page is the server-side reference.

What's mounted ​

The BFF mounts the MCP server at /api/mcp (the CritterWatchMcpExtensions.DefaultRoute constant). Clients connect over streamable HTTP; no SSE fallback is required.

POST http://your-critterwatch-host/api/mcp

For multi-package composition (CritterWatch tools alongside per-store tools), see Composition below.

Tool catalog ​

Read tools ​

Always license-gated. RBAC-free except the reads that return business data: the dead-letter reads, the projection tools, the event query, the SQL query, the document reads, the conversation reads and the saga reads, which are gated on mcp.dlq.read / mcp.projection.step / mcp.events.query / mcp.sql.query / mcp.documents.read / mcp.conversations.read / mcp.sagas.read — see below. preview_high_water_advance is a read too; it is listed with the high water mark advance under Action tools because it shares that tool's capability.

FamilyToolsCapability
Alertslist_active_alerts, get_alert, summarize_active_alerts—
Healthsummarize_cluster_health, get_service_health, list_degraded_surfaces—
Performanceget_backlog_state, list_backlog_hotspots, get_projection_lag, list_shard_health—
OpenTelemetry tracesquery_recent_traces, get_trace, check_trace_provider_health—
Conversationslist_conversations, get_conversationmcp.conversations.read
Sagaslist_sagas, list_saga_instances, get_saga_instancemcp.sagas.read
Message routingget_message_routing, list_message_routing, explain_message_routing—
Document explorerlist_document_types, query_documents, get_documentmcp.documents.read (the last two; every call audited)
Lifecycledescribe_lifecycle—
Dead letterssummarize_dead_letters, summarize_dead_letter_groups, query_dead_lettersmcp.dlq.read
Projectionsdiagnose_projection, run_projection_stepper, get_projection_apply_sourcemcp.projection.step
Event queryquery_eventsmcp.events.query
SQL queryquery_sqlmcp.sql.query (every call audited)
Scheduled messagesquery_scheduled_messages—
Recurring scheduleslist_recurring_schedules—
High water detectionlist_high_water_loops—
Tenantslist_tenants—
Stream compactionlist_compaction_policies, get_compaction_activity—
Command outcomesget_command_outcome—

Dead-letter reads ​

summarize_dead_letters gives grouped counts by message type and exception type — the triage view. query_dead_letters returns individual envelopes including their ids, which are exactly what replay_dead_letters / discard_dead_letters take. Together they close the investigate → explain → replay loop that the action tools alone could not: before these existed an agent had no way to discover an envelope id short of a human pasting it out of the console.

  • A group is one endpoint. Each summarize_dead_letters group carries its receivedAt — the endpoint the messages were received at, not a time — as well as its database, message type and exception type, and query_dead_letters takes receivedAt as a filter beside messageType, exceptionType and the from / to window, so an agent can pull exactly the envelopes one group counted.
  • from and to are when the dead letter failed (1.2). That holds on all three reads and on the group actions below, so an action touches what the read counted. An answer carries rangedOn. A service on a Wolverine.CritterWatch client older than 1.2 can only range on the sent time: it answers with rangedOn: SentAt (per service in summarize_dead_letter_groups) and summarize_dead_letters and query_dead_letters add a rangeNote saying so. Do not report such a read as "failed in that window". query_dead_letters returns failedAt beside sentAt, newest failure first.
  • Failure groups (1.1). summarize_dead_letter_groups groups dead letters by FailureGroup (the default: the same exception thrown from the same place), MessageType, Endpoint or ExceptionType, across one service or, with no serviceName, the whole fleet, merged by the console across every database and service. Each group has a key; pass a failure group's key to query_dead_letters' failureGroup to pull its envelopes. Groups with predatesFingerprinting are grouped by exception type: dead letters recorded before Wolverine 6.54, or a service on a Wolverine.CritterWatch client older than 1.1 (supportsGroups: false). For such a service query_dead_letters turns an exception-type group's key into an exception-type filter, and refuses a real fingerprint rather than return every dead letter. Check partial as with the other reads. archived: true reads the archived dead letters instead, and each group carries the operators' note, with noteBy and noteAt (from 1.2; before that the field was always null).
  • Acting on a group (1.1). replay_dead_letter_group, archive_dead_letter_group, restore_dead_letter_group and discard_dead_letter_group take a group's key as failureGroup, a required reason, and optionally a serviceName, from / to and tenantId. Each sends ONE operation, fleet-wide unless a service is named, and the console narrows it per service as above. Replay needs dlq.replay, archive and restore need dlq.archive, and discard needs dlq.discard, on each service the operation reaches. Discard is confirmed first; its preview counts the group now. The console refuses a second operation on a group with one still running, and a tool's accepted: true means sent, not applied: the Operations tab shows what ran.
  • The note on a group (1.2). set_dead_letter_group_note(failureGroup, note) writes the same note as the console's pencil: it belongs to the group's key fleet-wide, survives replays, keeps the text it replaced, and an empty note clears it. It needs dlq.note, takes no confirmation token (nothing is lost), and is audited with channel MCP. Use it to leave what an investigation found for the next operator.
  • Replay history (Wolverine 6.54). Each envelope from query_dead_letters carries replayCount (how many times it was replayed and failed again), firstFailedAt and lastReplayedAt. They are null when the service's store does not record the history (an older Wolverine, or a dead letter written before 6.54), which means unknown, never 0.
  • The actions take a reason and return an operation id. replay_dead_letters and discard_dead_letters accept an optional reason, recorded on the audit row and in the console's operation history, and answer with the operationId the Dead Letters page's Operations tab tracks the operation under: how many of its databases answered, and how many dead letters it affected.

They carry a capability where the other read tools do not, because dead letters contain message bodies and exception detail — business data. "May look at them" is worth granting separately from "may act on them".

Always check databasesAnswered against databasesAnnounced

Both tools fan out across every physical message database a service owns, and both report how many were asked versus how many replied, plus a partial flag and a warning string.

A store that fails to answer is otherwise indistinguishable from a store with no rows. That is exactly how the console came to assert "No dead letter queue entries found." over a queue holding 42 dead letters on an eight-database deployment. An empty result with partial: true means some stores did not report — not that the queue is empty. Do not conclude a service is clean on the strength of a partial read.

Projection troubleshooting ​

The three tools are one runbook, in order, and each hands the next its inputs:

diagnose_projection answers "is this projection running?" from the console's own data — no round trip to your service, so it works even when the service is unreachable. It returns the projection's shards worst first, each with the shared health verdict and the reason behind it, the latched apply error's type and message, the shard's position and the high-water mark it was measured against, dead-letter counts, and any alerts already firing about it.

run_projection_stepper answers "is it producing the right answer?", which nothing in a progression table can. It replays the monitored service's own production projection code over a slice of its real events and returns the projected state before and after every event, per aggregate instance. Nothing is written — the replay is in-memory on the service and does not move any shard's position. Source modes are stream, streamslice (fromVersion/toVersion, much cheaper once you know where to look) and tagquery (DCB tags).

get_projection_apply_source fetches the exact Apply(<EventType>) overload that ran on a step the stepper flagged. Source comes from the running assembly's PDB, so a service published without symbols answers found: false with an explanation rather than code.

A null gap is not a caught-up shard

gap and highWaterMark are null when nothing could be measured — never 0. mark − sequence is zero both for a level shard and for one with no denominator at all, and collapsing the two once put a green pill on twenty projections whose lag the tile two inches away called unmeasurable. "gap": 0 means caught up; "gap": null with "status": "Unmeasurable" means you do not know.

An empty shards array has three causes that are indistinguishable from the array alone — an unknown service (serviceKnown: false), a misspelled projection name, and a service whose shards CritterWatch is not tracking at all. None is a clean bill of health. Read serviceKnown and warning.

Stepper responses truncate by default

Every step row carries the projected state twice and a stream can run to thousands of events, so maxRowsPerBucket defaults to 25 (max 200) and maxBuckets to 10 (max 50). Compare rowsReturned against rowsTotal and bucketsReturned against bucketsTotal; when either is short, truncated is true and warning says so in prose. Pass includeState: false for a compact outline when the states are large.

Per-step apply failures never populate error — they ride the individual rows and the timeline continues past them, because the state after a failed apply is part of the diagnosis. A response with ran: true and totalFailedSteps: 3 ran fine and found three broken applies.

run_projection_stepper and get_projection_apply_source additionally require CritterWatchOptions.EnableEventStoreExplorer = true on the monitored service; diagnose_projection has no such precondition.

Event query ​

query_events queries the raw events in a monitored service's event store — identically whether that service runs Marten (PostgreSQL), Polecat (SQL Server) or Fisher (SQLite), because the query executes on the monitored service through the JasperFx.Events abstractions. The agent needs no database credentials and no dialect; the console's message channel is the access path. It is the "what actually happened?" tool: did the command emit the events you think it did, in the order you think, with the payloads you think — the write side, where run_projection_stepper is the read side.

Every filter combines with every other in one query, and they all AND together: tags (a JSON object, DCB semantics — every tag must match), streamId, eventTypeName / eventTypeNames, the timestamp and sequence windows, and correlationId / causationId / userName. Every answer is a page plus totalCount — of the combined match — on Marten, Polecat and Fisher alike. All of it takes tenantId, storeUri (an ancillary store's Subject URI, exactly as CritterWatch reports it), paging, and includeData: false for an envelope-only survey.

A tags-only query against a monitored service too old to honour tag filters on the combined path is detected — its applied-filter echo lacks TagValues — and re-asked on the older standalone tag path, which that service does speak. Every other dropped filter stays a loud FilterMismatch.

There is deliberately no aggregation: totalCount per filtered call is the counting primitive (count-by-type is one cheap call per event type), and the reasoning belongs to the connected model.

Read the honesty fields before concluding anything

NoResponse means the service did not answer — not that it has no events. A tenant filter against a store without multi-tenancy is an error (EventQueryFailed naming the reason), never an empty page. hasMore: true / a totalCount larger than the page means the page is a floor. Every query_events call requires CritterWatchOptions.EnableEventStoreExplorer = true on the monitored service — on by default only in Development — and answers ExplorerDisabled otherwise, which is a configuration answer, never "no events". Before 1.1 only the tag path checked it.

Event payloads are business data, so the tool carries its own capability (mcp.events.query) — the same reasoning as mcp.projection.step, whose projected states are derived from these very events. The CLI twin is the events-query command in JasperFx.Events' command line (beside projection-run), which runs on the application host against its own store — the no-console path, and the right tool inside a test loop.

Document reads: predicates, plans and rebuilds ​

query_documents pages one document type as JSON with the total matching count (pageSize at most 200). Soft-deleted documents are hidden unless includeDeleted: true, which returns them flagged isDeleted; allTenants: true reads every tenant of a multi-tenanted store and cannot be combined with tenantId. It filters and orders on the document's own properties with where / orderBy / arguments (Dynamic LINQ applied by the service's store), and on its metadata with correlationId, causationId, lastModifiedBy and orderByMetadata. Two arguments answer questions the page itself does not:

  • explain: true adds plan, the store's own plan for the page: rowsExamined against rowsReturned, indexesUsed, scansTable, whether the figures were measured (isActual), and the engine's plan text. A null field means the engine does not say, never zero or false. PostgreSQL measures by running the query a second time. When there is no plan, planUnavailable says why.
  • get_document with rebuild: true adds rebuilt, the document aggregated live from its stream by the single-stream projection that produces it (list_document_types names it as singleStreamProjection), and differences, the member paths where stored and rebuilt disagree. rebuiltToNothing and rebuildUnavailable cover a stream that produces no document and a type that cannot be rebuilt. Nothing is written.

A metadata filter on a type that does not capture that column is refused as CriteriaRefused naming it (jasperfx#1077). A store built before JasperFx 2.95 ignores it instead, so the answer echoes the filters under metadataFilters with that caveat. explain, rebuild and that refusal all need the service's store on JasperFx 2.95 (Marten 9.54 / Polecat 5.46 / Fisher 1.24).

SQL query ​

query_sql runs one read-only SELECT against a monitored service's event-store database, on the service's own connection, and returns the rows. It is the escape hatch beside query_events: use it for the question the structured filters cannot express — a join to a projection document table, a GROUP BY over a payload field, a count per stream — at the price of writing the target store's own dialect (PostgreSQL for Marten, T-SQL for Polecat, SQLite for Fisher; the answer's engine says which). Prefer query_events for anything its filters can express.

What the monitored service enforces: a single SELECT (or WITH … SELECT) — a second statement and INTO are refused; table references allow-listed to the objects the store declares, with a refusal that lists them (allowedTables) so the next attempt can be right; a read-only transaction that is always rolled back; a statement timeout (timeoutSeconds, default 30, max 120) and a row cap (maxRows, default 100, max 1,000) reported as truncated rather than presented as a total. There is no paging past the cap — it is the contract, not a missing parameter — so a statement that needs rows beyond it windows them itself with ORDER BY plus LIMIT/OFFSET or OFFSET … FETCH. parameters is a JSON object referenced as @name in the statement, typed by inference. Cells come back typed where the column type allows — integers, decimals and booleans as numbers and booleans, JSON columns parsed into JSON — and as text otherwise.

Addressing: storeUri names one event store and is required on a service with more than one (StoreAmbiguous lists them — SQL cannot fan out across stores the way query_events does); on a database-per-tenant store give tenantId or databaseIdentifier (DatabaseAmbiguous lists the databases; the service never picks one).

Honesty fields

NoResponse means the service did not answer — not zero rows. Disabled means the service has not opted in: CritterWatchOptions.EnableSqlQuery follows EnableEventStoreExplorer unless set, so it is on by default only in Development. Timeout means the statement was cancelled, not that it returned nothing. truncated: true means the rows are a floor in the statement's own order — put an ORDER BY and a LIMIT / TOP in the statement.

This reads business data by the table, so it carries its own capability, mcp.sql.query, scoped to the target service — separate from mcp.events.query, because an operator trusted to read events by filter is not thereby trusted to SELECT * from every projection. Every attempt that reaches the wire is written to the audit log with the statement and the caller. There is no CLI twin inside the stack: psql / sqlcmd / sqlite3 against your own store are that twin.

Conversations ​

list_conversations and get_conversation answer "what actually happened to this one request across the fleet?", the question the console's Conversations page answers for an operator. A conversation is every message one request caused, grouped by Wolverine correlation id, or by the W3C trace id when there is none.

  • list_conversations returns recent conversations, newest activity first: the conversation id, correlation id, root message type, services, started and last activity, hop count and hasFailure: whether any message in it is still failed, judged by its latest attempt, so one retried or replayed into success does not count. Narrow it with messageType (full or short name), serviceName, failedOnly and since.
  • get_conversation opens one by conversationId or correlationId. A W3C trace id or a message id (a dead letter's id) works too, and matchedBy says which matched. That is what lets a correlation id from a failing test, a log line or an alert go straight to the conversation behind it. It returns:
    • the hops: each captured span, with its parent span, service, message type, kind, message id, destination, handler, saga, start, duration, status and status description;
    • the edges of the Why graph, between envelopes. An edge is observed when a captured parent span links the two, and inferred when only time order does. An async projection or subscription boundary splits a flow into several traces that share a correlation id, and no captured span crosses it;
    • the timeline (the When view): each envelope's start, end and duration, and the gap before it, which is where a scheduled message or a queue wait shows up. Each envelope is failed when its latest attempt failed, and recovered when an earlier attempt failed and a later one succeeded (a retry, or a replay from the dead-letter queue). Only a failed envelope has anything in the dead-letter queue to act on.

Both tools derive the edges and the timing with the same code the console's page uses, so an agent and an operator are never shown two different graphs of one conversation. The derivation is pinned to one shared fixture from both sides.

Read completeness before the chain

get_conversation sets completeness.mayBeIncomplete when hops may be missing, and says why in completeness.notes:

  • retention is at its cap and this conversation starts at the edge of what is kept (startMayBePruned), so its earlier hops may have been pruned. retentionFull on its own is a console-wide fact: it is true on any busy console within minutes, and it says nothing about a conversation that began well inside the window;
  • a span names a parent the console never captured: an HTTP request or other non-Wolverine span, a service CritterWatch does not monitor, or a pruned hop;
  • an envelope was sent but never seen received;
  • a message was sent outside any handler or request (unlinkedSends). A projection's side effect reads like this, and so does a timer or a background loop. originNotCaptured is true when the first message carries the correlation id of a trace the console holds nothing of, so what began the conversation is known to be missing.

When mayBeIncomplete is true, do not read the chain as the whole story. Inferred edges are counted (inferredEdges) and noted, but they do not set it: an inferred edge is a link that was not captured, not a missing hop. Read one as order, not cause.

A hop carries no message body. A failed hop's status description, though, is the handler's exception message, and exception text often carries the data that failed. So conversations get their own capability, mcp.conversations.read. list_conversations needs it on the named service, or fleet-wide when there isn't one. get_conversation needs it on every service the conversation touches. The CLI twin is cw-conversations, which emits the same JSON. From 1.2, list_conversations also takes sagaId (and cw-conversations --saga-id): every conversation that touched one saga instance. A hop carries the saga id but not the saga type, so narrow by service when two saga types can share an id.

Sagas ​

list_sagas, list_saga_instances and get_saga_instance (1.2) answer "where is this saga instance, what has it done, and what is it waiting on?", the question the console's Saga Explorer answers for an operator.

  • list_sagas(serviceName?) is the catalog each service reports: the saga state type, its id type, its storage, and every message type it handles with its role (Start, StartOrHandle, Orchestrate, NotFound) and the member that carries the saga id. It reads what the console already stores, so it asks no service anything.
  • list_saga_instances(serviceName, sagaType, count) reads instances from the service's own saga storage: identity, whether each is completed, when it last changed, and its state as JSON. It is a bounded peek, an arbitrary set in no particular order (not the newest), not a search; a store may return fewer than asked.
  • get_saga_instance(serviceName, sagaType, identity) puts one instance's story together in one call:
    • state: the instance, read from the service's saga storage. A completed saga that was deleted is NotFound, and its history still answers.
    • executed: the messages captured for that saga id on that service, from the console's conversation hops. When a trace provider is bound, traces lists the traces carrying the saga's id tag ({SagaName}Id); open one with get_trace.
    • outstanding: the message types the saga handles that have not been observed for this instance.
    • pending: the instance's pending timeouts, which are the scheduled messages carrying its saga id, read from the service's own message store (up to 50, soonest first, with totalCount and hasMore). A service whose Wolverine.CritterWatch is older than 1.2 cannot filter its schedule by saga, so it is not asked: pending.available is false and the reason says so. On a service with several message databases the answer is the first database to reply, and database names it.

Read sources before the answer

sources says which part answered: state (answered, NotFound, ExplorerDisabled, NoResponse, …), conversations (with scanTruncated), traces (answered, notBound, …) and scheduledMessages (answered, notSupported, noResponse, failed). Not observed is not "did not happen": the console keeps a bounded number of conversation hops, and traces cover only the provider's window. NoResponse means the service did not answer, not that there is no such instance.

A saga's state is application data, so these tools carry their own capability, mcp.sagas.read, on the named service (fleet-wide for list_sagas without one). The two relay reads also need the service's explorer on (EnableEventStoreExplorer, on by default only in Development); a service that has it off answers ExplorerDisabled.

Scheduled messages ​

query_scheduled_messages lists the pending scheduled messages in a monitored service's own message store — envelope metadata only (id, message type, scheduled time, destination, attempts, tenant and, from 1.2, the saga id), never message bodies, which is why it needs no dedicated mcp.* capability. Its ids are what the cancel/reschedule action tools take, and it is where a rebuild deferred with schedule_projection_rebuild becomes visible: the service schedules the deferred command into its own store precisely so this surface — and the console's Scheduled Messages page — can see, cancel, and move it. From 1.2 it takes sagaId, to list one saga instance's scheduled messages; it is refused, rather than answered with the whole schedule, for a service on a Wolverine.CritterWatch older than 1.2.

Honesty fields

NoResponse means the service did not answer — not an empty schedule. A multi-database service answers once per database and the unscoped read returns the first answer, labelled as such — pass databaseUri to read one database exactly. And scheduling has no duplicate guard (the store exposes no message bodies to compare): calling schedule_projection_rebuild twice schedules two rebuilds, both visible and cancellable here.

Trace tools route through the per-service ITraceProvider binding cascade — operators bind Jaeger, Datadog, etc. to specific services and the tools surface whichever provider is configured for the service in the query.

Action tools (RBAC-gated) ​

Each takes a target serviceName (or resource id) and runs the RBAC enforcement pipeline before publishing the existing Wolverine command. On allow, returns an Accepted JSON envelope; on deny, returns a Forbidden / LicenseMissing envelope.

Every action tool publishes its command with the caller's relay ticket. The console's relay authorizes again on its side, and the ticket is how it knows who asked: without it an authorizer refuses the command after the tool has already answered accepted: true. The same ticket is what writes the audit row with channel MCP, the caller's name and the client (the request's User-Agent) (see Audit Log › Channels). accepted: true means the command was published, not that the service has applied it. replay_dead_letters and discard_dead_letters also return an operationId you can follow to the end on the Dead Letters page's Operations tab. To find out what became of any other relayed command, see What happened to a command.

FamilyToolsCapability
DLQreplay_dead_letters, discard_dead_lettersdlq.replay, dlq.discard
DLQ failure groupsreplay_dead_letter_group, discard_dead_letter_group, archive_dead_letter_group, restore_dead_letter_group, set_dead_letter_group_notedlq.replay, dlq.discard, dlq.archive (archive and restore), dlq.note (the note)
Projectionpause_projection, restart_projection, rebuild_projection, eject_projection, eject_retired_projection_versionprojection.pause, projection.restart, projection.rebuild, projection.eject (both ejects)
High water detectionrestart_high_water_detectionprojection.restart-high-water
High water mark advancepreview_high_water_advance, advance_high_water_markprojection.advance-high-water (both; the preview is the evidence for the advance)
Recurring schedulespause_recurring_schedule, resume_recurring_schedule, trigger_recurring_schedulerecurring-schedule.pause, recurring-schedule.resume, recurring-schedule.trigger
Stream compactionrun_compaction_policycompaction-policy.run
Stream compactionpause_compaction_policy, resume_compaction_policyrecurring-schedule.pause, recurring-schedule.resume
Scheduled messagesschedule_projection_rebuild, cancel_scheduled_message, reschedule_scheduled_messageprojection.rebuild (scheduling a rebuild IS a rebuild action), scheduled-message.cancel, scheduled-message.reschedule
Tenantadd_tenant, enable_tenant, disable_tenant, remove_tenant, hard_delete_tenanttenant.add, tenant.enable, tenant.disable, tenant.remove, tenant.hard-delete
Alertacknowledge_alert, snooze_alert, clear_alertalert.acknowledge, alert.snooze, alert.clear
ChaosMonkeyenable_chaos_monkey, disable_chaos_monkey, set_chaos_monkey_failure_rate, set_chaos_monkey_slow_handler, set_chaos_monkey_projection_failure_rate, set_chaos_monkey_projection_poison, clear_chaos_monkey_projection_poison, seed_dead_letterschaos-monkey.toggle (on/off), chaos-monkey.configure (rate / delay / poison / seeding)
Listenerpause_listener, restart_listener, drain_listenerlistener.pause, listener.restart, listener.drain
Metricsdelete_metrics_samplesmetrics.delete
Serviceevict_serviceservice.evict
Documentsupdate_document, delete_document, undelete_documentdocuments.write, documents.delete (undelete too)

ChaosMonkey and Tenant deliberately split their capabilities so an operator trusted to stop chaos isn't automatically trusted to crank it higher, and a tenant cleanup grant doesn't extend to dropping the tenant's database. See the RBAC page for the full rationale.

What happened to a command ​

Every action tool that relays a command to a monitored service says so in its result:

json
{
  "accepted": true,
  "operation": "RestartListener",
  "serviceName": "TripService",
  "endpointUri": "rabbitmq://queue/trips",
  "correlationId": "5f0c2a7e9b1d4c3f8a6e2d1b7c4f9e03",
  "hostOutcome": "unknown",
  "hostOutcomeNote": "accepted means the command was sent. ..."
}

hostOutcome is unknown because the tool answers once the command is published, and it does not wait for the service. Pass correlationId to get_command_outcome to see whether the service reported a failure:

hostOutcomeMeaning
failedThe service reported a failure. failures lists each one, with serviceName, commandType, exceptionType, error and reportedAt. exceptionType is None when the service refused without throwing. A fan-out can list more than one.
unknownNo failure has been reported. This is not success.

A failure reaches the lookup whichever way the service reports it: CommandFailed when a handler throws, or a failed final acknowledgement from the commands that refuse without throwing, which are the projection, recurring schedule, compaction and high water commands. A missing license on that host reaches it either way.

The console records failures only, so get_command_outcome can never report success. unknown means the command worked, is still on its way, or was refused in a way this lookup cannot see:

  • A command the console itself refuses before relaying it, such as one aimed at an unknown service, never reaches a service. An MCP caller is not told about those.
  • eject_retired_projection_version reports its own refusals on its answer, which the lookup does not read. A missing license is the exception, and does appear.
  • A dead-letter operation that fails on one database reports it on the operation, so follow operationId on the Operations tab.

A rebuild refused because the same projection is already rebuilding is not a failure: that rebuild carries on, so it stays unknown.

So confirm the effect with the read tool for what you changed, which hostOutcomeNote names where there is one. For a listener that is get_service_health once the next health snapshot arrives, within about a minute: a paused listener reads Paused, and a paused local queue reads as a Sending endpoint with senderLatched: true.

A failure is kept for as long as the timeline keeps its entries, and goes when the service is evicted. The console's document tools (update_document and its siblings) do not use any of this: they wait for the service's reply.

The commands that stop at the console, such as acknowledge_alert, set_dead_letter_group_note, evict_service and delete_metrics_samples, have no service to hear from, so they carry none of these fields.

Tool annotations: readOnlyHint and destructiveHint ​

Every tool states both MCP annotations explicitly, so an agent client can decide when to ask the user before it runs one, rather than prompting for everything or trusting everything. The classification is deliberately conservative:

AnnotationTools
readOnlyHint: true, destructiveHint: falseEvery read tool above. preview_high_water_advance, list_high_water_loops and query_scheduled_messages are reads too, although they sit beside actions. So is get_document with rebuild: true: it aggregates the stream in memory and writes nothing.
readOnlyHint: false, destructiveHint: truediscard_dead_letters, replay_dead_letters (re-runs handlers), discard_dead_letter_group, replay_dead_letter_group, update_document, delete_document, disable_tenant, remove_tenant, hard_delete_tenant, rebuild_projection, schedule_projection_rebuild, eject_projection, eject_retired_projection_version, advance_high_water_mark (skips events), cancel_scheduled_message, trigger_recurring_schedule (runs the job), run_compaction_policy, enable_chaos_monkey, the four set_chaos_monkey_* tools, seed_dead_letters, delete_metrics_samples, evict_service
readOnlyHint: false, destructiveHint: falsearchive_dead_letter_group, restore_dead_letter_group (both lose nothing), set_dead_letter_group_note (keeps the text it replaces), acknowledge_alert, snooze_alert, clear_alert, pause_listener, restart_listener, drain_listener, pause_projection, restart_projection, restart_high_water_detection, pause_recurring_schedule, resume_recurring_schedule, pause_compaction_policy, resume_compaction_policy, reschedule_scheduled_message, disable_chaos_monkey, clear_chaos_monkey_projection_poison, undelete_document, add_tenant, enable_tenant

An action counts as destructive unless it is clearly reversible and loses no data. Re-running work that has side effects, injecting a fault, and taking something offline all count. Every rebuild is destructive. Annotations are fixed per tool, so they cannot depend on the projection being rebuilt at call time, and the one rebuild that would not be (a single stream of an Async projection) has no tool.

⚠️ A hint is advice to the client, not enforcement. A client set to auto-approve ignores it, so the hints sit beside the licence and RBAC gates, never in place of them.

Confirmation tokens: the server asks before an irreversible call ​

Annotations leave the decision to ask with the client, and a client set to auto-approve never asks. So for the calls that cannot be undone, the server asks:

  1. Called without confirmationToken, the tool changes nothing and publishes nothing. It answers with a preview of what the call would do and a token:

    json
    {
      "confirmationRequired": true,
      "tool": "discard_dead_letters",
      "preview": { "action": "Permanently delete 2 dead letter(s) from RepairShop's dead-letter storage.", "messageIdCount": 2, "...": "..." },
      "confirmationToken": "…",
      "expiresAt": "2026-10-25T15:05:00Z",
      "message": "Nothing has been changed. To perform this, call discard_dead_letters again with exactly the same arguments plus confirmationToken."
    }
  2. Called again with exactly the same arguments plus that confirmationToken, it performs the call.

The token is bound to the caller, the tool and a hash of the arguments. It is single-use and lives five minutes. A refusal uses the usual deny envelope:

errorMeaning
ConfirmationMismatchA different caller, tool or arguments, or a token that was never issued
ConfirmationExpiredPast its five minutes. Preview again
ConfirmationConsumedAlready used. Each token performs one call
ConfirmationUnavailableThe host has no confirmation store, so the tool refuses rather than run unconfirmed

Licence and RBAC run on both calls, because a preview can reveal data. Tokens are kept in the console's own store, so the second call works on any node of a cluster, and an atomic insert makes them single-use however many callers race. The store keeps a hash of the token, never the token itself, and expired tokens are swept an hour after they expire.

ToolConfirmed
discard_dead_letters, discard_dead_letter_group, update_document, remove_tenant, hard_delete_tenant, eject_projection, eject_retired_projection_version, cancel_scheduled_message (this also covers cancelling a scheduled rebuild), delete_metrics_samples, evict_serviceAlways. update_document's preview is its own dry run, and dryRun: true is never confirmed
delete_documentWhen the type is not soft-deleted. isSoftDeleted: false, an older store that cannot say, and no answer all count as permanent
run_compaction_policyWhen the policy is armed, or the console cannot tell. A dry-run policy runs unconfirmed
trigger_recurring_scheduleWhen the schedule drives an armed compaction policy, or the console cannot tell. A schedule the console knows is not a compaction schedule runs unconfirmed

advance_high_water_mark already conforms and takes no token. It requires the expectedCurrentMark and confirmSkipCount that preview_high_water_advance reports, and the service refuses, writing nothing, if the mark has moved or the gap no longer matches the confirmed skip count. Those checks are bound to the state, which is stronger than a token.

A service on Wolverine.CritterWatch 1.1.0 does not check the skip count

The skip-count check arrived in 1.2. An older service ignores confirmSkipCount and advances on the mark check alone. The tool's result says which one ran: skipCountEnforced is false, with a note, for an older service.

Both calls are audited, with channel MCP: McpConfirmation.Issued when the preview is shown and McpConfirmation.Redeemed when the confirmed call runs. They share confirmationId in their parameters.

⚠️ What it guarantees, and what it does not. The agent receives the concrete consequence before it acts, and the call that runs is exactly the call that was previewed. It does not prove that a person looked: an agent on auto-approve can still chain both calls. Show the preview to the user, and make the second call only on their answer.

Document writes: read first, then write against that version ​

update_document, delete_document and undelete_document send the same SaveDocument / DeleteDocument / UndeleteDocument commands the Document Store Explorer's editor sends, so there is one write path. The store does the write through its own serializer and session, never a raw UPDATE. Unlike the other action tools, they wait for the service's answer instead of returning Accepted.

  • expectedVersion is required. Read the document with get_document and pass its metadata.version. A stale version comes back as ConcurrencyConflict with the current document, and nothing is written. The SPA may write unconditionally; an agent may not.
  • The answer to a save is the document as stored, which can differ from the JSON sent: a member the type does not declare is dropped.
  • Distinct error kinds: EditingDisabled (the service has not opted into EnableDocumentEditing; on only in Development by default), ConcurrencyConflict, NotFound, Refused (the store's own reason), BadRequest, and Timeout. A timed-out write may still have been applied, so read the document again before retrying.
  • Know which delete it is before confirming. list_document_types reports isSoftDeleted per type (jasperfx#1070): true means the row stays, marked deleted, and undelete_document can restore it; false is a permanent delete. A store built before JasperFx 2.94 always sends false, so false must be read as permanent.
  • Preview an edit with dryRun: true. update_document then answers Previewed with the document exactly as the store would keep it (dropped members, normalized casing and enums) and writes nothing.
  • A projection-produced document is overwritten by the next event or rebuild.
  • The audit row is the relay's, attributed to the MCP caller through the relay ticket. It records that a write was requested and against which version, never the JSON.

Deterministic chaos: prefer it over the rates ​

Three of the ChaosMonkey tools produce a known failure rather than a probable one. Reach for them whenever you need to reason about a specific failure — which is most of the time.

ToolUse instead ofWhy
set_chaos_monkey_projection_poisonset_chaos_monkey_projection_failure_rateThe rate is a dice roll per apply, so the alert, the dead-letter drill-in and the projection stepper each land on a different random event. A poison names one event — by type, or by stream and version — so all three agree, and the stepper reproduces it on the exact step instead of failing randomly under itself. It fires independently of the rate, so you can reproduce with the rate at 0.
seed_dead_letterswaiting on set_chaos_monkey_failure_rateThe failure rate has produced Handled=905, DeadLetter=0 after minutes on a service whose handlers mostly succeed. Seeding writes a known number immediately, with varied message types, exception types, attempt counts and ages so the DLQ summary groups meaningfully. Each seeded failure has its own throw site, so Failure Groups shows one fingerprinted group per failure, titled after it.
clear_chaos_monkey_projection_poison—Disarms the poison and leaves the probabilistic rate alone. Use disable_chaos_monkey to stop everything.

Seeded dead letters are replayable: a configurable fraction is seeded recoverable and succeeds on replay, while the rest throw again and return to the queue. That makes "replay the recoverable ones, discard the rest" a real decision rather than a scripted gesture where everything replays cleanly.

Both write to real storage on a real service. They are chaos-monkey.configure-gated and license-gated, like the rest of the family — use them against staging and dev services.

Per-tenant scoping on projection action tools ​

pause_projection, restart_projection, and rebuild_projection take the projectionShardName the read tools report, and accept an optional tenantId argument. When supplied, the action runs against only that tenant's projection shard (using the same per-tenant daemon path the SPA's per-tenant Rebuild button uses). When omitted on a multi-tenant service, the action targets the store-global shard — typically what you want on a single-tenant service and almost never what you want when tenants are partitioned.

For authorizers, the RBAC resource of these three tools (and of schedule_projection_rebuild) is the projection's agent URI, event-subscription://{serviceName}/{projectionShardName}, with @{tenantId} appended when the agent supplies a tenant id — for example event-subscription://tripservice/TripSummary:All@acme-corp. It is the same resource the relay asks about when an operator presses the button in the console, so one grant covers both. The URI's host is lower-cased by URI normalization, so compare service names case-insensitively.

⚠️ Changed in 1.1. These tools used to ask about {serviceName} or {serviceName}:{tenantId}, while the relay asked about the agent URI, so no single grant satisfied both. The tenant tools changed the same way and now ask about the tenant id. An authorizer that matches on resource needs its patterns updated: see Upgrade Notes.

A per-tenant authorizer therefore takes the tenant from after the last @ and the service from the URI's host. A resource with no @ is the store-global shard, which this sample leaves to its other paths:

cs
public Task<bool> IsAllowedAsync(
    ClaimsPrincipal principal, string capability, string? resource, CancellationToken ct)
{
    // A projection action's resource is the projection's agent URI,
    // event-subscription://{service}/{shard}, with "@{tenantId}" appended when
    // the action is narrowed to one tenant.
    if (capability == Capabilities.ProjectionRebuild
        && resource is { } scope
        && TrySplitScope(scope, out var service, out var tenantId))
    {
        return Task.FromResult(principal.HasGrant(service, tenantId, capability));
    }

    // … other paths
    return Task.FromResult(false);
}

// The tenant is whatever follows the LAST '@'. The service is the URI's host, which
// URI normalization lower-cases, so compare service names case-insensitively.
private static bool TrySplitScope(string scope, out string service, out string tenantId)
{
    service = "";
    tenantId = "";

    var at = scope.LastIndexOf('@');
    if (at < 0 || !Uri.TryCreate(scope[..at], UriKind.Absolute, out var agentUri))
    {
        return false;
    }

    service = agentUri.Host;
    tenantId = scope[(at + 1)..];
    return true;
}

The agent-URI resource is the one the SignalR-routed commands use, so the MCP tools and the console's buttons are asked the same question.

RBAC enforcement ​

Each action tool calls a single helper before publishing:

csharp
var gate = await McpAuthorizationContext.EnforceAsync(
    httpContextAccessor, authorizer,
    Capabilities.DlqReplay, resource: serviceName, ct);
if (gate.IsDenied) return gate.DenyPayload!;

The helper runs the license guard + RBAC check (RbacGuard.IsAllowedAsync against HttpContext.User). Deny produces a stable-shape JSON envelope:

FieldMeaning
error"LicenseMissing" or "Forbidden" (a read-only server's backstop answers "McpReadOnly", and the confirmation refusals have their own codes)
messageHuman-readable explanation
capabilityThe capability string the caller is missing (only on Forbidden)
resourceThe resource scope the deny was evaluated against (only on Forbidden, only when supplied)

Off-mode hosts (no custom authorizer registered) see the DefaultAllowAuthorizer and every grant succeeds — same shape as the HTTP enforcement layer. See RBAC for the operator- facing detail.

Why stateless transport ​

The MCP server runs with HttpServerTransportOptions.Stateless = true. This is required for RBAC enforcement: in the default (stateful) mode the HttpContext reachable via IHttpContextAccessor is the one that initialised the MCP session, not the one of the current tool invocation. HttpContext.User would be stale (or empty) for every action after init.

Stateless mode also removes the need for session affinity on multi-node deployments — a useful side benefit for clustered CritterWatch installations.

Licensing ​

All MCP tools are license-gated. Read tools and action tools both check McpLicenseGuard.IsAllowed() before doing any work; the first check caches the result for the process lifetime. The license is the same JASPERFX-signed license CritterWatch's core uses (see Licensing).

In tests, pre-seed the cache via CritterWatch.Mcp.Licensing.McpLicenseGuard.SetForTesting(true) at assembly load — see src/McpTests/LicenseSetup.cs for the module- initialiser pattern.

Composition ​

Standalone (default) ​

cs
builder.Services.AddCritterWatchMcp();
// …
app.MapCritterWatchMcp();

This:

  • Registers an MCP server with the streamable-HTTP transport configured stateless.
  • Adds every tool in the read + action families. The registered catalog is test-enforced by McpToolRegistrationTests, which asserts registered == documented == defined — so the live tools/list response is the count, and this page is the description.
  • Wires AddHttpContextAccessor() so action tools can resolve the caller's principal.

Read-only: investigate, never act ​

For teams that want agents to look but not touch, one switch leaves only the read tools registered:

cs
// Only the read tools are registered. Or set CritterWatch:Mcp:ReadOnly = true in configuration.
builder.Services.AddCritterWatchMcp(o => o.ReadOnly = true);
// …
app.MapCritterWatchMcp();

or, with no code change, CritterWatch:Mcp:ReadOnly = true in configuration (CritterWatch__Mcp__ReadOnly=true as an environment variable, or WithCritterWatchMcp(readOnly: true) from an Aspire AppHost).

  • The action tools are not registered at all. They are absent from tools/list, so an agent can neither see nor call one, and its context carries only the read tools. Which tools stay is decided by each tool's readOnlyHint (see tool annotations), not by its class: preview_high_water_advance, list_high_water_loops and query_scheduled_messages stay, beside actions that go.
  • A backstop refuses any CritterWatch action that is still reachable, for example one added to the server some other way, with the deny envelope { "error": "McpReadOnly", ... }. Another package's tools on a composed server are not affected.
  • The agent is told. The server's MCP instructions say it is read-only, so an agent asked to act explains why it cannot instead of hunting for a tool.
  • Reads stay gated exactly as before. The licence check, and the capabilities on the gated reads (mcp.dlq.read, mcp.sql.query, mcp.events.query, mcp.documents.read, mcp.projection.step, mcp.conversations.read, mcp.sagas.read), still apply. Read-only does not mean ungated.
  • Either setting turns it on, and neither turns the other off. Configuration can make a server read-only without a code change, and a false in configuration cannot undo ReadOnly = true in code.
  • It is read once at startup, so a change takes effect on restart.

Chained alongside per-store servers ​

If your host already composes an MCP server (e.g. with Marten.Mcp + WolverineFx.Mcp), chain CritterWatch's tools onto the existing builder:

csharp
builder.Services
    .AddMcpServer()
    .WithHttpTransport(o => o.Stateless = true)
    .AddCritterWatchMcp()
    .AddMartenMcp()
    .AddWolverineMcp();

When composing, the host is responsible for setting Stateless = true on the transport and for registering AddHttpContextAccessor() itself. The IMcpServerBuilder overload of AddCritterWatchMcp() only chains the tools; the standalone IServiceCollection overload sets up both for you.

Connecting an MCP client ​

Any client that speaks streamable HTTP MCP can connect — for example the @modelcontextprotocol/inspector:

bash
npx @modelcontextprotocol/inspector
# URL: http://localhost:5173/api/mcp (or your BFF's address)

For Claude Desktop or similar, configure the MCP server in the client's config to point at /api/mcp on your CritterWatch host. The transport is streamable HTTP, not stdio — pick the matching client setting.

If your host has RBAC enforcement on, the MCP client needs to present an authenticated principal that the host's authentication layer recognises (OIDC bearer token, signed header from a reverse proxy, etc.). Anonymous calls hit the fail-closed-on-no-principal branch and get a Forbidden envelope.

Testing ​

McpTests in the CritterWatch repo covers every tool with the same matrix: happy-path publish, RBAC deny, fail-closed-on-no-principal, license-missing, plus per-tool bad-request cases. Tools are invoked directly with substituted IHttpContextAccessor / authorizer / IMessageBus — no MCP server stand-up needed for unit-style tests. See src/McpTests/Mcp/DlqActionToolsTests.cs for the reference shape.

  • RBAC — capability catalog + authorizer interface
    • custom authorizer skeleton
  • Licensing — the same license gates both surfaces