How to Use the CodexBar Serve HTTP API for External Integrations
The CodexBar serve HTTP API exposes a lightweight, loopback-only server via the codexbar serve command, enabling local scripts and applications to query usage data and trigger refreshes through JSON endpoints strictly bound to localhost connections.
CodexBar ships with a built-in HTTP server designed specifically for local automation, allowing external tools to access real-time usage data without exposing sensitive information to the network. The server implementation resides in CLILocalHTTPServer.swift while the routing logic and endpoint definitions live in CLIServeCommand.swift, creating a secure bridge between the CLI and third-party integrations.
Architecture and Security Model
The CodexBar serve HTTP API operates as a TCP socket server that defaults to 127.0.0.1:0, automatically selecting a free ephemeral port to avoid collisions. According to the source in CLILocalHTTPServer.swift, every incoming connection first undergoes validation through CLILocalHTTPRequest.parse before reaching the handler closure defined in CLIServeCommand.swift.
Loopback-Only Enforcement
Security is enforced by the isAllowedLoopbackHost method (implemented around lines 83-110 in CLILocalHTTPServer.swift), which inspects the Host header of every request. This function explicitly rejects any connection that does not resolve to 127.0.0.1, localhost, or [::1], ensuring the API remains inaccessible from external networks regardless of firewall configuration. This design prevents accidental exposure while still allowing tunneling via SSH or reverse proxies for legitimate remote access scenarios.
Available Endpoints
The router registered in CLIServeCommand.swift exposes four primary JSON endpoints:
- GET
/usage– Returns current provider statistics including consumed tokens, limits, and utilization percentages. - GET
/status– Provides a minimal health payload containing the provider name, version identifier, and operational flag. - POST
/refresh– Triggers an immediate synchronization with the provider API, ensuring subsequent queries return up-to-date data. - GET
/token– Exposes the current access token only when the CLI is invoked with the--expose-tokenflag, requiring explicit opt-in to prevent credential leakage.
Unit tests in CLIServeRouterTests.swift validate these routes, ensuring proper HTTP method restrictions (returning 405 for invalid verbs) and correct JSON payload structures.
Integration Steps
1. Start the Server
Launch the HTTP daemon as a background process:
# Auto-select a random port (recommended for CI/CD environments)
codexbar serve &
# Or bind to a specific port
codexbar serve --port 8080 &
When using the default port 0, the server outputs the assigned endpoint to stdout: Codex Bar HTTP server listening on 127.0.0.1:53412.
2. Discover the Port
Capture the port number from the console output or read the CODX_BAR_HTTP_PORT environment variable, which the CLI automatically exports for child processes.
3. Query from Shell Scripts
Use standard HTTP clients to retrieve data:
curl -s http://127.0.0.1:${CODX_BAR_HTTP_PORT}/usage | jq .
Typical response structure:
{
"provider": "OpenAI",
"model": "gpt-4",
"usedTokens": 12345,
"limitTokens": 400000,
"percentage": 3.1
}
4. Consume from Swift Applications
Implement a native client using URLSession:
import Foundation
struct Usage: Decodable {
let provider: String
let model: String
let usedTokens: Int
let limitTokens: Int
let percentage: Double
}
func fetchUsage(from port: UInt16) async throws -> Usage {
let url = URL(string: "http://127.0.0.1:\(port)/usage")!
let (data, _) = try await URLSession.shared.data(from: url)
return try JSONDecoder().decode(Usage.self, from: data)
}
// Usage example
let usage = try await fetchUsage(from: 8080)
print("Current utilization: \(usage.percentage)%")
5. Trigger Refresh Cycles
Force an immediate data update before querying:
curl -X POST -s http://127.0.0.1:${CODX_BAR_HTTP_PORT}/refresh
6. Shutdown Procedures
The server terminates automatically when the parent codexbar process exits. For programmatic control, invoke the stop() method on the CLILocalHTTPServer instance, or send SIGINT/SIGTERM to the process ID.
Practical Automation Examples
Monitor usage in a polling loop:
#!/bin/bash
codexbar serve --port 8080 &
sleep 2
while true; do
percentage=$(curl -s http://127.0.0.1:8080/usage | jq -r '.percentage')
echo "Token usage: ${percentage}%"
if (( $(echo "$percentage > 90" | bc -l) )); then
echo "WARNING: Approaching limit"
fi
sleep 60
done
Integrate into a Swift build tool:
import Foundation
@main
struct StatusChecker {
static func main() async throws {
let port = UInt16(ProcessInfo.processInfo.environment["CODX_BAR_HTTP_PORT"] ?? "8080")!
let url = URL(string: "http://127.0.0.1:\(port)/status")!
let (data, _) = try await URLSession.shared.data(from: url)
print(String(data: data, encoding: .utf8)!)
}
}
Summary
- CodexBar serve HTTP API provides a localhost-only server via
codexbar serve, exposing usage data through JSON endpoints at/usage,/status,/refresh, and optionally/token. - Security is enforced by
isAllowedLoopbackHostinCLILocalHTTPServer.swift, which rejects any non-loopback connection to prevent network exposure. - Integration requires starting the server, capturing the port from stdout or the
CODX_BAR_HTTP_PORTenvironment variable, and issuing standard HTTP requests to127.0.0.1. - Core implementation files include
CLILocalHTTPServer.swiftfor socket handling,CLIServeCommand.swiftfor routing logic, andCLIServeRouterTests.swiftfor behavior validation.
Frequently Asked Questions
How do I expose the CodexBar serve API to remote machines?
You cannot disable the loopback restriction; the isAllowedLoopbackHost check in CLILocalHTTPServer.swift explicitly blocks non-localhost addresses. For remote access, establish an SSH tunnel using ssh -L 8080:127.0.0.1:8080 remote-host or route traffic through a reverse proxy with authentication.
Why does the server default to a random port?
The default configuration uses 127.0.0.1:0 to prevent port conflicts when running multiple instances or parallel CI jobs. The CLI prints the assigned port and sets the CODX_BAR_HTTP_PORT environment variable for easy discovery by calling scripts.
How do I access the API token through the HTTP interface?
The /token endpoint is disabled by default to prevent credential leakage. Start the server with the --expose-token flag to enable this route, which then returns the current provider access token in the JSON response body.
What HTTP status codes does the API return for errors?
According to CLIServeRouterTests.swift, the server returns 404 for undefined routes, 405 for valid paths with invalid HTTP methods (such as POST to /usage), and 403 for requests that fail the loopback host validation. Successful requests return 200 with JSON content.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →