Skip to main content

Bending Aspire to your will - Run a test call from the dashboard, the CLI and your agent

I spend a lot of time testing and debugging APIs, and so do my AI agents. Lately I notice that my agents lose time and tokens on it. They look for the right port, guess at endpoints, fight with a terminal, and try to get the database back into a known state. Every run starts with the same detective work.

So for this series of posts I picked one scenario and I’m sticking with it: the API-testing loop. The goal is to adapt Aspire so that I (and my agents) can debug and test easily and efficiently.

Part 1 gave me an export button for the OpenAPI spec. Now the next step in the loop: firing a test call at an endpoint. To check one endpoint I open a REST client, look up the port and type the URL. Again. My agents do the same, only they pay for it in tokens.

Note: this post is part of a series about the demos from my session “Bending Aspire to your will”.

The test call I want to make is simple: retrieve the products of the catalog service for a given brand. The endpoint is /api/v1/catalog/items/type/all/brand/{brandId}. What I want is a command that asks for the brand ID, calls the endpoint and shows me the JSON.


A command that returns a result

Part 1 used WithProcessCommand to wrap curl. This time I don't need an external process. WithCommand lets you run your own C# code and return a result to the caller:

var catalogEndpoint = catalogService.GetEndpoint("http");

catalogService.WithCommand(
    name: "retrieve-products",
    displayName: "Retrieve products",
    executeCommand: async context =>
    {
        var brandId = context.Arguments.GetInt32("brandId");
        var path = $"/api/v1/catalog/items/type/all/brand/{brandId.ToString(CultureInfo.InvariantCulture)}";

        try
        {
            using var client = new HttpClient();
            using var response = await client.GetAsync(new Uri(new Uri(catalogEndpoint.Url), path), context.CancellationToken);
            if (!response.IsSuccessStatusCode)
            {
                return CommandResults.Failure($"Catalog service returned HTTP {(int)response.StatusCode} ({response.ReasonPhrase}).");
            }

            var json = await response.Content.ReadAsStringAsync(context.CancellationToken);
            return CommandResults.Success(
                message: "Products retrieved for brand " + brandId + ".",
                result: json,
                resultFormat: CommandResultFormat.Json);
        }
        catch (HttpRequestException ex)
        {
            context.Logger.LogError(ex, "Failed to retrieve products for brand {BrandId}.", brandId);
            return CommandResults.Failure($"Failed to retrieve products for brand {brandId}: {ex.Message}");
        }
        catch (OperationCanceledException) when (!context.CancellationToken.IsCancellationRequested)
        {
            return CommandResults.Failure($"The catalog service request for brand {brandId} timed out.");
        }
    },
    // commandOptions: see next section
);

Three things matter here:

  • Forward the CancellationToken. If someone cancels the command, the HTTP call stops too.
  • Fail with a message a human can act on. CommandResults.Failure shows up in the dashboard. "Catalog service returned HTTP 404 (Not Found)" tells you more than a generic error.
  • Return a structured result. With CommandResultFormat.Json the dashboard shows the response as formatted JSON, and callers like the CLI or an agent get it as data.

Remark: I create a new HttpClient per call. For a demo that's fine. In a long-running AppHost you may want to reuse one.

Ask for input and validate it

The command needs a brand ID. You declare that as an input on the command options:

commandOptions: new CommandOptions
{
    Arguments =
    [
        new InteractionInput { Name = "brandId", Label = "Brand ID", InputType = InputType.Number, Required = true },
    ],
    ValidateArguments = context =>
    {
        var brandId = context.Inputs.GetInt32("brandId");
        if (brandId <= 0)
        {
            context.AddValidationError("brandId", "Brand ID must be a positive number.");
        }

        return Task.CompletedTask;
    }
});

When you click the button, the dashboard shows a form with a number field. ValidateArguments runs before the command executes, so a brand ID of 0 is rejected without a single HTTP call.


One command, three front doors

The nice part is that I only wrote this once. The same command is available from:

  • The dashboard: the "Retrieve products" button on the catalog service
  • The CLI: aspire resource <resource> <command>
  • MCP: the execute_resource_command tool of the Aspire MCP server

That last one is why I'm doing this. An agent no longer has to find the port, guess the URL or write a curl call. It sees a command with a name and a typed input, and it gets JSON back. It's less guessing, so fewer tokens.


Remark: the dashboard asks for input through a form. On the command line and via MCP, the arguments have to be supplied by the caller. Not every interaction is available on every surface, so test the command in each of them.

That's it! The test call lives in the AppHost now, next to the resource it belongs to. In the next part, I'll tackle the third step of the loop: resetting the state so every test run starts clean.

More information

Popular posts from this blog

Podman– Command execution failed with exit code 125

After updating WSL on one of the developer machines, Podman failed to work. When we took a look through Podman Desktop, we noticed that Podman had stopped running and returned the following error message: Error: Command execution failed with exit code 125 Here are the steps we tried to fix the issue: We started by running podman info to get some extra details on what could be wrong: >podman info OS: windows/amd64 provider: wsl version: 5.3.1 Cannot connect to Podman. Please verify your connection to the Linux system using `podman system connection list`, or try `podman machine init` and `podman machine start` to manage a new Linux VM Error: unable to connect to Podman socket: failed to connect: dial tcp 127.0.0.1:2655: connectex: No connection could be made because the target machine actively refused it. That makes sense as the podman VM was not running. Let’s check the VM: >podman machine list NAME         ...

Cache stampede: when our cache turned against us

While investigating some performance issues, we ran into an ASP.NET Core API that cached a fairly expensive aggregation query for 60 seconds. Under normal load, that was fine: one request rebuilds the cache, everyone else reads from it. Under peak load, dozens of requests would arrive in that same expiry window, all see a cache miss, and all fire the same expensive query in parallel. The database didn't like that. That was the moment when our caching layer stopped helping and started hurting. A burst of requests comes in at the same time, all miss the cache, and all go hammer the database or the downstream API at once. That's a cache stampede . The cache was supposed to protect our backend, and for a few hundred milliseconds it did the opposite. Why this happens IMemoryCache.GetOrCreate (and its async sibling) looks like it protects you, but it doesn't add any locking on its own. Look at the naive version: public async Task<Report> GetReportAsync(string key) ...

VS Code Planning mode

After the introduction of Plan mode in Visual Studio , it now also found its way into VS Code. Planning mode, or as I like to call it 'Hannibal mode', extends GitHub Copilot's Agent Mode capabilities to handle larger, multi-step coding tasks with a structured approach. Instead of jumping straight into code generation, Planning mode creates a detailed execution plan. If you want more details, have a look at my previous post . Putting plan mode into action VS Code takes a different approach compared to Visual Studio when using plan mode. Instead of a configuration setting that you can activate but have limited control over, planning is available as a separate chat mode/agent: I like this approach better than how Visual Studio does it as you have explicit control when plan mode is activated. Instead of immediately diving into execution, the plan agent creates a plan and asks some follow up questions: You can further edit the plan by clicking on ‘Open in Editor’: ...