APIs

Build HTTP APIs with controllers, route attributes, streaming responses, and MCP Tools.
Framework Docs Menu

An API Package provides HTTP endpoints. It is mounted at the route set in its configuration (or the .defaultRoute in its manifest), and its controller methods handle requests under that route.

GET /api/example/M001?units=mm
Configuration routeroute: /api/example picks the API
/api/example → this API
Endpoint attribute[ApiGet("{key}")] picks the method; its route is relative to the API's route
M001 → {key}
Your methodGet([FromRoute] string key, [FromQuery] string units)
key = "M001", units = "mm"
ResponseOk(value) → 200 with text or JSON
An [ApiStream] method instead returns a stream of responses, over a WebSocket or Server-Sent Events
The same endpoint can also be offered to AI assistants as an MCP Tool with [ApiMcpTool].

Create an API

dotnet new trakhound.api

The template creates a controller that inherits from TrakHoundApiController:

using TrakHound;
using TrakHound.Api;

public class Controller : TrakHoundApiController
{
    [ApiGet]
    public async Task<TrakHoundApiResponse> Get([FromQuery] string name)
    {
        return Ok($"Hello {name}");
    }

    [ApiGet("{key}")]
    public async Task<TrakHoundApiResponse> GetValue([FromRoute] string key)
    {
        var value = await Variables.ReadString(key);
        return Ok(value);
    }

    [ApiPut("{key}")]
    public async Task<TrakHoundApiResponse> PutValue([FromRoute] string key, [FromQuery] string value)
    {
        await Variables.Set(key, value);
        return Ok();
    }
}

If this API is configured with the route /api/example, the endpoints are:

GET  /api/example?name=World
GET  /api/example/{key}
PUT  /api/example/{key}?value=...

Route Attributes

Add an attribute to each method to set its HTTP method and route. The route is relative to the API's route and can contain parameters in braces.

AttributeHTTP Method
[ApiGet]GET
[ApiPost]POST
[ApiPut]PUT
[ApiDelete]DELETE
[ApiPatch], [ApiHead], [ApiOptions], [ApiConnect], [ApiTrace]PATCH, HEAD, OPTIONS, CONNECT, TRACE
[ApiStream]A streaming endpoint (see below)

Parameters

AttributeReads the value from
[FromQuery]The query string (ex. ?name=World)
[FromRoute]A route parameter (ex. {key})
[FromHeader]A request header (ex. [FromHeader("X-Line")], or the parameter name when none is set). Names are case-insensitive, and a missing header leaves the parameter's default
[FromBody]The request body. An optional content type can be set (ex. [FromBody(ContentType = "application/json")])

Headers that carry the caller's credentials (Cookie, Authorization, Proxy-Authorization, X-API-Key, X-TrakHound-Module-Token, and token) are never passed to an API, so it can't act as its caller. Header parameters are listed in the OpenAPI document as in: header and left out of MCP Tool inputs. Apps send headers with Client.Api.Send and the Get, Post, Put, Delete, and Stream overloads that take headers.

Describe each parameter with Description. Descriptions appear in the admin UI, the OpenAPI document, the API Catalog, and MCP Tool inputs:

[ApiGet("production")]
public async Task<TrakHoundApiResponse> GetProduction(
    [FromQuery(Description = "The first day to include")] DateTime start,
    [FromQuery(Description = "The last day to include")] DateTime end)

Responses

Methods return a TrakHoundApiResponse. The controller provides helpers for common status codes. Each accepts nothing, a string (text/plain), an object (serialized as JSON), or bytes with a content type.

HelperStatus Code
Ok()200
Created()201
Accepted()202
Redirect(location, statusCode = 303)303 (or the given status code)
BadRequest()400
NotAuthorized()401
NotFound()404
InternalError()500
File(content, contentType, filename)200 with a file download (bytes or stream)

Streaming

A method marked with [ApiStream] returns an ITrakHoundStream<TrakHoundApiResponse>. Push responses into the stream as data becomes available, and clean up when the client disconnects:

[ApiStream]
public async Task<ITrakHoundStream<TrakHoundApiResponse>> Stream()
{
    var timer = new System.Timers.Timer(1000);
    var stream = new TrakHoundStream<TrakHoundApiResponse>();

    timer.Elapsed += (s, args) => stream.Push(Ok(DateTime.Now.ToString("o")));
    timer.Start();

    // Called when the client disconnects
    stream.OnDisposed = () => timer.Dispose();

    return stream;
}

Clients connect to a stream endpoint with a WebSocket, or with Server-Sent Events: a GET request with Accept: text/event-stream (ex. a browser EventSource) receives each value as a data event. Server-Sent Events only go from the server to the client, so input from the client needs a WebSocket.

curl -N -H "Accept: text/event-stream" http://localhost:8472/api/example/stream

MCP Tools

Mark an endpoint with [ApiMcpTool] to offer it to AI assistants as a Tool of the Instance's MCP Server. Write the Description for an AI agent, and only mark endpoints that are safe for an agent to call:

[ApiGet("status")]
[ApiMcpTool(Description = "Returns the current status")]
public async Task<TrakHoundApiResponse> GetStatus()
{
    return Ok("OK");
}

GET and stream endpoints are read only. Set ReadOnly = true on another method that only reads (ex. a POST search), or Destructive = true on one that deletes data or affects equipment. See API Endpoints as Tools.

Permissions

Add [TrakHoundPermission("read")] (one or more) to an endpoint so administrators can control who calls it with security profiles. Each endpoint is a resource named api:{apiId}:{controllerId}:{endpointId}. See Security.

Controller Properties

PropertyDescription
ClientClient used to call other APIs, run Functions, and read and write Services.
Volume, VariablesThe module's Volume and Variables.
ConfigurationThe API's configuration. Read parameters with Configuration.GetParameter(name).
GetConfigurationVariable(name)Reads a Configuration Variable shared by every configuration in the profile.
PackageInformation about the Package.
InstanceId, BaseUrl, BasePathThe Instance ID and the API's base URL and path.
LoggerLogger for the API. Also available through Log(level, message).

Override OnInitialize() or OnInitializeAsync() to run setup code when the controller is created.

Grouping and Documentation

Use [TrakHoundApiController(route, name, description)] on a controller class to set its route, name, and description, and [TrakHoundApiResponse(statusCode, returnType)] on a method to describe its responses. This information is shown in the Instance's admin UI Explorer, where endpoints can also be run.

Each API also gets an OpenAPI document at _api/openapi/{apiId}, linked from its page in the admin UI. Developers without admin access can find the APIs and endpoints they are allowed to call in the API Catalog.

Configuration

Besides its route, an API configuration can set httpEnabled: false to serve the API only to other modules inside the Instance, and mcpTools to choose which endpoints are MCP Tools. Routes used by the Instance itself (such as /_admin) are reserved and can't be used by APIs. See Configuration.