Blog Post

Microsoft Developer Community Blog
8 MIN READ

Privacy proxy in Agents with Microsoft Agent Framework Middleware

vikas_gautam's avatar
vikas_gautam
Icon for Microsoft rankMicrosoft
May 15, 2026

An AI agent is not a single model call but a complex system combining models, tools, planners, and memory introducing multiple points where sensitive data can unintentionally propagate. As agent sophistication increases, protecting PII becomes significantly harder, which is why integrating centralized controls like PII Shield as middleware in frameworks such as Microsoft Agent Framework is essential for consistent and reliable data protection.

In the first part - Introducing PII Shield: A Privacy Proxy for Every LLM Call - we introduced PII-Shield as a privacy proxy that detects sensitive data, applies configurable anonymization strategies per entity, and reverses that anonymization once the LLM has completed its task. While this approach is valuable in any AI application, it becomes essential in agentic systems.

Consider an agentic chatbot - BankBuddy - designed to help customers with tasks such as unblocking cards or requesting replacements. As part of its workflow, the agent collects sensitive information including the customer’s name, Aadhaar number, card details, and date of birth. This data is used to validate the customer, invoke backend APIs to perform the requested action, and ultimately communicate the outcome - what was completed, what could not be processed, and any next steps required. 

The sequence diagram below illustrates how this interaction is orchestrated behind the scenes. If we carefully observe the interactions between the agent and LLM, some information about the customer is sent across so that the LLMs can perform tool calling, frame accurate responses etc. For regulated industries, this could be a red flag. If not handled well, actual customer information (which may be PII) could inadvertently surface in LLM inference logs or downstream processing layers.

 

Rather than placing this responsibility on individual AI developers, the burden should be absorbed by the enterprise architecture. Developers should remain focused on delivering business functionality, while a centralized, enforced privacy boundary ensures that all LLM and tool interactions are consistently governed. This boundary must be non-optional - every request and response flows through it, with no possibility of bypass. This approach removes the need for per-agent privacy engineering and guarantees uniform protection across applications - an essential requirement in highly regulated sectors such as BFSI, healthcare, and government.

In the next section, we explore how this challenge can be addressed within the Microsoft Agent Framework.

Middleware in Microsoft Agent Framework

The Microsoft Agent Framework provides two middleware extensibility points that are particularly relevant in this context (for more refer here):

MiddlewarePurposeWhere PII-shield gets hooked
ChatMiddlewareWraps every LLM call Anonymise outgoing messages, de-anonymise the response
FunctionMiddlewareEvery @tool invocationDe-anonymise tool args, re-anonymise tool results

Together, these form a generalized implementation of the “Anonymize → LLM → De-anonymize” pattern introduced in the first post - now systematically applied to every LLM interaction and every tool call within an agent’s execution loop. The example below demonstrates how PII Shield is integrated into a Microsoft Agent Framework ChatAgent using two coordinated middleware components that share a common mapping store. The PiiMappingStore serves as per-conversation memory, maintaining the association between placeholders (for example, {{PERSON_1}}, {{IN_AADHAAR_1}}) and their corresponding real values. This ensures consistent coreference across turns and tool invocations.

PiiShieldChatMiddleware operates at the LLM boundary, sanitizing every outbound prompt - including user input and accumulated context before it reaches the model, and restoring original values in the model’s response on the return path. Complementing this, PiiShieldFunctionMiddleware wraps all tool calls: it resolves placeholders into real values before execution (ensuring functions such as get_customer_info receive valid inputs) and then re-anonymizes the results before they are passed back into the agent loop.

By registering both middleware components in the agent’s middleware=[…] pipeline, the privacy boundary becomes comprehensive and non-bypassable. Every prompt, every tool invocation, and every response is automatically governed - eliminating opt-out paths and ensuring consistent protection by design.

