The Pattern Map
Adapter, Facade and Proxy, the Plumbing Behind AI Apps
October 12, 2026 · 15 min read
Design Patterns, Software Architecture, C#, Python, Swift, MCP, AI
This is the second pattern post in The Pattern Map, after Abstract Factory, Builder and Prototype. These three are structural patterns: they're about how objects are wired together, not how they're made or how they behave.
They're worth taking together because they're easy to confuse. All three put one object in front of another. The difference is the intent:
| Interface the caller sees | Job | |
|---|---|---|
| Adapter | A different one from the wrapped object | Make something fit an interface it wasn't built for |
| Facade | A simpler one than the subsystem behind it | Hide a lot of moving parts behind one front door |
| Proxy | The same one as the wrapped object | Decide whether, when and how the real call happens |
Decorator, which I covered in 5 Design Patterns Every Developer Should Master, also keeps the same interface. The line between Decorator and Proxy is intent: a decorator adds behaviour and always calls through; a proxy controls access and may not call through at all. The code often looks identical.
As in the last post, every sample here compiles and runs as shown (C# as .NET 10 file-based apps, Python 3.12, Swift 6), with stand-ins where a real service would go.
Adapter
The problem
You've written your app against an interface you like. Then you need a library, a vendor SDK or some older code of your own that does the right thing with the wrong shape: different method names, different units, different types. You don't want that shape leaking through your app, and you can't change the library.
An Adapter implements your interface and translates each call into theirs. The rest of the app never knows the vendor exists.
C#
// The interface my app is written against.
public sealed record Forecast(double TemperatureC, string Summary);
public interface IWeatherProvider
{
Forecast GetForecast(double latitude, double longitude);
}
// A vendor SDK I can't change: different method, units and shapes.
public sealed record AcmeReport(double TempF, int ConditionCode);
public sealed class AcmeWeatherClient
{
public AcmeReport Fetch(string latLon) => new(TempF: 50.0, ConditionCode: 3);
}
// The adapter: implements my interface, translates to theirs.
public sealed class AcmeWeatherAdapter(AcmeWeatherClient client) : IWeatherProvider
{
public Forecast GetForecast(double latitude, double longitude)
{
var report = client.Fetch($"{latitude},{longitude}");
var celsius = (report.TempF - 32) * 5 / 9;
return new Forecast(celsius, Describe(report.ConditionCode));
}
private static string Describe(int code) => code switch
{
1 => "Clear",
2 => "Partly cloudy",
3 => "Overcast",
_ => "Unknown",
};
}
IWeatherProvider weather = new AcmeWeatherAdapter(new AcmeWeatherClient());
var forecast = weather.GetForecast(43.65, -79.38); // Toronto
Console.WriteLine($"{forecast.TemperatureC:F1} °C, {forecast.Summary}");
10.0 °C, Overcast
The Fahrenheit, the string-encoded coordinates and the magic condition codes all stop at the adapter. If I switch weather vendors, I write one new adapter and nothing else changes. That's also why adapters make testing easy: the app depends on IWeatherProvider, and a fake one is three lines.
Python: adapting a function into a tool
Here's the version of Adapter that matters most in AI code. A model can't call your Python function directly. An agent needs each tool described in a fixed shape: a name, a description, and a JSON Schema for the inputs. Then it sends back a tool call as a name plus a dictionary of arguments. Your existing function has none of that. It has a signature, type hints and a docstring.
That's an interface mismatch, and the fix is an adapter:
import inspect
import json
from typing import Any, Callable
PY_TO_JSON = {str: "string", int: "integer", float: "number", bool: "boolean"}
class ToolAdapter:
"""Adapts a plain Python function to the shape an MCP tool listing uses:
a name, a description, a JSON Schema for inputs, and call(arguments)."""
def __init__(self, fn: Callable[..., Any]):
self.fn = fn
self.name = fn.__name__
self.description = inspect.getdoc(fn) or ""
params = inspect.signature(fn).parameters.values()
self.input_schema = {
"type": "object",
"properties": {p.name: {"type": PY_TO_JSON[p.annotation]} for p in params},
"required": [p.name for p in params if p.default is inspect.Parameter.empty],
}
def describe(self) -> dict:
return {"name": self.name, "description": self.description,
"inputSchema": self.input_schema}
def call(self, arguments: dict) -> str:
return json.dumps(self.fn(**arguments))
# Existing code that knows nothing about agents.
def convert_temperature(fahrenheit: float, decimals: int = 1) -> float:
"""Convert a Fahrenheit temperature to Celsius."""
return round((fahrenheit - 32) * 5 / 9, decimals)
tool = ToolAdapter(convert_temperature)
print(json.dumps(tool.describe(), indent=2))
print(tool.call({"fahrenheit": 50})) # what a model's tool call would send
{
"name": "convert_temperature",
"description": "Convert a Fahrenheit temperature to Celsius.",
"inputSchema": {
"type": "object",
"properties": {
"fahrenheit": {
"type": "number"
},
"decimals": {
"type": "integer"
}
},
"required": [
"fahrenheit"
]
}
}
10.0
The output shape (name, description, inputSchema) matches how the Model Context Protocol describes a tool in a tools/list response. This toy only handles four simple types; a real one handles lists, nested objects and optional values.
The MCP connection
This is the "same patterns, new clothes" idea at its clearest. MCP's own docs describe it as "like a USB-C port for AI applications": one standard plug. Every MCP server is an adapter between something with its own shape (a database, a filesystem, a SaaS API, your app) and that one standard interface. The AI application (the "host") speaks only MCP. The server translates.
The official MCP Python SDK does a production version of my toy: you decorate a type-hinted function with @mcp.tool(), and, as the README puts it, the type hints are the schema. The pattern is the same one in the weather example above; only the target interface changed, from IWeatherProvider to a protocol every AI client agrees on. I went through MCP itself in Understanding MCP back in January.
Swift: callbacks to async/await
Swift has its own everyday Adapter, and if you've maintained an iOS app for more than a few years you've probably needed it. Older APIs report results through completion handlers; new code wants async/await. withCheckedThrowingContinuation is the standard-library adapter between the two:
import Foundation
// An older, callback-based API (think a vendor SDK, or your own code from 2019).
final class LegacyPhotoLibrary: @unchecked Sendable {
func fetchAlbumNames(completion: @escaping @Sendable (Result<[String], Error>) -> Void) {
DispatchQueue.global().async {
completion(.success(["Favourites", "Point Pelee", "Astro"]))
}
}
}
// The adapter: same capability, the async/await shape the rest of the app uses.
extension LegacyPhotoLibrary {
func albumNames() async throws -> [String] {
try await withCheckedThrowingContinuation { continuation in
fetchAlbumNames { result in
continuation.resume(with: result)
}
}
}
}
let names = try await LegacyPhotoLibrary().albumNames()
print(names)
["Favourites", "Point Pelee", "Astro"]
The "checked" in the name matters, because a callback adapter has two classic bugs: resuming twice and never resuming. With the checked version, resuming twice crashes with a "SWIFT TASK CONTINUATION MISUSE" fatal error, and dropping the continuation without resuming prints a warning that the waiting task may stay suspended forever. The unchecked variant skips those checks.
In Python you often don't need this. Duck typing means there's usually no interface to satisfy; if the caller only needs .get_forecast(), any object with that method works, and a small function or a lambda is often the whole adapter. You still need the idea whenever the target is a fixed external format, as with tool schemas above.
Where you'll see it now: in the cloud era it's the Anti-Corruption Layer, which Microsoft describes as "a façade or adapter layer" between a new system and a legacy one. In the AI era it's every MCP server.
Facade
The problem
Some jobs need several components in the right order. Answering a question from your own docs (retrieval-augmented generation, or RAG) means: search for relevant passages, build a prompt around them, call the model, attach citations. Every caller who wants an answer shouldn't have to know those four steps or get their order right.
A Facade is one simple entry point over a subsystem. The key difference from Adapter: the facade invents a simpler interface; it isn't conforming to an existing one. And the subsystem stays available for callers who need the details.
C#
// The facade: one call for the 90% case.
public sealed class DocsAssistant(IRetriever retriever, PromptBuilder prompts, IModelClient model)
{
public string Ask(string question, int topK = 2)
{
var passages = retriever.Search(question, topK);
var prompt = prompts.Build(question, passages);
var answer = model.Complete(prompt);
var sources = string.Join(", ", passages.Select(p => p.Id));
return $"{answer}\n(sources: {sources})";
}
}
// The subsystem: each piece stays public and usable on its own.
public sealed record Passage(string Id, string Text);
public interface IRetriever { IReadOnlyList<Passage> Search(string query, int topK); }
public interface IModelClient { string Complete(string prompt); }
public sealed class KeywordRetriever : IRetriever
{
private readonly Passage[] _docs =
[
new("account.md#reset", "To reset your password, open Settings > Account > Reset."),
new("billing.md#refund", "Refunds are handled through the App Store."),
new("account.md#delete", "Deleting your account removes all synced data."),
];
public IReadOnlyList<Passage> Search(string query, int topK) =>
_docs.OrderByDescending(d => Score(d.Text, query)).Take(topK).ToList();
private static int Score(string text, string query) =>
query.ToLowerInvariant().Split(' ').Count(w => text.ToLowerInvariant().Contains(w));
}
public sealed class PromptBuilder
{
public string Build(string question, IReadOnlyList<Passage> passages) =>
"Answer using only these passages:\n" +
string.Join("\n", passages.Select(p => $"[{p.Id}] {p.Text}")) +
$"\n\nQuestion: {question}";
}
public sealed class FakeModelClient : IModelClient
{
public string Complete(string prompt) =>
"Open Settings > Account > Reset.";
}
var assistant = new DocsAssistant(new KeywordRetriever(), new PromptBuilder(), new FakeModelClient());
Console.WriteLine(assistant.Ask("How do I reset my password?"));
Open Settings > Account > Reset.
(sources: account.md#reset, account.md#delete)
The retriever is a keyword match and the model is a stand-in, but the shape is the real one. Swap in a vector search and a real client and Ask doesn't change. That's the facade's job: callers depend on "ask a question, get an answer with sources", not on how many steps that takes this month.
The risk with facades is the one I noted about service layers in Design Patterns I Keep Coming Back To: they grow. A facade with forty methods isn't simplifying anything any more. Keep it to the common path and let advanced callers use the parts directly.
Python
DOCS = {
"account.md#reset": "To reset your password, open Settings > Account > Reset.",
"billing.md#refund": "Refunds are handled through the App Store.",
"account.md#delete": "Deleting your account removes all synced data.",
}
def search(query: str, top_k: int) -> list[tuple[str, str]]:
words = query.lower().split()
score = lambda item: sum(w in item[1].lower() for w in words)
return sorted(DOCS.items(), key=score, reverse=True)[:top_k]
def build_prompt(question: str, passages: list[tuple[str, str]]) -> str:
context = "\n".join(f"[{id}] {text}" for id, text in passages)
return f"Answer using only these passages:\n{context}\n\nQuestion: {question}"
def complete(prompt: str) -> str:
return "Open Settings > Account > Reset." # stand-in for a model call
# The facade is just a function. The module is the subsystem.
def ask(question: str, top_k: int = 2) -> str:
passages = search(question, top_k)
answer = complete(build_prompt(question, passages))
return f"{answer}\n(sources: {', '.join(id for id, _ in passages)})"
print(ask("How do I reset my password?"))
In Python you often don't need this as a class. A module already groups a subsystem, and one well-named top-level function is the facade. Python's own standard library is full of them: json.dumps hides the encoder class you'd otherwise configure by hand.
Where you'll see it now: in the cloud era, Gateway Aggregation and Backends for Frontends, where one endpoint fronts several services. In the AI era, almost every SDK's "just ask" method is a facade over retrieval, prompting, tool loops and parsing.
Proxy
The problem
Sometimes you want callers to use an object exactly as they normally would, while something in between decides whether the real call happens. Maybe the real object is expensive (cache the result), remote (handle the network), not needed yet (create it lazily), or dangerous (check permissions first).
A Proxy implements the same interface as the real subject and stands in for it. The GoF book lists remote, virtual (lazy) and protection proxies, plus "smart references"; a caching proxy is the common modern addition. Lazy<T> in .NET is a virtual proxy you already use, and every generated client for a remote API is a remote proxy.
C#: a caching proxy in front of a model
Model calls are slow and billed per token, and apps often send the same prompt more than once. A caching proxy answers repeats itself:
public interface IModelClient
{
string Complete(string prompt);
}
// The real subject: slow, rate-limited, billed per token.
public sealed class RemoteModelClient : IModelClient
{
public int Calls { get; private set; }
public string Complete(string prompt)
{
Calls++;
return $"(model output for: {prompt})";
}
}
// The proxy: same interface, and it decides whether the real call happens at all.
public sealed class CachingModelProxy(IModelClient inner) : IModelClient
{
private readonly Dictionary<string, string> _cache = new();
public string Complete(string prompt)
{
if (_cache.TryGetValue(prompt, out var cached))
return cached;
var result = inner.Complete(prompt);
_cache[prompt] = result;
return result;
}
}
var real = new RemoteModelClient();
IModelClient client = new CachingModelProxy(real);
client.Complete("Write alt text for a heron photo.");
client.Complete("Write alt text for a heron photo."); // served from cache
client.Complete("Write alt text for a fox photo.");
Console.WriteLine($"3 requests, {real.Calls} paid model calls");
3 requests, 2 paid model calls
Two caveats that carry straight over from classic caching proxies. First, this only makes sense where the same input should give the same output; if you want variety from the model, a cache defeats the purpose. Second, a real version needs expiry and a size limit; this dictionary grows forever.
Python: a protection proxy for agent tools
The protection proxy is the one that maps most directly onto coding agents. An agent gets a tools object; you want it to read files in one project and nothing else. You don't want to rewrite the tools. You put a proxy in front:
from pathlib import Path
class FileTools:
"""A tool object an agent can call. It doesn't know about permissions."""
def read_file(self, path: str) -> str:
return f"(contents of {path})"
def list_dir(self, path: str) -> list[str]:
return ["a.swift", "b.swift"]
def write_file(self, path: str, text: str) -> None:
print(f"wrote {len(text)} chars to {path}")
class ReadOnlyProxy:
"""Protection proxy: forwards allowlisted methods, refuses everything else,
and keeps every path inside one project root."""
ALLOWED = {"read_file", "list_dir"}
def __init__(self, target, root: str):
self._target = target
self._root = Path(root).resolve()
def __getattr__(self, name):
if name not in self.ALLOWED:
raise PermissionError(f"{name} is not allowed for this agent")
method = getattr(self._target, name)
def guarded(path: str, *args, **kwargs):
resolved = (self._root / path).resolve()
if not resolved.is_relative_to(self._root):
raise PermissionError(f"{path} is outside {self._root}")
return method(str(resolved), *args, **kwargs)
return guarded
tools = ReadOnlyProxy(FileTools(), root="/srv/project")
print(tools.read_file("Sources/App.swift"))
for attempt in (lambda: tools.write_file("notes.md", "hi"),
lambda: tools.read_file("../../etc/passwd")):
try:
attempt()
except PermissionError as e:
print("blocked:", e)
(contents of /srv/project/Sources/App.swift)
blocked: write_file is not allowed for this agent
blocked: ../../etc/passwd is outside /srv/project
resolve() turns ../../etc/passwd into a real absolute path before the check, which is what stops the classic path-traversal trick. This is a sketch for the pattern, not a sandbox: a real one would also need to think about symlinks created after the check, and a determined process can reach the filesystem by other routes. Real agent harnesses enforce permissions outside the model's reach for exactly that reason. But the shape, a gatekeeper with the same interface as the thing it guards, is the same.
In Python you often don't need a proxy class per interface. __getattr__ is called for any attribute the proxy doesn't define, so one small class can forward every method of any target, which is what the example does. In C# you'd write one proxy class per interface by hand, generate them (Castle DynamicProxy, which Moq uses under the hood, does this), or use DispatchProxy from the base library.
Where you'll see it now: in the cloud era, the Ambassador and Gateway Offloading patterns, API Management in front of a service, and every reverse proxy. In the AI era, LLM gateways that sit between your app and the model provider to cache, rate-limit, hold the API keys and log usage, and permission layers in front of agent tools.
Telling them apart, in one line each
- Adapter: "I have the right thing in the wrong shape." Changes the interface.
- Facade: "There are too many steps for every caller to know." Simplifies the interface.
- Proxy: "The caller shouldn't notice, but something has to decide first." Keeps the interface, controls the call.
Next week: Composite, Bridge and Flyweight, the three structural patterns left. The full list is on The Pattern Map.
Further reading
- Design Patterns: Elements of Reusable Object-Oriented Software by Gamma, Helm, Johnson and Vlissides (1994), chapter 4 covers the structural patterns.
- Refactoring.Guru on Adapter, Facade and Proxy.
- MCP architecture overview, including the
tools/listandtools/callmessages. - The official MCP Python SDK.
- Microsoft's cloud pattern pages for the Anti-Corruption Layer and Ambassador.
- Apple's documentation for
CheckedContinuation.
Thoughts on this?
Tell me on X: @bobbyencoded · Share this post on X
Want more like this? Subscribe to The Decode, a weekly email on the AI and developer news worth your time.