Building a Dynamic CLI from an API Discovery Service: Implementation and Operational Considerations

    This article explains how a CLI can read command definitions from an API discovery service at runtime instead of hard-coding endpoints, parameters, and authentication rules. It covers applicability, metadata structure, caching and fallback behavior, command-tree generation, parameter validation, permission filtering, auditing, and a practical implementation checklist.

    Traditional command-line tools hard-code each cloud API’s endpoints, parameters, and authentication rules into static code. When a service changes, the CLI must be recompiled, tested, and released. For cloud platforms with hundreds of services, this approach also increases executable size and slows startup.

    A dynamic approach based on an API discovery service changes this. The CLI keeps only generic parsing, request, and authentication logic; the available commands are read from the discovery service at runtime. This reduces the work of writing adapter code for each interface, but it does not eliminate all maintenance costs. The following sections describe its prerequisites, key workflow, and common risks.

    1. Applicability and Boundaries

    Dynamic construction is not suitable for every scenario. Its benefits are clear only when the following conditions are largely met:

    1. Cloud services can describe endpoints, methods, parameters, and permissions in a machine-readable format, usually JSON.
    2. The metadata specification remains stable for a period, or has an explicit version number and compatibility policy.
    3. Someone on the team continuously maintains the CLI engine itself. After the engine is upgraded, older metadata must still be parsed correctly.
    4. The server always performs complete authorization and parameter validation for every request. CLI-side filtering and validation only improve the user experience; they cannot replace server-side security controls.

    If a service has no structured interface description, or its interfaces change extremely frequently without version management, a statically generated SDK or handwritten commands may be easier to maintain.

    2. Metadata Structure of the Discovery Service

    A discovery service usually returns a JSON document. The fields the CLI needs to focus on are as follows:

    Field Meaning Required (document contract) Role for CLI
    version Metadata specification version Yes Determine whether the CLI can parse the document
    service Service name Yes Use as the root node of the command tree
    baseUrl Base access URL Yes Assemble the full request URL
    resources Resource groups Yes Generate second-level commands
    methods Operations under a resource Yes Generate third-level commands
    httpMethod GET, POST, PUT, etc. Yes Determine the request method
    parameters Parameter type, required flag, default value, and regex rule No Parameter parsing and upfront validation
    scopes OAuth scopes or roles required for the call No Command filtering and token selection

    When parsing, unknown fields should be ignored so that new fields added on the server side do not break older CLIs. If version is higher than the major version supported by the CLI, the CLI should reject the new document and prompt the user to upgrade rather than trying to guess its meaning.

    3. Runtime Fetching and Caching

    3.1 Authentication

    The discovery document itself may also require access credentials. If so, the CLI should use a token with read-only scope, read it from an environment variable or system key store, and not write it to configuration files or code. Cached documents should not contain tokens.

    3.2 Cache Update Steps

    1. Read the local cache, including the document content, document hash (or ETag), fetch time, and expiry time.
    2. If the cache has not expired (within the TTL), use the cache directly and do not make a network request. The TTL should be set according to the service change frequency, for example 10 minutes, and documented.
    3. If the cache has expired, send a conditional request with the saved hash or ETag.
    4. If the server returns 304, the document has not changed; refresh only the fetch time and expiry time.
    5. If the server returns 200, first validate the JSON structure and version, then write to a temporary file, and finally atomically replace the old cache. This avoids a corrupted cache if writing is interrupted halfway through.
    6. If any step fails, enter the fallback process.

    3.3 Fallback Order on Network Failure

    When the network is unavailable, the CLI should proceed in the following order:

    1. Online fetch succeeds: use the new document.
    2. Cache has not expired: use the cache directly.
    3. Cache has expired but still exists: allow read-only commands and warn in the output that “metadata may be stale.” Write operations are rejected outright to avoid incorrect operations caused by stale permission information.
    4. No usable cache exists: exit with an error and prompt the user to check the network or the discovery service address.

    The fallback strategy requires particular attention to permissions. An expired cache may still show permissions that the user has already lost. Therefore, an expired cache is suitable only for displaying and executing read-only commands; write operations must rely on online data.

    4. Generating the Command Tree

    4.1 Build Rules

    The engine traverses the document and generates command paths according to the hierarchy of service, resource, and method. For example, the objects resource and list method under storage-service correspond to the command storage-service objects list. If two resource names or method names conflict after conversion, the engine should report an error and identify the conflict location rather than arbitrarily overwriting one of them.

    4.2 Mapping Metadata to Requests

    Metadata field CLI element HTTP request element
    service + resources key names Command path None
    methods key name Subcommand name None
    parameters key names --parameter-name option Query parameter or request body field, depending on httpMethod
    parameters.type Type conversion rule Value format in request
    parameters.default Value when parameter is omitted Automatically filled into request
    httpMethod + path + baseUrl None Full request URL and method
    scopes Whether command is visible Required token scopes

    4.3 Pseudocode Example

    1. def build_command_tree(doc):
    2. root = CommandNode(doc["service"])
    3. for res_name, res in doc.get("resources", {}).items():
    4. res_node = root.add_child(res_name)
    5. for method_name, method in res.get("methods", {}).items():
    6. leaf = res_node.add_child(method_name)
    7. leaf.operation = method # store path, httpMethod, parameters, scopes
    8. return root

    This code only shows the tree-building process. A real implementation also needs to handle naming conflicts, parameter type conversion, and error message output.

    5. Upfront Parameter Validation

    The engine should complete parameter checks before sending a network request, in the following order:

    1. Type conversion: convert command-line strings into the types declared in the metadata.
    2. Required checks: confirm that all parameters with required set to true have been provided.
    3. Default value filling: fill in default values for parameters that were not provided and have defaults.
    4. Regex matching: validate string formats according to the pattern field.

    On failure, give specific messages, for example:

    1. Error: parameter --maxResults should be an integer, received "abc".
    2. Error: missing required parameter --bucket.

    A correct command example:

    1. storage-service objects list --maxResults=50

    Local validation can only reduce invalid requests; it cannot replace server-side validation. The rules on both sides should remain consistent. If server rules change while metadata is not synchronized, local validation may allow requests the server will reject, or block requests the server would actually allow.

    6. Permission Filtering and Auditing

    1. Filter commands: parse the scope list from the token and hide commands the user is not authorized to execute. This improves the user experience but is not a security boundary. Even if a command is hidden, the server should still reject unauthorized requests.
    2. Least privilege: issue CLI tokens with only the scopes needed to complete the task, and set a reasonable expiry time.
    3. File permissions: cache files and configuration files should be readable and writable only by the current user, for example 0600 on Unix systems.
    4. Audit logs: record the executed command, time, returned status code, and token identifier (not the token value). Sensitive fields in parameters should be redacted before being written to logs.

    7. Implementation Checklist

    • Pin the major version of the supported metadata specification and provide a clear message for unknown versions.
    • Test cache behavior when the TTL expires, when the hash matches, and when the hash changes.
    • Simulate network disconnection and verify that read-only fallback and write rejection behave as expected.
    • Test error messages for missing required parameters, type errors, and regex mismatches.
    • Compare CLI command filtering results with server authorization results to confirm consistency.
    • Check audit logs for tokens or other sensitive information.

    Conclusion

    A dynamic CLI based on an API discovery service can move interface information from code into runtime metadata, reducing the work of writing adapter code for each interface. Its effectiveness depends on several prerequisites: a stable metadata specification, a maintained engine, tested caching and fallback strategies, and full server-side authorization on every request. Teams should confirm these prerequisites before deciding whether to adopt this approach.