microsoft/aspire · error · InvalidOperationException

Foundry CLI command ' ' exited before producing required…

Error message

Foundry CLI command '{command}' exited before producing required output with exit code {process.ExitCode}: {incompleteError}{incompleteOutput}

What it means

During Foundry service startup (stopReadingAfterProcessExit=true), RunProcessAsync waits for the daemonizing `foundry` start command to exit and to emit the required endpoint line. If both output streams close (the process exited) before the endpoint/completion predicate matched, this InvalidOperationException is thrown with the captured partial output and exit code. It means the CLI terminated without ever reporting a service endpoint.

Solutions

  1. Inspect the exit code and partial output in the message; run `foundry service start` manually to see the real startup error.
  2. Check for port conflicts or a stale/hung Foundry service: `foundry service status`, stop it (`foundry service stop`) and retry.
  3. Update the Foundry Local CLI — older versions may not emit the endpoint line this integration parses.
  4. Look for machine-level issues in the output: GPU driver errors, out-of-memory, or missing prerequisites, and fix them before restarting.
  5. Clear/reinitialize local Foundry state if the service is stuck in a bad state, then start the service again.

Example fix

// before: stale service blocks startup and the CLI exits without an endpoint
// after: reset the service before starting the app host
// $ foundry service stop
// $ foundry service status
// $ foundry service start   # confirm 'Service is Started on http://...'
// $ dotnet run --project MyApp.AppHost
Defensive patterns

Strategy: try-catch

Validate before calling

// Before launching the AppHost, confirm the service can start cleanly:
//   foundry service stop; foundry service start; foundry service status
var psi = new ProcessStartInfo("foundry", "service status") { RedirectStandardOutput = true, UseShellExecute = false };
using var p = Process.Start(psi)!;
var status = await p.StandardOutput.ReadToEndAsync();
bool serviceHealthy = status.Contains("running", StringComparison.OrdinalIgnoreCase);

Try / catch

try
{
    await foundryResource.StartAsync();
}
catch (InvalidOperationException ex) when (ex.Message.Contains("exited before producing required output"))
{
    logger.LogError(ex, "Foundry CLI exited without reporting an endpoint: {Message}", ex.Message);
    // Inspect the embedded exit code/output, fix the root cause, then retry.
}

Prevention

When it happens

Trigger: StartCliServerAsync -> RunFoundryCommandCoreAsync -> RunProcessAsync with stopReadingAfterProcessExit=true, when the foundry server-start process exits (success or failure) without a line matching the endpoint completion predicate, e.g. 'Service is Started on <url>'.

Common situations: Foundry service fails at startup due to port conflicts, missing runtime dependencies, or corrupt local state; an outdated CLI version whose startup banner no longer matches the expected format; the service dies immediately after spawn (GPU/driver issues, insufficient resources); another Foundry instance crashed leaving stale state.

Understand the failure class

Background: ECONNREFUSED and "connection refused" / "could not connect to server" errors: what they mean and how to fix them — this error's family across 44 libraries.

Related errors


AI-assisted analysis of microsoft/aspire@25830f84bd (2026-09-16). Data as JSON: /api/errors/040f9ffc13465cd0. Report an issue: GitHub.

Appendix: source

Thrown at src/Aspire.Hosting.Foundry/FoundryLocalService.cs:443

            using var startCancellationRegistration = startCancellation.Token.Register(static state => KillProcess((Process)state!), process);

            try
            {
                // The modern "server start" command daemonizes, and the daemon inherits the CLI's
                // redirected stream handles. Wait until the parent exits and reports its endpoint,
                // then stop draining instead of waiting forever for EOF from the daemon. If both
                // streams close first, the CLI exited without producing the required endpoint.
                await process.WaitForExitAsync(startCancellation.Token).ConfigureAwait(false);
                var readersCompletionTask = Task.WhenAll(outputTask, errorTask);
                var completedTask = await Task
                    .WhenAny(outputCompletionSource.Task, readersCompletionTask)
                    .WaitAsync(startCancellation.Token)
                    .ConfigureAwait(false);
                if (completedTask == readersCompletionTask && !outputCompletionSource.Task.IsCompleted)
                {
                    var incompleteOutput = await outputTask.ConfigureAwait(false);
                    var incompleteError = await errorTask.ConfigureAwait(false);
                    throw new InvalidOperationException(
                        $"Foundry CLI command '{command}' exited before producing required output with exit code {process.ExitCode}: {incompleteError}{incompleteOutput}");
                }
            }
            catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
            {
                throw new TimeoutException($"Timed out waiting for Foundry CLI server startup after {s_serviceStartTimeout}.");
            }
            finally
            {
                readCancellation.Cancel();
                await Task.WhenAll(outputTask, errorTask).ConfigureAwait(false);
            }
        }
        else
        {
            await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
        }

View on GitHub (pinned to 25830f84bd)