Skip to main content
Version: 3.x

Model Context Protocol

UnambitiousFx.Synapse.ModelContextProtocol exposes Synapse requests as Model Context Protocol tools. An MCP tool is one more transport, like HTTP: the tool builds the request from its arguments, IMcpInvoker sends it through the pipeline (so authorization, validation and every other behavior apply), and the Result becomes a CallToolResult.

It is the MCP counterpart of IHttpInvoker.

Install​

dotnet add package UnambitiousFx.Synapse.ModelContextProtocol
dotnet add package ModelContextProtocol # the MCP server: AddMcpServer, WithTools, transports

The package only depends on ModelContextProtocol.Core, so you pick the hosting package yourself: ModelContextProtocol for stdio, ModelContextProtocol.AspNetCore for HTTP.

Setup​

builder.Services.AddSynapse(cfg => { /* ... */ });

builder.Services.AddSynapseMcp(o =>
{
o.HideExistence = true; // the default: NotFound and Unauthorized give the same answer
o.MaxAnswerLength = 50_000; // cut longer answers and say so
o.JsonContext = AppJsonContext.Default; // NativeAOT
});

builder.Services.AddMcpServer()
.WithStdioServerTransport()
.WithTools<LoanTools>();

Tools​

[McpServerToolType]
public sealed class LoanTools(IMcpInvoker invoker)
{
[McpServerTool(Name = "get_loan"), Description("Get one loan.")]
public ValueTask<CallToolResult> GetLoan(Guid id, CancellationToken ct)
=> invoker.InvokeAsync(new GetLoan(id), ct); // IQuery<Loan> → JSON answer

[McpServerTool(Name = "rename_loan"), Description("Rename a loan.")]
public ValueTask<CallToolResult> RenameLoan(Guid id, string label, CancellationToken ct)
=> invoker.InvokeAsync(new RenameLoan(id, label), ct); // ICommand<Loan> → JSON answer

[McpServerTool(Name = "delete_loan"), Description("Delete a loan.")]
public ValueTask<CallToolResult> DeleteLoan(Guid id, CancellationToken ct)
=> invoker.InvokeAsync(new DeleteLoan(id), ct); // ICommand → "Done."
}

IMcpInvoker is scoped. The MCP SDK creates a scope per request, so the tool class gets the invoker of that request.

RequestSuccessFailure
IQuery<T> / ICommand<T>One text block holding the JSON answerTool error from IMcpFailurePolicy
ICommandOne text block: Done.Tool error from IMcpFailurePolicy

A tool error is a CallToolResult with IsError = true. The model reads it and can react (fix an argument, try another item), unlike a protocol error.

Options​

OptionDefaultEffect
HideExistencetrueNotFoundFailure and UnauthorizedFailure give the same NOT_FOUND answer.
ListValidationErrorstrueA ValidationFailure lists each error with its field and code, in the text and in _meta.
MaxAnswerLengthnullLonger answers are cut to this many UTF-16 code units and flagged (or refused, see OversizedAnswer). null means no limit.
OversizedAnswerTruncateRefuse answers a tool error instead of a cut answer; None sends it whole.
OversizedCommandAnswernullSame as OversizedAnswer, for commands (ICommand<T>) only. null follows OversizedAnswer.
SerializerOptionsnullJsonSerializerOptions used to serialize answers, as is. Wins over JsonContext.
JsonContextnullSource-generated context used to serialize answers. Without it (and without SerializerOptions), McpJsonUtilities.DefaultOptions is used.

Existence hiding​

An assistant calls tools with identifiers it guessed, read somewhere, or was given by someone else. If "you may not see this" and "this does not exist" answer differently, the difference tells it which items exist. With HideExistence on, both give exactly the same tool error:

NOT_FOUND: The requested item was not found.

The original message is dropped too, because a not-found message often names the item it looked for. An AggregateFailure holding either failure is hidden the same way. Turn it off only when every caller may know which items exist.

Answer capping​

With MaxAnswerLength set, a longer answer is cut and followed by a second text block:

[Answer truncated: showing the first 50000 of 182344 UTF-16 code units. The JSON above is incomplete; narrow the request to get the rest.]

Lengths are counted in UTF-16 code units (string.Length), not Unicode scalar values or UTF-8 bytes: most emoji count as two, and the encoded payload can be larger than the limit. The result's _meta also carries unambitiousfx.synapse/truncated: true and unambitiousfx.synapse/originalLength, in the same unit. The cut never splits a surrogate pair. Failures are never cut.

Refusing instead of truncating​

A cut answer is not valid JSON, and models do not reliably honour "the JSON above is incomplete": they read the first items as the whole answer and report wrong totals. For data an assistant computes with (amounts, statements, positions), refuse instead:

builder.Services.AddSynapseMcp(o =>
{
o.MaxAnswerLength = 50_000;
o.OversizedAnswer = OversizedAnswer.Refuse; // default: Truncate
});

A longer answer then becomes a tool error the model can act on:

ANSWER_TOO_LARGE: The answer is 182344 characters, above the 50000 limit: narrow the request (a shorter period, a filter, a page).

Its _meta carries unambitiousfx.synapse/failureCode: "ANSWER_TOO_LARGE", unambitiousfx.synapse/originalLength and unambitiousfx.synapse/maxAnswerLength, in UTF-16 code units like the limit.

Never refusing a command that already ran​

