Use await using to close the child server’s standard input and give it a chance to exit.
dotnet add package RecursiveAI.OneModelContextRequires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.
using RecursiveAI.OneModelContext; // Pass the server DLL and its arguments. var pipe = ContextTransport.Process( "dotnet", args); await using (var client = await ModelContext.ConnectAsync(pipe)) { await client.ListToolsAsync(); } Console.WriteLine("Client disposed.");
args contains your server’s DLL path and any arguments it needs, for example ["MyServer.dll"]. Prints Client disposed. The downloadable example includes its own child server.
Unzip the example, then dotnet run.
The full program
The example starts a second copy of itself with the serve argument. The parent receives a tool list, leaves the await using block, and checks the child’s message on standard error. The child prints that message only after the server returns, without its cancellation deadline firing.
using RecursiveAI.OneModelContext; if (args is ["serve"]) { using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(30)); await ModelContext.ServeAsync(new ContextServer("Local", "1.0"), stop.Token); Console.Error.WriteLine(stop.IsCancellationRequested ? "Server stopped by cancellation." : "Server returned after EOF."); return; } var command = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet"; var dll = typeof(Program).Assembly.Location; string? shutdown = null; var transport = ContextTransport.Process(command, [dll, "serve"], new ProcessTransportOptions { StandardErrorHandler = line => shutdown = line }); using var shutdownRequest = new CancellationTokenSource(); try { await using var client = await ModelContext.ConnectAsync(transport); await client.ListToolsAsync(); Console.WriteLine("Tool list received."); if (args is ["cancel"]) shutdownRequest.Cancel(); shutdownRequest.Token.ThrowIfCancellationRequested(); } catch (OperationCanceledException) when (shutdownRequest.IsCancellationRequested) { Console.WriteLine("Client workflow canceled."); } if (shutdown != "Server returned after EOF.") throw new InvalidOperationException("The server did not report a normal EOF shutdown."); Console.WriteLine(shutdown); Console.WriteLine("Client disposed.");
Tool list received. Server returned after EOF. Client disposed.
If a child does not exit during the process transport’s grace period, the transport tries to stop the child process tree forcibly.
Variations
Raise the client’s ShutdownGrace if it stops the child too soon; raise the server’s EndOfStreamTimeout if it cancels handlers too soon after end-of-file (EOF). To give the child more time to exit, set the process transport option:
new ProcessTransportOptions { ShutdownGrace = TimeSpan.FromSeconds(10) }
Run dotnet run -- cancel to cancel the parent’s workflow after it receives the tool list. The exception leaves the await using scope, and disposal still sends EOF. The output adds Client workflow canceled. before the child’s EOF message.
Related recipes
The short answer
Use await using around the ContextClient returned by ModelContext.ConnectAsync. For ContextTransport.Process, leaving that block closes the pipe to the child’s standard input and waits for the child to exit. This is a whole-connection shutdown, not a request to stop one tool.
How do I gracefully shut down a child process in C#?
With standard input and output as the transport, the ordinary shutdown signal is end-of-file on the child’s input. The client closes its writing end of the pipe. The server can still write replies even though no new messages can arrive. OneModelContext drains the child’s standard output while waiting, so a child finishing a write isn’t blocked on a pipe that nobody reads. This also means diagnostics should go to standard error, leaving standard output for protocol messages only.
The process transport implementation closes input before trying to kill the child. Start your shutdown by awaiting disposal rather than calling a process kill API yourself. If the forced step was needed, disposal still completing is not proof that the server finished its work. The example uses a message from the child to tell the two cases apart.
What does graceful shutdown mean for an in-flight request?
On input EOF, OneModelContext’s server lets handlers it has already admitted finish and drains queued replies. Server-side EndOfStreamTimeout defaults to five seconds; the server then cancels outstanding handlers and has a further bounded shutdown wait. A reader that stops draining output can lose the last reply. The process transport separately waits five seconds by default before its forced step, so giving the server more grace alone won’t give the child more time to exit. See EOF and shutdown.
If your application needs the result of a request, await that result before disposing the client, as the snippet does with ListToolsAsync. Use the cancellation token on the connection call to bound startup, or the token on a tool call when you want to cancel that call without deliberately closing the client. The server’s ServeAsync also accepts a host-side token. Explicit cancellation skips the EOF handler grace period, but don’t use a token as a substitute for closing the child’s input pipe. Neither of those server or request controls substitutes for disposing the client you own.