Extending¶
This page covers the SDK's extension points: modules, stages and their fixed order, tool sources, FadenstackTransport, and the client modules an agent can require.
Modules¶
A module is a package that plugs into the builder. It implements IFadenstackModule:
builder.Use(module) calls Configure, where the module adds its stages, tool sources or tools. Fadenstack.Mcp is such a module: AddLocalMcp adds a LocalMcpModule, named mcp.local.
A module is active only when it is referenced and added to the builder, never just by being installed.
Required client modules¶
An agent's profile on the server can list client modules the agent needs (required_client_modules). When the agent starts, every listed name must be the Name of a module added with Use. Otherwise StartAsync throws FadenstackException, naming the missing modules, and no session starts.
A module whose Name is null can be added, but it cannot satisfy a requirement.
using Fadenstack.Agents;
public sealed class AuditModule : IFadenstackModule
{
public string? Name => "example.audit";
public void Configure(AgentBuilder builder) =>
builder.AddToolStage(StageOrder.Custom, new ToolLogStage());
}
Stages¶
Stages wrap the agent's work. There are two kinds:
AddChatStage(order, wrap)wraps theIChatClientthat carries the agent's requests to the gateway.wrapgets the inner client and returns the client that wraps it, usually a Microsoft.Extensions.AIDelegatingChatClient.AddToolStage(order, stage)wraps each tool call. AnIToolStagesees the call before the tool runs and the result after.
The order is fixed¶
Stages run in the order of their order value, whatever order they are added in. A module picks its slot, not its position in the builder chain. StageOrder names the slots:
| Constant | Slot |
|---|---|
StageOrder.Context |
Context added to a request. |
StageOrder.Pii |
Personal data masked on the device. |
StageOrder.Provenance |
Content marking: the turn's receipts, and the check that tools mark what they place. |
StageOrder.Custom |
Your own stages. |
A lower value sits further from the transport. A request passes the stages from the lowest value to the highest and then goes to the gateway: context first, then masking, then custom stages. A tool call passes them in the same order on the way to the tool, and the result comes back through them in reverse. Give each of your stages its own value when their order matters.
Tool stages run after the approval: the agent decides first whether a call may run, and only calls that run reach the stages.
A chat stage¶
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Microsoft.Extensions.AI;
public sealed class TimingStage : DelegatingChatClient
{
public TimingStage(IChatClient inner) : base(inner)
{
}
public override async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(
IEnumerable<ChatMessage> messages, ChatOptions? options = null,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
var watch = Stopwatch.StartNew();
await foreach (var update in base.GetStreamingResponseAsync(messages, options, cancellationToken))
{
yield return update;
}
Trace.WriteLine($"Model call took {watch.Elapsed}.");
}
}
The agent streams every request, so a chat stage overrides GetStreamingResponseAsync.
A tool stage¶
using System.Diagnostics;
using Fadenstack.Agents;
public sealed class ToolLogStage : IToolStage
{
public async Task<object?> InvokeAsync(ToolInvocation invocation, ToolInvoker next, CancellationToken cancellationToken)
{
Trace.WriteLine($"{invocation.Tool.Name} ({invocation.Class}) starts.");
try
{
return await next(invocation, cancellationToken);
}
finally
{
Trace.WriteLine($"{invocation.Tool.Name} ended.");
}
}
}
A ToolInvocation carries the Tool, the model's Call, the Arguments the tool gets (a stage may change them, for example to put masked values back), the tool's Class, the SessionId and TurnId, and the Agent it runs in. Call next to go on to the next stage and finally the tool; what you return is the tool's result.
A stage can also:
- get the call's tool services with
GetService<T>(): the same instance the tool gets (see Services a call gets; a module adds them withbuilder.AddToolService<T>(factory)); - write an entry of its own type into the session's transcript with
RecordAsync(type, data), such asprovenance.placed. The SDK's own entry types are refused, since they make the history the model gets; keep content out of the data; - tell the user something about the call with
NoticeAsync(notice): it goes into the turn's notices and the transcript, and raises aNoticeRaisedevent.
Tool sources¶
An IToolSource adds tools once the agent's profile is known, for example tools that depend on the agent's policy:
public interface IToolSource
{
Task<IReadOnlyList<AgentTool>> GetToolsAsync(AgentContext context, CancellationToken cancellationToken);
}
Add one with builder.AddToolSource(source). The AgentContext gives the source the Client, the agent's Profile and ReportAsync, which reports an activity event to the server (names and counts, never content). A host tool wins over a source's tool of the same name. A source that implements IDisposable is disposed with the agent.
An AgentTool wraps an AIFunction with its class, its Source (host or mcp), the Server label of an MCP tool, and whether it reaches outside the organisation.
Tool sources that change¶
Some sources have tools that come and go: a server that adds or drops a tool, a setting that switches a group of tools on or off. Such a source implements IChangingToolSource, which adds one event:
Raise Changed, from any thread, when GetToolsAsync would now answer differently. The agent listens from its start. It asks a source again at the start of the next turn, never inside a turn, and settles the answer by the same rules as at start: a host tool wins over a source's tool of the same name, and the agent's contract sets the class. From then on agent.Tools and the model's requests show the new list. A source that did not raise Changed is not asked again. If asking again fails, the agent keeps the tools it had and writes a warning (event 2014). A model that calls a tool that went away is told "(name) is no longer available." The agent stops listening when it is disposed. LocalMcpModule is a changing source.
Tools in scope per conversation¶
A tool source can decide, per conversation, which of its tools the model is offered. Set AgentTool.Scope to an IToolScope:
public interface IToolScope
{
bool Offers(AgentTool tool, ChatSession session);
string? BeforeCall(AgentTool tool, ChatSession session);
}
Offers says whether the model gets the tool in this session's requests now; a tool without a Scope is always offered. A tool that is not offered can still be called by name. BeforeCall runs before the call is approved or run: it returns the text that answers the call instead, or null to run it. Both can be called from any thread. This is how the local MCP module brings its tools in only when the model asks for them (Tools on request). A minimal scope that offers a tool once the model has called it:
using System.Collections.Concurrent;
using Fadenstack.Agents;
public sealed class AskedForScope : IToolScope
{
private readonly ConcurrentDictionary<(string Session, string Tool), bool> _on = new();
public bool Offers(AgentTool tool, ChatSession session) => _on.ContainsKey((session.Id, tool.Name));
public string? BeforeCall(AgentTool tool, ChatSession session) =>
_on.TryAdd((session.Id, tool.Name), true)
? $"{tool.Name} is now switched on. Call it again with its parameters."
: null;
}
FadenstackTransport¶
client.Transport makes authenticated requests to the server with the client's tokens, TLS settings and typed errors. Use it to add requests the SDK does not cover yet, without copying the plumbing:
using Fadenstack.Http;
using Fadenstack.Models;
var transport = client.Transport;
var features = await transport.GetAsync<ServerFeatures>(transport.Gateway("v1/features"));
| Member | Meaning |
|---|---|
Gateway(relative), Api(relative) |
The URL of a gateway route (/v1) or a backend route (/api). |
GetAsync<T>, PostAsync<T>, PutAsync<T>, PatchAsync<T>, DeleteAsync |
JSON in, JSON out, errors as typed exceptions. |
SendJsonAsync<T>(method, url, body) |
The same, for any method. |
SendAsync(build, completion, cancellationToken) |
Any request. build creates the request; it is called again for the one retry after a 401. |
ServerUrl, ApiUrl, Timeout, HttpClient |
The client's settings. |
CreateHandler(options) |
A handler with the client's TLS settings, for your own requests to the same server. |
Requests carry the bearer token. When the server answers 401, the transport gets a fresh token and retries once. JSON uses the server's snake_case names; FadenstackJson.Options holds the serializer options.