from agent_framework import ChatAgent from bankingbuddy.middleware import ( PiiShieldChatMiddleware, PiiShieldFunctionMiddleware, PiiMappingStore, ) mapping_store = PiiMappingStore() # per-conversation chat_mw = PiiShieldChatMiddleware( mode="api", # or "library" api_url="http://pii-shield:8000", api_app_id="bankingbuddy-prod", # received from registering the app in PII-shield mapping_store=mapping_store, ) fn_mw = PiiShieldFunctionMiddleware(chat_middleware=chat_mw) agent = ChatAgent( chat_client=foundry_chat_client, instructions="You are BankingBuddy …", tools=[get_customer_info, unblock_card, order_card, report_lost_card], middleware=[chat_mw, fn_mw], )

The middleware can talk to PII Shield in two ways:

  • api mode (default) - Invokes the PII Shield REST endpoints (such as /anonymize_unique and /deanonymize). This approach decouples the NLP layer from the agent runtime, making it well-suited for production environments where PII Shield is deployed as a shared service across multiple teams.
  • library mode - Uses the in-process pii_shield.PiiShieldEngine to perform anonymization locally. This reduces latency and is particularly useful for local development, batch processing scenarios, and edge deployments.

A complete reference implementation of an agent incorporating this middleware pattern is available in the following GitHub repository:

 github.com/vikasgautam18/pii-agent-demos

Once this middleware approach is in place, the execution flow changes fundamentally. The LLM operates exclusively on anonymized placeholders, while the middleware transparently handles the substitution of real values during tool execution and response handling. This ensures that sensitive data never enters the model context, without requiring any additional effort from the agent developer. The sequence diagram below depicts how additional hops ChatMiddleware, FunctionMiddleare and PII-Shield ensure the LLM does not receive PII values.

High-level design

The diagram below illustrates the high-level architecture of this solution. From the user’s perspective, interaction remains unchanged - they communicate with a standard Microsoft Agent Framework ChatAgent, sending raw text and receiving raw responses.

Within the agent, however, two middleware components enforce strict privacy boundaries at the points where PII could otherwise be exposed. PiiShieldChatMiddleware operates at the LLM boundary, transforming every outbound prompt into anonymized placeholders and rehydrating the model’s response before it is returned. In parallel, PiiShieldFunctionMiddleware governs the tool boundary, performing the inverse operation: it de-anonymizes arguments so backend systems receive real values, and re-anonymizes tool outputs before they are fed back into the next LLM turn.

Both middleware components delegate the underlying detection and mapping logic to PII Shield - deployed either as a sidecar service or consumed as a library - and share a common PiiMappingStore scoped to the conversation. This shared state ensures consistency, allowing placeholders such as {{PERSON_3}} to reliably represent the same individual (for example, Vikas Gautam) across multiple turns, tool invocations, and final responses.

The net effect is a clean separation of concerns: the LLM operates exclusively on anonymized placeholders, backend systems operate on real values, and neither side needs awareness of the other. Privacy is enforced transparently and consistently, without adding complexity to the agent’s core logic.

How does it work - a turn in the life of an agent

Imagine the user types:

"Hi, I'm Vikas Gautam, customer ID 246813579. My card 4532-1234-5678-9012 is blocked, can you unblock it?"

ChatMiddleware: inbound

The middleware grabs the last user message, calls POST /anonymize, gets the following response: 

"Hi, I'm {{PERSON_1}}, customer ID {{IN_CUSTOMER_ID_1}}. My card {{CREDIT_CARD_1}} is blocked, can you unblock it?"

And the mapping { {{PERSON_1}}: "Vikas Gautam", {{IN_CUSTOMER_ID_1}}: "246813579", {{CREDIT_CARD_1}}: "4532-1234-5678-9012" } is stored in the run state and merged into the long-lived PiiMappingStore.

LLM 

The LLM sees only placeholders. It decides to call a tool:

{ "name": "unblock_card", "arguments": { "customer_id": "{{IN_CUSTOMER_ID_1}}", "card_number": "{{CREDIT_CARD_1}}" } }

FunctionMiddleware: before the tool

The function middleware reads the run state, walks the arguments, and replaces every placeholder with its real value

{ "customer_id": "246813579", "card_number": "4532-1234-5678-9012" }

The unblock_card tool runs against the real CRM with real IDs. No changes or configurations required in the tool itself.

FunctionMiddleware: after the tool

The tool returns the following: 