The answer is measured after the request has run. A refused command's change is kept, and the assistant only learns that its answer was too large, so it is likely to send the command again. A command's answer is usually short and bounded by its input, so the cap is a guard for queries: set OversizedCommandAnswer to None to send command answers whole while query answers are still refused.

builder.Services.AddSynapseMcp(o =>
{
o.MaxAnswerLength = 50_000;
o.OversizedAnswer = OversizedAnswer.Refuse; // queries
o.OversizedCommandAnswer = OversizedAnswer.None; // commands: sent whole
});

A request is a command when it implements ICommand<T>, the rule the authorization package uses for its default scope. OversizedCommandAnswer left to null follows OversizedAnswer, so a command answer is refused or cut like any other.

Same JSON as the HTTP API​

An application that serves the same requests over HTTP already has its JSON set up: converters (ids, dates, money), naming, and often one source-generated context per module. Set SerializerOptions to use those options as is, so the MCP answers match the REST ones:

builder.Services.AddSynapseMcp(o => o.SerializerOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
TypeInfoResolver = JsonTypeInfoResolver.Combine(CoreJson.Default, BillingJson.Default),
Converters = { new AccountIdConverter() }
});

To reuse the options ASP.NET Core already built, read them from the container with the options API (the package itself has no ASP.NET Core dependency):

builder.Services.AddSynapseMcp();
builder.Services.AddOptions<SynapseMcpOptions>()
.Configure<IOptions<Microsoft.AspNetCore.Http.Json.JsonOptions>>((o, json) =>
o.SerializerOptions = json.Value.SerializerOptions);

With several set, the most specific wins: SerializerOptions, then JsonContext, then McpJsonUtilities.DefaultOptions. Every response type must be resolvable from the options, or the call throws InvalidOperationException naming the type. Under NativeAOT, the options' TypeInfoResolver must be source-generated.

NativeAOT​

Every response type returned through IMcpInvoker must be in JsonContext (or in the source-generated resolver of SerializerOptions):

[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(Loan))]
internal sealed partial class AppJsonContext : JsonSerializerContext;

A type missing from the context throws InvalidOperationException naming the type, which the MCP SDK turns into a generic tool error.

Failure policy — IMcpFailurePolicy​

DefaultMcpFailurePolicy builds every tool error:

FailureTool error text
NotFoundFailure, UnauthorizedFailure (with HideExistence)NOT_FOUND: The requested item was not found.
ExceptionalFailure, alone or at any depth inside an AggregateFailure<code>: An unexpected error occurred. — exception messages can hold internals
ValidationFailure, alone or inside an AggregateFailure (with ListValidationErrors)<code>: Some fields are not valid. then one line per error (see below)
Anything else<code>: <message>

The rows apply in this order, so existence hiding and exception hiding win over the validation list. The code is also in _meta under unambitiousfx.synapse/failureCode, so a client can branch on it without parsing the text.

Validation errors​

A ValidationFailure's own message joins the error messages without their fields, so an assistant cannot tell which argument to fix. With ListValidationErrors on (the default), each error gets its own line with its field and code:

orders.invalid_order: Some fields are not valid.
- lines[3].amount (request.amount): Must be positive.
- label (request.required): Required.
- At least one line is required.

An error without a field or a code is listed without them. For an AggregateFailure, the first line keeps the aggregate's code and message, and the errors of every ValidationFailure inside it are listed. The errors are also in _meta, so a client can read them without parsing the text:

{
"unambitiousfx.synapse/failureCode": "orders.invalid_order",
"unambitiousfx.synapse/errors": [
{ "field": "lines[3].amount", "code": "request.amount", "message": "Must be positive." }
]
}

A null field or code is left out of the object. Set ListValidationErrors = false to get the one-line <code>: <message> form back.

To change it, register your own policy. AddSynapseMcp uses TryAdd, so a policy registered before it wins; one registered after it with AddSingleton replaces it too.

public sealed class LoanFailurePolicy(IOptions<SynapseMcpOptions> options) : IMcpFailurePolicy
{
private readonly DefaultMcpFailurePolicy _default = new(options);

public CallToolResult ToToolError(Failure failure) => failure switch
{
ConflictFailure => new CallToolResult
{
IsError = true,
Content = [new TextContentBlock { Text = "CONFLICT: someone changed this loan; read it again first." }]
},
_ => _default.ToToolError(failure)
};
}

builder.Services.AddSingleton<IMcpFailurePolicy, LoanFailurePolicy>();
builder.Services.AddSynapseMcp();

Context propagation​

MCP has no headers. Out-of-band request data travels in params._meta, which is where W3C traceparent, tracestate and baggage go. McpMetaPropagationCarrier is the IPropagationCarrier over it, the MCP counterpart of HttpRequestPropagationCarrier. Use it in a call-tool filter so the tool's request continues the client's flow:

builder.Services.AddMcpServer()
.WithRequestFilters(filters => filters.AddCallToolFilter(next => async (context, ct) =>
{
var store = context.Services!.GetRequiredService<IInboundContextStore>();
var propagator = context.Services!.GetRequiredService<IContextPropagator>();
store.Inbound = propagator.Extract(new McpMetaPropagationCarrier(context.Params!));
return await next(context, ct);
}))
.WithTools<LoanTools>();

The filter runs in the same request scope as the tool, so IContext.TraceId in the handler is the client's trace id.

warning

_meta is chosen by the client. Adopt it only from clients you trust with your trace identity. The trace id is a correlation label, never an authorization input.

See also​