Build a Multi-Model Protocol Adapter in About 50 Lines of C#

    A lightweight C# adapter can decouple an AI coding agent’s structured response protocol from model backends that expose chat completions. This article explains the dual-endpoint architecture, request and response mappings, configuration, and a minimal implementation, along with the tool-calling, streaming, security, and reliability work needed for production use.

    1. Why AI Coding Agents Need a Protocol Adapter

    Many AI coding agents support shell tool calls, patch application, and plan tracking. These capabilities help developers modify code, execute commands, and break tasks into steps. Such agents often rely on a structured response protocol: the model must return not only natural-language text, but also structured fields representing tool calls, execution steps, patches, or status information.

    Many model services, however, expose only a chat completion protocol. They accept an array of messages and return candidate responses, without directly providing the structured format expected by the coding agent.

    This creates a protocol mismatch when developers try to connect the same agent to different model services. The agent expects one response format, while a local inference server or model aggregation service provides another. Modifying the agent’s source code is costly, and maintaining a separate integration for every model is difficult to sustain.

    A lightweight adapter between the agent and the model service provides a cleaner boundary. It keeps protocol differences inside an independent process:

    • The coding agent continues to use its expected structured endpoint.
    • The adapter converts incoming requests into chat completion requests.
    • The adapter converts upstream responses back into the agent’s structured format.
    • Switching models requires configuration changes rather than changes to the agent-facing protocol.

    The benefit is not simply connectivity. It is the separation of the tool-facing frontend from the model backend.

    2. Architecture: Two Endpoints, One Model Client

    The recommended architecture has six parts:

    1. Point the AI coding agent to the local adapter’s base URL.
    2. Expose two HTTP endpoints: one for structured responses and one for chat completions.
    3. Route both endpoints through a shared model client that calls the upstream service.
    4. Allow the upstream service to be a model aggregator, a local inference server, or a cloud-hosted model service.
    5. Supply the model name, upstream URL, API key, and listening port through environment variables.
    6. Create a local configuration directory at startup and write a basic configuration file for the agent to read or for manual inspection.

    The central principle is to keep protocol conversion in the adapter while leaving tool definitions and agent logic unchanged. This allows the same shell tools, patch application workflow, and plan tracking capabilities to be reused across multiple models.

    3. Essential Protocol Mappings

    A minimally usable adapter needs to handle four categories of mapping.

    Request Mapping

    A structured request may contain system instructions, user messages, tool definitions, and context. The adapter should extract a message array that the upstream model understands and convert tool definitions into the upstream service’s supported tool format.

    If the upstream service does not support native tool calling, the prompt must explicitly describe the tools and establish a parameter format.

    Response Mapping

    Chat completion responses typically contain candidate text, a finish reason, and possibly tool-call fragments. The adapter must wrap text in structured messages, convert tool calls into fields the target agent recognizes, and supply required identifiers, statuses, and ordering information.

    Do not invent upstream information. Represent missing capabilities through empty arrays, appropriate default statuses, or explicit errors.

    Tool-Call Mapping

    Function names, call identifiers, and JSON arguments must remain consistent. A mapping table can translate upstream tool-call identifiers into local identifiers, preventing confusion across multiple conversation turns.

    Validate argument JSON before passing a tool call to the agent. Invalid arguments should produce a structured error rather than trigger an incorrect execution.

    Streaming and Error Mapping

    If the agent expects streaming responses, the adapter must convert incremental text, tool-argument fragments, and completion events into the target protocol’s event sequence. If the upstream service does not support streaming, fall back to a non-streaming response.

    Error handling should use consistent HTTP status codes and JSON error bodies. Record the upstream request identifier, elapsed time, and error category to make failures easier to diagnose.

    4. Endpoint Design and Configuration

    For illustration, the adapter exposes two endpoints:

    • POST /v1/structured-response: a structured response endpoint for AI coding agents.
    • POST /v1/chat-completion: a chat completion endpoint for other editing tools.

    These paths are illustrative. Configure the actual routes to match the target tool’s requirements, and keep route constants in one place rather than scattering them throughout the code.

    The adapter can use the following environment variables:

    • MODEL_BACKEND: the upstream chat completion URL.
    • MODEL_NAME: the default model name.
    • MODEL_API_KEY: the upstream API key.
    • ADAPTER_PORT: the local listening port.

    At startup, create a local configuration directory and write a configuration such as:

    1. {
    2. "baseUrl": "http://127.0.0.1:18080"
    3. }

    Do not write API keys into this configuration file. Read them from environment variables. If secrets must be persisted, use a managed secret storage service rather than a plaintext configuration file.

    5. A Minimal C# Implementation

    The following example demonstrates the core approach. It omits streaming conversion, complete error handling, and detailed tool-call mapping. Adjust field names to match the target agent’s actual protocol documentation.

    1. using System.Net;
    2. using System.Text;
    3. using System.Text.Json;
    4. const string StructuredPath = "/v1/structured-response";
    5. const string ChatPath = "/v1/chat-completion";
    6. var port = int.Parse(Env("ADAPTER_PORT", "18080"));
    7. var backend = Env("MODEL_BACKEND", "http://127.0.0.1:8080/v1/chat-completion");
    8. var model = Env("MODEL_NAME", "default");
    9. var key = Env("MODEL_API_KEY", "");
    10. var dir = Path.Combine(AppContext.BaseDirectory, "adapter-config");
    11. Directory.CreateDirectory(dir);
    12. File.WriteAllText(Path.Combine(dir, "config.json"),
    13. JsonSerializer.Serialize(new { baseUrl = $"http://127.0.0.1:{port}" }));
    14. var listener = new HttpListener();
    15. listener.Prefixes.Add($"http://127.0.0.1:{port}/");
    16. listener.Start();
    17. while (true) { var ctx = await listener.GetContextAsync(); _ = Handle(ctx); }
    18. async Task Handle(HttpListenerContext ctx)
    19. {
    20. try
    21. {
    22. var body = await new StreamReader(ctx.Request.InputStream, Encoding.UTF8).ReadToEndAsync();
    23. var path = ctx.Request.Url!.AbsolutePath;
    24. var userText = ExtractUserText(body);
    25. var chatBody = JsonSerializer.Serialize(new
    26. {
    27. model,
    28. messages = new[] { new { role = "user", content = userText } }
    29. });
    30. var upstream = await Forward(chatBody);
    31. var text = ExtractText(upstream);
    32. var result = path == StructuredPath
    33. ? JsonSerializer.Serialize(new { id = Guid.NewGuid().ToString("N"),
    34. output = new[] { new { type = "message", content = text } } })
    35. : JsonSerializer.Serialize(new { choices = new[] {
    36. new { message = new { role = "assistant", content = text } } } });
    37. var bytes = Encoding.UTF8.GetBytes(result);
    38. ctx.Response.ContentType = "application/json";
    39. ctx.Response.OutputStream.Write(bytes);
    40. }
    41. catch (Exception ex)
    42. {
    43. ctx.Response.StatusCode = 502;
    44. var bytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new { error = ex.Message }));
    45. ctx.Response.OutputStream.Write(bytes);
    46. }
    47. finally { ctx.Response.Close(); }
    48. }
    49. async Task<string> Forward(string body)
    50. {
    51. using var http = new HttpClient();
    52. if (!string.IsNullOrWhiteSpace(key))
    53. http.DefaultRequestHeaders.Authorization = new("Bearer", key);
    54. var resp = await http.PostAsync(backend,
    55. new StringContent(body, Encoding.UTF8, "application/json"));
    56. return await resp.Content.ReadAsStringAsync();
    57. }
    58. string ExtractUserText(string body)
    59. {
    60. using var doc = JsonDocument.Parse(body);
    61. if (doc.RootElement.TryGetProperty("input", out var input)) return input.ToString();
    62. if (doc.RootElement.TryGetProperty("messages", out var msgs))
    63. return msgs.EnumerateArray().Last().GetProperty("content").ToString();
    64. return body;
    65. }
    66. string ExtractText(string upstream)
    67. {
    68. using var doc = JsonDocument.Parse(upstream);
    69. return doc.RootElement.GetProperty("choices")[0]
    70. .GetProperty("message").GetProperty("content").ToString();
    71. }
    72. string Env(string name, string fallback) =>
    73. Environment.GetEnvironmentVariable(name) ?? fallback;

    The important point is the separation of responsibilities, not the exact line count. Routing, configuration generation, upstream forwarding, and response wrapping have distinct roles.

    This is a simplified text-only demonstration, not a complete implementation of the mappings described above. A production version needs asynchronous concurrency control, timeouts, retries, streaming event conversion, and tool-call mapping.

    6. Switching Between Model Backends

    Model Aggregation Services

    With a model aggregation service, the adapter can pass the model name upstream to select different models under a single API key. This is useful for quickly comparing model behavior.

    However, models and providers may differ in their tool-calling support, streaming formats, and context limits. A shared endpoint does not eliminate these compatibility differences.

    Local Inference Services

    A local inference service can keep data within the deployment environment and provide more control over latency, making it suitable for private code workflows.

    The main constraints include GPU memory, concurrency, and context-window limits.

    Cloud Deployment

    For a cloud deployment, general-purpose container hosting, logging, and monitoring services can host and operate the adapter. Baidu AI Cloud is one option mentioned in this context; consult the official documentation for availability in the intended deployment region.

    Inject configuration through environment variables or a secret management service rather than storing API keys in plaintext files.

    Configuration and Compatibility Testing

    Make switching policies configurable:

    • Read the model name, temperature, maximum output length, and timeout from environment variables or configuration files.
    • Define default and fallback models for different tasks.
    • Run contract tests against a fixed set of samples to verify tool calls, patch fields, and streaming completion events.

    7. Production Readiness Checklist

    1. Security: Bind to the loopback address by default, allowlist upstream URLs, keep API keys out of logs, and enforce request-size and timeout limits.

    2. Observability: Generate a request identifier for each request. Record upstream latency, status code, model name, and error category, while redacting sensitive log data.

    3. Reliability: Reuse connection pools, apply retries with backoff, and add circuit breaking and rate limiting. Release resources promptly when streaming connections disconnect.

    4. Compatibility: Pass through or ignore unknown fields as appropriate, manage protocol versions centrally, and run regression tests using recorded request and response samples.

    5. Maintainability: Separate protocol mappings into independent modules. Keep the core proxy small and readable—roughly 50 lines where practical—and expand complex behavior in dedicated components.

    8. Conclusion

    A lightweight protocol adapter can isolate the differences between structured response protocols and chat completion APIs. This lets an AI coding agent use a consistent frontend while connecting to multiple hosted or local model backends.

    The core proxy can remain compact, but a usable system requires additional engineering for security, observability, streaming conversion, and tool-call mapping. For teams looking to reduce coupling between coding tools and models, the combination of two endpoints, a shared model client, and configuration-driven switching provides a practical foundation.