{ "status": "unblocked", "card_holder": "Vikas Gautam", "card_number": "4532-1234-5678-9012", "confirmation_email_sent_to": "vikas@example.com" }

The middleware then re-anonymises the result through PII Shield before handing it back to the LLM, so the next LLM hop sees only known placeholders (plus a brand-new {{EMAIL_ADDRESS_1}} for the email).

ChatMiddleware: outbound

After the agent loop finishes, the LLM's final answer might be:

"All done, {{PERSON_1}}. Your card ending in {{CREDIT_CARD_1}} is now active. A confirmation has been sent to {{EMAIL_ADDRESS_1}}."

The chat middleware walks every assistant message in the result, applies local string replacement (longest placeholder first) using the accumulated PiiMappingStore, and the user sees:

"All done, Vikas Gautam. Your card ending in 4532-1234-5678-9012 is now active. A confirmation has been sent to vikas@example.com."

Let's just assume at this point, the user asks:

"What's my balance?"

There's no PII in this message, so anonymisation is a no-op. But when the LLM calls get_balance(customer_id="{{IN_CUSTOMER_ID_1}}") - using a placeholder it remembers from turn 1 - the function middleware still resolves it from the PiiMappingStore. Memory is preserved across the entire conversation with no extra plumbing.

Benchmark

To evaluate the impact of the middleware, we designed a paired-sample benchmark that executes the same workload through two paths: one without the middleware and one with PiiShieldChatMiddleware enabled. Each pair is run back-to-back for every message, with execution order randomized to minimize the effects of transient LLM and network variability. This allows us to isolate the per-pair latency difference with high fidelity.

Please refer the below GitHub repository for more details on the benchmark implementation: 

pii-agent-demos/benchmark

We report the median, 95th percentile, and 99th percentile of these differences across 1,000 runs. All tests were conducted against a locally deployed PII Shield service running in Docker. The benchmark harness also includes a no-op mode, where the LLM call is bypassed, enabling precise measurement of middleware overhead in isolation. To keep total runtime practical, the framework supports concurrent execution of request pairs. For transparency and reproducibility, all raw samples, aggregated results, and a complete environment fingerprint are persisted to disk for every run.

Our findings show that PiiShieldChatMiddleware introduces a median latency overhead of approximately 70 ms per interaction, with a 99th percentile overhead of approximately 200 ms. The majority of this cost is attributable to the PII Shield service’s inference time rather than the middleware layer itself. It adds roughly one-tenth of a second per turn - a modest and predictable trade-off for ensuring that raw personally identifiable information is never exposed to the model context.

Metric

Overhead per turn

Median

71.27 ms

Mean

84.09 ms

95th percentile

189.29 ms

99th percentile

207.44 ms

Conclusion

Agents multiply every privacy-sensitive boundary by the number of LLM hops and tool invocations. Relying on developers to consistently route calls through a downstream PII Shield is not a robust strategy.

By integrating PII Shield directly into the Microsoft Agent Framework as a ChatMiddleware + FunctionMiddleware pair, these concerns are addressed systematically:

  • Automatic anonymization on every LLM call - even during multi-step agent loops.

  • Seamless restoration of real values for tools - placeholders are transparently resolved before execution.

  • Automatic re-anonymization of tool outputs - ensuring that raw PII from systems like CRM never re-enters the model context.

  • Consistent identity mapping across turns - placeholders such as {{PERSON_1}} remain stable from the first interaction through to the seventieth.

  • Flexible deployment model - a single switch allows you to move between in-process (library) and shared-service (API) modes.

This post focused on protections inside the application - embedding PII Shield within the Agent Framework so that a single agent, or even an entire fleet within a shared codebase, is secure by default. In the next post, we zoom out one layer to explore PII Shield in combination with Azure API Management. Here, the privacy boundary shifts to the gateway, ensuring that every call to an LLM backend - regardless of application, language, or team - is intercepted, anonymized, forwarded, and de-anonymized through APIM policies. The principle remains the same, but enforcement moves from the agent runtime to the network edge.

Published May 13, 2026
Version 1.0
No CommentsBe the first to comment