Building a Multi-Model Adapter Layer in 50 Lines of C# for Your Coding CLI

    Many AI coding CLI agents are locked into a single proprietary response protocol, making it hard to switch between local and cloud model backends. This article shows how to add a lightweight adapter layer between the agent and model providers: two HTTP entry points, one unified chat kernel, and protocol conversion in between. A minimal ~50-line C# implementation demonstrates the core loop, along with key implementation details around request normalization, streaming events, tool call mapping, error handling, and configuration-based model routing.

    1. The Problem: Capable Agents, Hardwired Protocols

    AI coding CLI agents can execute commands, apply patches, and track plans—turning natural language intent into actual operations on a codebase. Their value lies not in “chatting” but in completing multi-step tasks in an editor or terminal: reading files, generating changes, running commands, and planning next steps based on results. This is exactly what makes them attractive to engineering teams.

    A common pain point, however, is that these agents communicate over a protocol designed around one particular “agent-style response format,” accepting only HTTP endpoints that conform to it. Meanwhile, most local inference servers, general-purpose model gateways, and cloud model services expose a “chat completions protocol” instead. The two differ in message structure, streaming events, tool call representation, and termination semantics, so agents cannot connect to these backends directly. Developers then face three problems: first, they cannot connect directly to local models; second, switching between models requires modifying the tool or proxy configuration; third, a multi-model strategy—simple tasks on a local model, complex tasks on a cloud model—is hard to implement.

    The solution does not require modifying the CLI agent’s source code. A lighter approach is to insert an adapter layer between the agent and the model backends: the agent keeps sending requests in its familiar agent response format, the adapter converts them into a unified chat request, calls the actual model backend, then converts the model output back into agent event format. The CLI agent thus becomes a unified front end for multiple models, with backends freely swappable.

    2. Core Architecture: Two Entrances, One Kernel

    The adapter can follow a “two entrances, one kernel” structure.

    The first layer is the entry layer. The adapter exposes two custom HTTP endpoints: a chat completions endpoint for general editing tools, and an agent response endpoint for CLI tools bound to the agent protocol. Endpoint paths are up to you—/chat and /agent work fine; what matters is format compatibility, not naming.

    The second layer is protocol conversion. It normalizes requests from different entrances into one internal structure—model name, message list, tool definitions, streaming flag, and metadata. When responding, it serializes internal deltas into the format required by the target protocol. Protocol differences are thus contained in a thin layer.

    The third layer is model abstraction. Define a vendor-agnostic chat backend interface, such as IChatBackend, with a streaming invocation method. Implementations can target local inference servers, cloud model services, or model aggregation gateways. Switching models only requires changing the model-to-backend mapping in configuration; the wire protocol stays the same.

    The benefits: multiple entrances but a single kernel avoids duplicated logic; the protocol format is stable while backends are replaceable; authentication, rate limiting, logging, and error handling can be centralized in the adapter; and the CLI agent needs no awareness of backend differences.

    3. What “50 Lines” Covers

    “50 lines” means a minimal viable loop, not a production-grade implementation. A ~50-line C# script can handle these core responsibilities: reading configuration, registering two routes, parsing JSON requests, calling a unified model client, writing streaming responses, and basic error mapping. It’s enough to verify that agent requests can be converted to chat requests, model deltas can be converted into agent events, and tool calls can be passed through correctly.

    A production deployment still needs: caller authentication, request body size limits, model whitelists, rate limiting, timeouts and cancellation, log redaction, auditing, upstream retry policies, health checks, and metrics reporting. The point of the 50-line script is to prove the core chain is simple and feasible—not to replace an engineered service. Once the minimal loop works, extensions have a clear boundary.

    4. Key Implementation Details

    1. Request Normalization

    The internal request structure should include the model name, message array, tool definitions, streaming flag, and optional metadata. Message roles must cover at least system, user, assistant, and tool results. Agent request input may be a message array or a tool result array; merge them in order and preserve call identifiers so multi-turn tool calls remain关联able across rounds.

    Tool definitions must retain name, description, and parameter schema. Field names differ across protocols but semantics are the same—use explicit mapping during conversion rather than blind passthrough. If multimodal content is supported, convert it into a common content-part array; if not, return a clear error instead of silently dropping images or attachments.

    2. Response Serialization and Streaming Events

    Unify streaming responses into incremental text, tool call deltas, termination events, and error events. The agent protocol may require event indices, statuses, and termination markers; the chat completions protocol may require data chunks with a final sentinel. A simple state machine works: start, content delta, tool call delta, done. Each delta should be written once, and the termination event must carry the final state.

    If an error occurs before the stream starts, return an HTTP error; if the stream has already started, write an error event and close the connection so the client doesn’t hang. Never switch response formats mid-stream, or the agent will fail to parse.

    3. Tool Call Mapping

    Tool calls are the core of agent capability. On the request side, convert agent tool definitions into backend tool definitions; on the response side, convert backend tool calls into agent events. Fields should include at least a call identifier, tool name, and arguments JSON. Arguments must be valid JSON; unknown tools or failed argument validation should return a diagnosable error. Multi-turn tool results must preserve call identifiers so the model can associate them correctly.

    4. Errors, Timeouts, and Cancellation

    A unified error object should include an error code, message, and retryability flag. Upstream timeouts, rate limits, and auth failures should map to distinct states. Support client cancellation and release the upstream stream when cancelled. Do not auto-retry non-idempotent tool calls; retry only on connection establishment failures or explicitly retryable errors. Redact logs—never record keys or full user code.

    5. Configuration and Model Routing

    Configuration can map model names to backend type, endpoint, key environment variable, timeout, and max output length. Routing follows a model name whitelist. Local and cloud models share the same interface; local models typically need no key, while cloud models read keys from environment variables. The minimal version can require a restart to apply changes; a more advanced version can hot-reload configuration.

    The following sketch highlights the core structure without depending on specific third-party libraries:

    1. record Msg(string Role, string Content);
    2. record ToolDef(string Name, string Description, string SchemaJson);
    3. record ChatRequest(string Model, List<Msg> Messages, bool Stream, List<ToolDef>? Tools);
    4. record AgentRequest(string Model, List<Msg> Input, List<ToolDef>? Tools);
    5. record Chunk(string Kind, string? Text, string? CallId, string? ToolName, string? ArgsJson);
    6. interface IChatBackend {
    7. IAsyncEnumerable<Chunk> StreamAsync(ChatRequest req, CancellationToken ct);
    8. }
    9. app.Post("/chat", async ctx => {
    10. var r = await ctx.ReadJson<ChatRequest>();
    11. await ctx.WriteChatStream(backend.StreamAsync(r, ctx.Aborted));
    12. });
    13. app.Post("/agent", async ctx => {
    14. var a = await ctx.ReadJson<AgentRequest>();
    15. var r = AgentToChat(a);
    16. await ctx.WriteAgentEvents(backend.StreamAsync(r, ctx.Aborted));
    17. });

    This sketch omits authentication and rate limiting but shows both entrances sharing a single backend abstraction. In a real implementation, AgentToChat handles message and tool definition conversion, while WriteAgentEvents serializes internal deltas into agent events.

    5. Deployment and Validation Recommendations

    Validate in order: first get non-streaming text working, then streaming text; then verify tool calls, multi-turn tool results, and error paths. Use fixed samples for protocol regression at every step, especially call identifiers and argument JSON in tool calls. For deployment, a general container platform or a local process works, combined with logging and monitoring for latency, error rates, and upstream status; apply authentication and rate limiting to callers, listen only on loopback or internal addresses, and inject keys via environment variables.

    On performance, streaming output reduces time-to-first-token; connection pooling reuses upstream connections; upstream timeouts should be shorter than client timeouts; avoid buffering the entire stream before responding. On security, limit request body size, configure CORS as needed, allow only whitelisted models, and prevent the adapter from being abused as an open proxy.

    6. Conclusion

    The adapter layer’s value lies in containing protocol differences within a thin layer: the CLI agent keeps using its agent response format, the adapter converts it into a unified chat request, calls a cloud or local model, then translates the results back into agent events. A ~50-line C# script can prove the core loop is not complicated, but production deployment still requires authentication, rate limiting, a streaming state machine, tool call mapping, error handling, and security controls. With these key points in place, an AI coding CLI agent becomes a unified front end that can freely switch between model backends—without touching its network protocol.