Article · Security architecture and AI
When the business system becomes a tool for the customer's AI
Security architecture, authorization and controlled disclosure when organizations connect their own AI agents to a multi-tenant system over MCP
Two architectures side by side. On the left, both the language model and the business system sit inside the system's own control. On the right, the AI agent runs in the customer's environment, with the customer's model, vendor and memory, and connects to the business system through the MCP entry point.
In an earlier article I described how an AI assistant can be built into a business system without getting more access than the user. This article covers the opposite direction: how the system can be opened to an agent that belongs to the customer. The Model Context Protocol (MCP) makes the connection easy. This time I do not own the model. The vendor, the region and the memory are the customer's choice. I describe the principles I build on, the trade-offs along the way and the decisions I changed as the threat model became clearer. The article describes the architecture, the security requirements and what I learned along the way, not a particular production environment or a roadmap.
The new trust boundary
When I build the assistant myself, I choose the model, vendor, region, retention rules and tools. With an external agent, the only thing I control is what the system answers when the agent asks. Everything after the response belongs to the customer and the customer's vendor.
That changes the threat model in four ways.
The agent may be manipulated. The customer might ask the agent to summarize an email that contains an instruction to fetch everything about the staff. I cannot stop the attempt. I can limit what the attempt gets back.
What has been disclosed cannot be recalled. AI vendors may store conversations and memories, and consumer accounts may be used for training. For that use, the vendor is no longer the customer's processor. Every field that is sent out has to be treated as permanently outside my retention and deletion.
The vendor is a risk in its own right. A single client vendor may hold tokens for connections at many organizations. If that vendor is compromised, every connection it holds can be exposed at once.
The agent is a machine. It asks quickly, often and systematically. A reasonable question from a person can turn into mapping when a loop asks it a thousand times.
The main principle follows from this: the protection sits in what I control, which is who may ask and what goes out. There is no language model on my side of the boundary. The tools are deterministic functions with schemas for input and output, and the agent does the rest.
Read access is not permission to disclose
Access control decides what the user may see. Disclosure control decides where the information may go. A conventional business system asks whether the user can read a row. A system that opens up to external agents also has to ask whether the user can pass the information on through this integration, to this environment. The answer is built from five layers:
| Layer | Question |
|---|---|
| Identity | Is the token valid, and does it belong to an active profile? |
| Permissions in the organization | Does the employee have access to this information in the app right now? |
| The integration | Has the organization enabled agents, approved this client and not restricted this employee? |
| Scope | Did the employee approve this category of tools when connecting? |
| Disclosure | May these fields leave the system at the organization's level? |
Effective access is the intersection of the employee's permissions, the scope the employee approved, the organization's policy and any restrictions on the employee. None of this is stored in the token. If the employee loses a permission, the agent loses it on the next call. If the employee leaves, the profile is closed and the connection goes with it. Scopes are subsets of permissions and are not tied to role names. If the agent asks for something outside its scope, it gets an error naming the missing scope, and a wider scope requires a new approval.
Effective access is the intersection of the employee's permissions, the organization's agent policy, the scope the employee approved and any restrictions on the employee. A separate disclosure control then decides which fields may leave the system. In the example the agent gets the number of open tasks, their status and due date, but not the responsible person, free text or the organization's own assessments.
The MCP specification covers authorization at the transport level, the token's audience and the ban on passing the token on. That is a necessary foundation. The rules for what may be disclosed have to live in the application.
An approved client is not an approved account
The organization approves a client application. Which account the employee uses inside that application is invisible to me.
| What I can control | What I cannot control |
|---|---|
| The client's id and redirect addresses | Whether the account is personal or managed by the organization |
| The organization's approval of the client | The vendor's retention settings for the account |
| Which fields are disclosed | Which model the client uses |
| How long the connection lives | What the client does with what it receives |
An approved client id does not show that processing happens in the organization's own business environment. That affects the contracts, the transfer assessment and how much can be sent out. The first phase therefore sends no names, contact details or free text, only numbers, dates and fixed values, and the organization has to confirm its responsibility before the feature is turned on.
Nor does the client id prove which software is actually calling. The clients are public and have no secret. Exact redirect addresses, PKCE and the employee's approval make it hard to hijack a connection, but they do not attest the application. What I can block with certainty are the connections registered under a client identity.
Why open up at all
My first position was not to. I saw the MCP surface as the most exposed part of the AI infrastructure, and an internal assistant covered the need. I still made the tool catalog declarative, so that an external surface could later be a thin adapter.
My view changed as it became clear that more and more people do their daily work inside their own agents. What I like most about this shift is that users no longer have to learn a new interface for every task. Business systems can remain specialists in their own domain while the agent helps the user work across them. The value of a business system lies in its domain rules, data, permissions and workflows. Screens are still needed for overviews, visualization and complex tasks, but they do not have to be the only way in.
Three decisions limit what is opened:
- Daily operations and getting things started. The agent should answer what is due, what is open and what the law requires. Exports and full lists do not exist in the agent surface in any phase. Anyone who needs an export logs in.
- A template instead of data where that is enough. If the agent is helping with something new, it gets structure and legal references from a published template, with a link into the system. The organization's own assessments are not included.
- One registry, several adapters. Each tool is described once, with its name, permission requirements, scope and input and output schemas. The MCP adapter reads the registry, and a REST interface for integration platforms can read the same registry later. A parity check fails if the database catalog and the registry disagree on name, permission, category, privacy class, arguments or fields.
Identity and authorization
A dedicated, narrow authorization server
I started from Supabase's built-in OAuth server, which is in beta, and tested it in a short spike before building anything. It supported PKCE, metadata and dynamic registration. It did not support client metadata documents, did not bind the token to the resource and had no custom scopes. The decisive finding was that the agent's token was a full login session. With it, the agent could read the email address, register a new two-factor method and change the password, and so lock the user out. The aim was to give the agent access to due dates. The ability to change the user's password was a less welcome extra. I found no setting that turned this off. A leaked token could have meant account takeover.
Left: the platform's built-in token was a full login session that gave access to business data over REST, the email address, registration of a new two-factor method and password change. Right: the chosen opaque token lives for 15 minutes, is bound to the resource and only reaches permitted tools through the MCP entry point.
I also looked at ready-made authorization servers and services. They solved the protocol, but moved the truth about connections out of the database and added a sub-processor. I ended up with a dedicated, narrow server in two server functions, one for OAuth and one for MCP, since they have different error semantics and different limits. The built-in OAuth server is turned off in every environment, and a check in the build pipeline makes sure it stays that way. I will revisit the decision when the platform can restrict such sessions and bind tokens to a resource.
A custom authorization server is more security-critical code to own, and small protocol mistakes can have large consequences. I made the choice deliberately for this threat model, and it raises the bar for testing and review. I do not recommend it as a general pattern. I keep it small by writing as little as possible myself: no custom cryptography, no signed tokens, no login or two-factor flow (those happen in the regular app), standard URL parsing and an approval page that is an ordinary page in the app. The server follows these standards:
| Standard | What it covers here |
|---|---|
| RFC 9700 | Current security best practice for OAuth 2.0, including rotating refresh tokens for public clients |
| RFC 7636 | PKCE, with S256 only and no downgrade to plain |
| RFC 8707 | Resource indicators, so the token is bound to one resource |
| RFC 8414 | Authorization server metadata |
| RFC 9728 | Protected resource metadata |
| RFC 9207 | The issuer is included in the authorization response |
| RFC 7009 | Token revocation |
| MCP specification | Authorization and protocol in versions 2025-11-25 and 2026-07-28, with client metadata documents |
The principles:
- An opaque token. The token is a random 256-bit value with a fixed prefix and a short checksum. Only a hash is stored. The prefix lets secret scanning find a leaked value, and the checksum lets the server function reject garbage without a database call. A token signed with the platform's key would have been accepted by the database's REST interface and the login service. A token signed with my own key brought no benefit, since the connection is looked up on every call anyway. The opaque token can be revoked and needs no signing key.
- A short-lived bearer token. Anyone who steals an access token can use it until it expires after 15 minutes or is revoked. Sender-constrained tokens (DPoP) were considered, but the major clients do not support them today. They are an option for first-party clients later.
- Authorization code with PKCE only. The code lives for 60 seconds and is stored only as a hash. Redemption is atomic, and the code is bound to the client, the resource and the redirect address. A failed verification attempt kills the code, and a reused code revokes whatever it issued.
- Exact redirects. The redirect address is compared as a raw string against the catalog, without normalization. Errors that occur before the address has been validated are shown as an error page and are never sent as a redirect. Local addresses and IP addresses cannot be added to the catalog without a new migration. Clients that use a local address on the developer's machine are left out until they have their own rule with their own tests.
- Known clients only. Clients come from a catalog with an exact client id and exact addresses, never host patterns. No client is allowed in an organization until an administrator has selected it.
- The client's own metadata is never shown. A name and logo supplied by the client itself could be aimed at the person approving. The approval page shows the name and domain from the catalog.
- Every connection requires a new click with fresh two-factor authentication. The approval is never remembered. It is refused in an impersonation session, including one left open by mistake, and the platform's operations accounts cannot connect agents. Others in the organization with the right to manage agents are notified in the same transaction.
- The approval is bound to the browser. An internal review showed that a forwarded approval link could let an attacker complete the flow with their own PKCE. The approval now requires both a one-time value in a secure cookie on the server's domain and a one-time token that is only issued to the signed-in account. The cookie is bound to the host name and is not sent with requests from other sites. The pages in the flow cannot be framed by another site, and no response containing a token is cached.
- Lifetimes are data. The access token lives for 15 minutes, the refresh token expires after 30 days without use, and the connection has an absolute cap of 90 days. The values sit in a catalog with a floor and a ceiling and can be changed without new code. The organization's usual session length limit applies to the approval session. The agent is governed by its own lifetimes and switches.
- Rotating refresh tokens with reuse detection. If a refresh token is used twice, the whole family is revoked, also when the reuse involves an older generation. I chose not to have a grace window for parallel refreshes. Such a window would let a stolen token be used without the family being revoked. The cost is that a client that refreshes twice at the same time, or retries after losing the response to a refresh, has to reconnect. If such revocations turn out to be races rather than theft, a narrow window is the alternative.
- Revocation bound to the client. The client id does not prove who is asking, so my first instinct was to let anyone holding the token revoke it. RFC 7009 does, however, require the server to check that the token was issued to the client requesting revocation, and the server performs that check.
- A fixed address from day one. The customer pastes the address once. It lives on its own domain, with a separate issuer per environment, and is built from configuration, never from the request's host header.
One entry point for business data
Everything the agent reads of business data goes through a single function in the database. The login flow has its own narrow functions alongside it. The server function in front is a thin adapter with no model and no session.
The path in has several steps. The proxy exists because the discovery address for OAuth metadata could not be routed directly to the server function, and because the address the customer has pasted must never change. The proxy filters headers, forwards only the five that are needed, adds a shared secret and does no logging of its own. The server function checks the secret first, in constant time. If it is missing, the call is rejected with an empty 404 response. No control exists only in the proxy, because the server function's address is public too.
For the path from the server function to the database, I considered three options:
- A service role that bypasses row-level security. Rejected, because a single bug would have given full access.
- Opening the entry point to the anonymous role. Rejected, because the anonymous key is public. The proxy, origin check, scanner and rate limits in the server function would all have become optional, and every defense against guessing would have had to live in the database.
- A dedicated login role through the connection pool that can only call the entry point.
I chose the third, with a latency requirement of a p95 under about 100 milliseconds. In the test environment I measured 200 warm calls over an open connection and 200 cold calls with a new connection, one after the other, against an early version of the entry point. Warm calls gave a p95 of 26 milliseconds and cold calls 193 milliseconds, with no errors. The requirement held for warm calls and failed for cold ones. I adjusted it: warm calls govern, and cold calls should stay below about 250 milliseconds. A public entry point weighed more heavily than a cold call of a fifth of a second. I was more willing to adjust a performance requirement than a security boundary.
The role can log in, inherits nothing and cannot be used by the REST layer. It may only call the entry points, has no table privileges, a cap of ten concurrent connections, short timeouts for statements, locks and idle transactions, and no statement logging. The schema holding the agent functions is not exposed in the REST layer. The entry point runs with its owner's privileges and a fixed search path, because it has to read tokens, switches, budgets and logs that the agent must never reach. The connection cap is deliberately low so that the agent surface can never take the connections ordinary users need. It is based on measured use and can be adjusted.
The tool functions are separate from the entry point. They are owned by a dedicated role that cannot log in, cannot bypass row-level security, owns no tables and only has read access to the tables the tools need. Before calling a tool, the entry point sets the same context as an ordinary login, so the policies apply to the agent as they do to the user. The role has to be carried by ownership, because a function running with its owner's privileges cannot switch roles midway.
The call goes from the agent through the proxy in the EU and the server function to a login role in PostgreSQL that can only call the entry point. The entry point sets the identity context and calls the tool function, which has an explicit filter and RLS policies. Both layers rely on the same foundation of identity context and permission functions. Only rows from organization A come out.
That last point is why I first set row-level security aside in the agent surface. In the preliminary investigation I tried switching to the ordinary user role inside the entry point, and the database refused. A separate owner role was an alternative, but the policies only applied to the ordinary user role, and the solution looked like more work than it was worth. The functions got explicit filters instead. A later review of the design made it clear that row-level security was no longer the last line of defense. I took the question up again with ownership as the starting point: the policies must also apply to the new role.
Each function also filters on organization, profile and permission itself, using the same permission functions the policies use. I considered removing the filters once the policies apply, and chose to keep them. The layers catch different mistakes. A policy that is too broad is stopped by the filter, and a filter with a bug is stopped by the policy. The field map catches neither, since a permitted field from the wrong organization is still a permitted field. The filters also give the error semantics I want: an id from another organization gets the same response as an id that does not exist. The cost is a few milliseconds per call for the policies, which is small compared with the value of a layer that holds on its own.
The layers are still not fully independent. They share the identity context the entry point sets, and the same permission functions. A bug there could make both layers accept the same lookup. The entry point is therefore the step that establishes identity, and only the entry point may set the context. The database does not by itself stop other functions from setting it, so an automated check in the build pipeline verifies that no other function does. The shared functions are tested separately in the agent context: a missing context returns no rows, and a conflicting organization and profile are refused.
Each layer is also tested alone. Probes with two organizations and several permission levels within the same organization run against every tool. A sabotaged copy of one filter must still return zero rows from another organization, and the same must hold when row-level security is turned off and only the filters remain. A probe checks that row-level security is actually active for every table in the context the tool reads from, and views in the call graph run with the caller's privileges. After the context is set, the entry point checks that the organization and profile match the connection. The automated checks for tables with special categories of data and for platform access also cover the schema with the agent functions. A static check in the build pipeline fails if a tool function gets an owner that can bypass row-level security, reads secrets for service access or calls anything other than the entry points. Apart from the database connection, no function in the chain can make outbound network calls, and a separate probe makes sure it stays that way.
Three test setups. A: the filter and RLS both work. B: the filter is a sabotaged copy, and RLS stops the lookup. C: RLS is turned off, and the filter stops the lookup. In all three, a lookup against another organization must return zero rows. The shared foundation is tested separately.
On every call, the entry point does the following:
- Resets any session settings the caller may have set, so that a reused connection does not carry context with it. A probe checks that the context is confined to the transaction.
- Looks up the token. An unknown, expired or revoked token gets the same response.
- Checks the switches at platform, organization and employee level, that the client is approved under the organization's rule for receiving environments, that the organization and profile are active, that the account is not an operations account, and that the call is within the rate limits.
- Sets the agent context locally in the transaction, with the organization and profile from the connection and the lowest authentication level. The agent never gets a higher level, and the two-factor check at connection time never counts as fresh two-factor authentication on later calls. The strong authentication check for ordinary sessions got its own branch for agents, which relies on two-factor having been fresh when the agent was connected.
- Looks up the tool in the catalog and checks scope, category, privacy class and the employee's permissions. Only argument names the catalog knows get through, so an organization or person can never be passed in as an argument.
- Calls the tool function by a name from the catalog, never from input, then deducts from the read budget, cuts at the row cap, filters the fields and writes the call log.
Errors have fixed codes. A database error can echo the value that was passed in, such as a name the agent pasted from an email, so neither the error text nor the input is returned. An id from another organization gets the same response as an id that does not exist. If the employee lacks a permission, the entry point responds with "tool denied" rather than an authorization error. Clients read an authorization error as a demand to log in again and end up in a loop.
The tool list requires a valid token and is empty when any of the checks fail. It is not filtered on the employee's permissions. The list is a view, and it is the call that gets checked.
Controlled disclosure
The tools: how little does the agent need
Each tool is built for one task and fetches only the fields that task needs, with a fixed row cap per call. I went through all the internal assistant's tools and placed each one in a phase or in "never". Some were merged, several were deferred to later phases, and some were marked "never".
The principles:
- An aggregate instead of a list where a list could single out people. The agent gets counts per status and severity.
- The link is a release valve for personal data. The agent points to the case, and the person sees the details in the system with their own permissions. A link carrying a stable id for a person or an incident can itself help someone piece things together, so links only carry ids that are already classified for disclosure.
- No name search. A tool that looks people up by name answers whether a particular person works there. Such entry points do not exist in the agent surface.
- No exports. A fixed row cap, no cursor-based paging, and date arguments bound to an operational window. The control is structural: the output schema cannot allow more items than the row cap.
- Ranking, evaluating and assigning work to individual employees never goes through an external agent. These are the uses the AI Act treats as high-risk in employment.
- Dates without times where the time is not needed. A deadline set a fixed number of hours after a report reveals when the report was submitted. Deadlines are therefore rounded to the date, and tasks that stem from a personal injury report are left out of the agent surface.
- The product's own content is not included. Course material and other content that is part of the product is not sent out, since a bulk extraction would copy the product.
- A narrow protocol surface. Batching, sampling, elicitation, roots, resources and prebuilt prompts are off. Only five methods are allowed. The request body is capped at 32 KiB, and the server is stateless.
A deterministic tool with no language model on my side also makes the legal assessment simpler. The server performs lookups and filtering. The Commission's guidelines on the definition of an AI system place such rule-based lookups outside it. That applies to this component. The system as a whole and how it is used are assessed separately, and a lawyer is to confirm the assessment.
Field by field
Row-level security decides which rows the user can see. It says nothing about which fields are safe to send out. A user who can open an incident in the app also sees its description, and that may contain names and health information.
Every field in every agent response therefore has a privacy class based on what the field is meant to contain:
| Class | Intended content |
|---|---|
| 0 | Controlled values that do not identify anyone directly: numbers, dates, controlled vocabulary, legal text, the system's own catalog text |
| 1 | Organization text: names of procedures, rooms and documents |
| 2 | Names, ids and contact details of employees |
| 3 | Information with elevated privacy risk |
| F | Free text about incidents and people |
Whether something is personal data does not depend on its data type. A date can be a person's first day of sick leave, and a room name can contain the name of an employee. The class says what the field was designed for. The content and context, especially in combination with other fields, can be something else. The field map enforces the class, but it does not guarantee the content. The first phase therefore only sends class 0 fields that the tools compute themselves or take from controlled lists. Organization text in class 1 can let names slip through and requires a separate decision by the organization.
Each field also has a form: full, pseudonym or never. I considered a reduced form with first name and initial. It was set aside, because pseudonym, role, link and the employee's own data covered the need. The form is reserved, and the automated check fails if anyone starts using it.
The protection has four layers:
- The database catalog cannot contain class 3 or F.
- Each tool function projects only the fields the organization's level allows.
- The entry point filters the response against a field map before it leaves the database. A field goes out only if its path is in the map with a permitted class and form. Everything else is removed.
- The server function projects onto the output schema and scans the whole response for patterns such as national identity numbers, email addresses and phone numbers. A match rejects the entire response and is logged without content. Names cannot be caught with patterns, so the scanner is a safety net behind the field map.
Six fields from a constructed row pass through four layers. Health information and free text are stopped in the database catalog. The procedure name and the responsible person are stopped in the tool's projection. Status and due date go out. A scanner match rejects the entire response.
The classification lives in the database, in the same functions that fetch the data. The server function only checks. A probe calls every active tool through the entry point and requires every path in the response to be in the field map. It also follows the call graph from each tool and fails if it reaches a table with special categories of data. Quasi-identifiers such as date, category and department cannot appear in the same list item as a person field. Each of them carries a low risk of identification on its own, but together they can point to one person.
Pseudonyms
The first phase sends no pseudonyms. They belong to a later phase, when an agent helping with follow-up needs to refer to the same person as last time without getting the name.
- Per connection. The same employee has different pseudonyms in different connections, so two agents cannot link the identities directly through the pseudonyms.
- Rotated per period. Otherwise the vendor's memory could gather information about one pseudonym over months, until it is in practice an identity. The length of the period is a setting. The automated check fails if a field gets the pseudonym form without rotation.
- Resolvable only from inside. If the agent uses a pseudonym in a draft, the system finds the right person. The agent can never go the other way.
- A role where that is enough. "The team lead" or "the managing director" is often more useful and reveals no more than what is already known in the organization.
Pseudonymization reduces risk, but it does not make the information anonymous. An agent may have access to the customer's email, calendar and documents, and can identify the person behind a pseudonym through the content. Rotation prevents direct linking over time, but not linking through the surrounding context. The disclosure rules therefore treat pseudonyms as personal data.
Small numbers
In an organization with five employees, "one serious incident last month" can point to a person. Two aggregates can also be subtracted from each other.
On Monday the count is 12 and on Tuesday 13. Both are above the threshold of 5, but the difference is one new person, and together with the duty roster that can reveal who it is.
- No threshold for numbers that cannot be tied to people, such as the number of documents and procedures. Whether a number can be tied to people is decided per tool, not by data type.
- A minimum cell size for numbers about people. Values below the threshold are only shown as being below it. The default threshold is 5, so values from one to four are shown as "under 5". If the denominator is below the threshold, nothing is shown. When the number concerns people, the denominator is the number of distinct people, not the number of events, because many events can come from one person. Zero also says something, namely that nothing has happened. Whether zero is shown exactly is therefore decided per tool. The threshold follows practice at statistical agencies, which use thresholds from 3 to 10. It sits in a registry with an allowed range from 3 to 20 and can be adjusted without a code change.
- A stricter threshold for the most sensitive categories, and no such aggregates until a separate assessment has been made.
- Fixed calendar windows. Month, quarter and year, never rolling windows or freely chosen dates. The same cell is not sent both with and without a filter in one response.
- Nested windows. The month sits inside the quarter and the quarter inside the year. The quarter minus the month would give a category cell with a small number, so the breakdown by category is only sent in the yearly window.
- Small organizations get less. If the organization has fewer active people than the threshold, the person-related aggregates are turned off.
- A daily frozen snapshot. Incident counts are as of midnight yesterday. With real-time counts, an agent could compare before and after a report and, together with a duty roster, work out who reported. A one-day lag is no problem for daily operations, and the snapshot is deleted after a week. The snapshot covers every tool with numbers about people, not only the incident counts.
- Composite measures count. A score or an inspection status built on incidents gets the same delay and threshold as the incident counts. Otherwise a user without access to the incidents could work the score back to them.
This reduces the risk, but does not eliminate it. Even the change from one day to the next can single out one person, as figure 7 shows. An agent with memory can collect responses over several days and subtract them: today's quarterly figure minus the months it has seen before, or today's yearly figure against the yearly figure from an earlier day. The same applies across categories and tools, and in combination with what the recipient already knows. The read budget does not help here, since one call a day is enough, but it makes systematic mapping slow and visible. Statistical offices use rounding and secondary cell suppression against such differencing, and thresholds computed on unique people rather than events. Both become relevant when agents get numbers that are more about people.
Where the data goes
An organization may have invested heavily in European hosting, data processing agreements and access management. If an employee then connects a personal AI account to the system, information from the organization can end up in an environment nobody has assessed. The business system can be properly secured by traditional authorization standards and still be the channel for an unfortunate disclosure.
The GDPR does not prohibit processing outside the EEA. A transfer can be lawful on the right basis. The risk lies in transfers nobody has checked. If the information is anonymous, the rules on transfers to third countries do not apply to it. If it is personal data, the transfer needs its own legal basis. For the customer's vendor, even numbers without names can be personal data, because the customer can link them to its employees, and an agent that also has the customer's email and calendar can do so itself. I have therefore chosen to treat everything that goes out as personal data, and I have done three things.
The first is the allocation of roles. The agreement assumes that the agent vendor is the customer's processor, and that the system acts as processor up to the point of disclosure and discloses on the customer's documented instructions. Whether that holds depends on the contract between the customer and the vendor, the vendor's own purposes and which account is used. This is set out in a separate addendum to the data processing agreement, where the customer is responsible for the legal basis and the transfer. If the vendor uses the information for its own purposes, such as training on a consumer account, it is an independent controller for that use, and that use falls outside the addendum.
The second is an approval rule for receiving environments. Every approved client has a registered assessment of where processing takes place, and a client without such an assessment gets the same response as a client that is not approved. The rule is the organization's policy. It does not replace the legal basis for the transfer. Here I had to adjust. My first default accepted only the EEA and countries with an adequacy decision. That would have shut out both of the major AI clients. I added a European contracting party as an approved receiving environment, but only for tools without numbers that can be tied to people, and only when the vendor's written confirmation of the contract chain has been registered: who receives the data, on whose behalf, on what basis, and who is the exporter and importer. A European contracting party does not by itself say where processing takes place, so the contract chain has to show it.
The third is keeping the data in Europe wherever I can. The proxy in front of the server functions runs in an EU region with a provider that is already a sub-processor. An alternative using edge functions with another provider was set aside because EU binding there required a more expensive plan, and a plain rewrite rule was rejected because it runs globally.
The largest residual risk is personal consumer accounts, as described above. It cannot be solved technically. I reduce it with a catalog of approved clients, a confirmation of responsibility from the organization before the feature is turned on, and a log the customer can see.
Misuse and revocation
Budgets and rate limits
The entry point has rate limits per connection, stricter for accounts in a high risk class, and per organization. On top of that, agent calls have their own read budget per hour and per day.
I changed two decisions here. At first the budget was only going to observe and let calls through if the counter failed, so that a fault would not cut the agent off from legal text and deadlines. I reversed that: the agent budget cannot be set to observe-only mode, cannot be turned off and closes on failure. A fault in the counter must not open the door to unlimited reading.
The second decision concerned who takes the hit. Originally a serious budget breach was going to throttle the employee's account, as it does for exports. That would have punished the employee for something the agent did, perhaps after an injected instruction. Now the connection loses its access, and the employee and whoever manages agents are notified. The account is only throttled on a separate signal that points to the account. Any extra confirmation after many extractions applies to the same connection and category, never the account.
A budget per hour and day limits the pace. It does not cap how much can go out in total over weeks and months.
Decoy tools
Some tool names exist only as traps. They give a signal with limited coverage. A name nobody can guess only catches clients that go looking, and a name that is easy to guess gives false positives from agents that invent tools. They never appear in the list the agent gets, are stored only as hashes and are added per environment through an audited function with fresh two-factor authentication. The names are not in the source code. Unknown tool names with the right format are passed on to the entry point, so the traps see them. A scope that is never advertised works the same way in the login flow and exposes a client that does not behave like the known clients.
At first, the first hit was going to revoke everything and require a new connection. I made the response gradual: the connection is revoked and the profile and client are quarantined for a period, and a new hit within a longer window pauses agent access for that employee until an administrator turns it back on. The account and the work in the app are not affected. A hit may come from content the agent has read, and it says nothing about who did something wrong. The employee is notified first, in wording that does not accuse, and the administrator gets a neutral message. The caller gets the same response as for an unknown tool.
A compromised client vendor
Should bulk extraction from one client be stopped automatically, or only flagged? I chose automatic blocking above a threshold. A blocked client can be let back in the same day, and a bulk extraction cannot be undone.
The rule had to be tightened. An internal review showed that two organizations, including ones on trial access, could trigger blocking of one of the major clients for every organization. Now each organization counts with a cap, and blocking requires traffic from several established organizations. That reduces the risk of someone shutting a client out for everyone, but does not remove it. The threshold is data and is adjusted as more organizations use the surface.
The switches
| Level | Effect | Reversible |
|---|---|---|
| Platform, switch | All tool calls and new connections are stopped. Revocation still works | Yes, the connections come back to life |
| Platform, revoke all | Every connection on the platform is revoked | No, a new connection is required |
| Platform, one client | The client is blocked and its connections are revoked | The block yes, the connections no |
| Organization, kill switch | All the organization's connections are revoked, and new ones are blocked | No |
| Employee, pause | The entry point refuses every call from the employee's agents | Yes |
| One connection | Rejected on the next call | No |
While an employee is paused, token refresh still works. It must be possible to lift the pause without a new connection, otherwise it becomes a permanent revocation. Alarms from the entry point are picked up by a scheduled job, so the entry point never makes outbound calls inside the transaction.
Revocation
Revocation happens in the database, in the same transaction as the event that triggers it: the profile is closed, the organization becomes inactive, or an emergency brake is pulled. It takes effect on the next call. A call already in progress, and data already disclosed, are not covered. Each call is a single transaction, and the window in which a call in progress can complete is bounded by the database's statement timeout. A guard refuses new connections while any of this applies. Reactivation brings nothing back to life, and a new connection is required. Unused connections expire on their own.
A timeline with the revocation in the middle. Responses already delivered may still exist with the recipient. A call in progress completes. A new call after the revocation is rejected.
Logging without content
The call log is an audit trail, a basis for misuse detection and the customer's window into usage. It must not itself become a place where sensitive data accumulates.
One row per call holds the organization, profile, connection, client, tool, category, outcome, number of rows, privacy level, correlation id and time. Arguments are never stored with their values. The log therefore contains personal data about usage, but no returned field values.
The plan was to store argument names and a hash of the value. The value behind a plain hash of a name or a national identity number can be found with a dictionary attack. Free-text arguments are stored only with name and length. For id arguments, a keyed hash is stored. That is derived data. Without the key it is hard to recover the original values with a dictionary attack, but anyone holding the key can try candidate values. The key is therefore secret, and the organization is part of the computation, so values cannot be linked across organizations. The traceability I need is who, which tool, when and how much.
The log is append-only. Updates and truncation are rejected, and deletion happens only after the retention period of 12 months. That period sits in the registry with a range from 6 to 36 months. Rejections before the rate limit are logged with a cap per connection, so an attacker cannot flood the log. The rate limits still count such attempts, without storing the token.
Authorization headers, codes, verifiers and refresh tokens are not logged at any step. A test sends fake tokens with a unique marker in the wrong places and then searches the logs at every step. A token in the URL is rejected by the server function, but the platforms that run the proxy and the server function log the request line before the request reaches my code. A token that has been seen in an address is revoked.
Technical rows from the login flow are a justified exception to the soft-delete rule. Expired requests and used one-time codes have no audit value and would grow without limit. They are deleted after a cleanup window, while the audit event remains. Requests can be created before login, and auditing them would have let an anonymous party fill the undeletable log.
The people in the system
Control for the customer
An organization that opens up to agents must be able to see and control them. Control sits with the organization and the employee, not with the vendor.
- Off by default. No employee can connect until the organization has turned the feature on, confirmed its responsibility and chosen modules and clients.
- An overview of connections: the client, when it was connected, when it was last used and which categories have been used, never content.
- Per-employee controls: turn it off for one person, limit categories, revoke a single connection. The right to do this is a separate permission.
- A kill switch with fresh two-factor authentication, and a notification when a new connection is created.
- Employees see their own usage and can disconnect themselves.
Consideration for employees
The integration should give the organization control over the agents. It must not become a new tool for monitoring employees.
Usage statistics per employee can in themselves be a control measure under the Norwegian Working Environment Act, with requirements for consultation, information and proportionality. This had to be fixed. A review showed that everyone who could administer agents could see usage per employee, while the text given to employees said something else. Now administration and history are separate. The overview shows numbers per client, category and tool in fixed calendar months, with the same small-number protection, also for the number of connections. A rolling window could have let two days be subtracted from each other. Other surfaces the administrator sees, such as the audit log, must not link a connection to a named employee either. History for a named employee requires a separate permission, fresh two-factor authentication, a purpose from a closed list, a justification and an audit row per lookup. Under the Norwegian regulation on employer access to email, monitoring the use of electronic equipment is only permitted to operate the network or to detect and investigate security breaches, so the list is short, and a lookup for a security breach must refer to a registered incident. The organization has to consult and inform before the feature is taken into use. The system also shows the measure when the agent is connected.
The word consent is used for three different things, and in an employment relationship they have to be kept apart. Approval in the login flow is a technical delegation: the employee lets one client act on their behalf within a scope. The organization's approval of the integration is a decision about which clients and modules are allowed. The legal basis under the GDPR is a third question, and in employment, consent is rarely the right basis. In this text I use approval for the first two.
Writing only as drafts
The first phase is read-only. In a later phase, agents may contribute drafts. When an agent contributes something, a draft is created in the system. That is a write operation, but the draft has no effect until a person has approved it, with the same permission check and audit trail as if that person had written it. The draft is marked with the agent it came from. An agent can also create a link to a form, prefilled only with values from fixed lists and with no free text in the address.
A draft is still an attack surface. It may contain injected text and influence whoever approves it. Only the person who connected the agent, and those who can approve, see the draft. The text is shown as a draft from an agent and treated as untrusted. Each connection has a cap on the number of drafts. Creation is stored and audited, but the draft has no business effects, such as notifications or deadlines, until it is approved. A draft nobody approves expires after a fixed period.
Actions that assign work to a named employee, send notifications to employees or rank employees do not go through an external agent without a separate risk assessment. A machine account with no person behind it is on hold pending the same assessment.
How the boundary is tested
The disclosure boundary in the database
The disclosure boundary is tested deterministically, independently of how the agent behaves. A corpus of injection texts, each carrying a unique, unguessable canary, is planted in the test data. The corpus covers direct instructions in several languages, false authority, exfiltration through addresses and images, forged tool calls, serialization breaks, invisible characters and bidirectional control characters, homoglyphs, encoded content, role play, long payloads, file names and synthetic personal data.
The target columns are derived from the database catalog: every text column in the tables the agent functions read, followed through the helper functions. A new table in the call graph gets tested without anyone having to remember it. The probe calls every tool through the entry point and requires zero canaries in any response, also when they are split by invisible characters or encoded once. A deliberately sabotaged copy of one projection must make the probe fail.
The tests show which attack-carrying data was stopped under the conditions that were tried. They do not prove that injection is impossible, and a canary can disappear in a transformation while the rest of the text slips through. The main protection is that free text is not in the field map at all. Responses without customer text mean that security rests on the data boundary. It does not depend on the model refusing.
Attacker roles
The scenarios are organized by who the attacker is:
| Role | Principle under test | Counts as a breach |
|---|---|---|
| Agent with a valid token | Only its own rows, only within scope, no writes beyond drafts | Data from another organization, beyond scope or with personal data above the organization's level |
| Thief with a stolen token | The token is worthless elsewhere, and revocation works on the next call | The token works against other surfaces, after revocation or after reuse |
| Malicious employee | Planted text does not reach a colleague's agent, and aggregates in one response cannot be subtracted | A canary in a response, or a cell below the threshold that can be derived from one response |
| Compromised vendor | One client can be stopped everywhere, and bulk extraction becomes visible | Connections survive a block, or the volume rule does not trigger |
| Injected content | The agent can only call known tools, without personal data above the level | An unknown tool that actually runs, argument values in the call log, or content from the email in the log |
| Third party without an account | Registration, approval and redirects are strict | A redirect to a foreign host, fetches from internal addresses or an injected client name |
| Platform insider | Operators cannot connect or read covertly | Approval from a platform account or an impersonation session, or log reading without a trace |
Layers
The same scenario has the same number in every layer:
- Probes in the database that call the entry point directly, in the build pipeline on every change to the database layer. Most of them have a self-test that is meant to fail.
- Unit tests of protocol handling, error mapping, the scanner, redirect matching and display names, with fuzzing of the OAuth parsers.
- HTTP tests against the test environment with an independent OAuth client, weekly and before every release.
- Runs with real agents against the test environment, at least ten per scenario and client, reported as rates. The runs are repeated quarterly and whenever the tool catalog or the clients change, because the same model can answer differently from one run to the next, and the vendor can change the model or test variants without notice. Zero breaches in ten runs gives a one-sided upper bound of about 26 percent at 95 percent confidence, assuming independent attempts with the same probability, so this layer catches regressions and says little about rare breaches. It is the disclosure boundary that has to hold when the model follows an injection.
In the fourth layer, a "followed" injection measures the vendor's model. There are two oracles. The call log shows that the agent only called tools in the expected set and used no unknown arguments. Since the log stores no content, the test harness itself checks the responses and the agent's final answer for personal data and canaries. If a call outside the expected set returns personal data in the response, it counts as a serious finding, whatever the model did.
The tests for the token flow run with a short-lived token outside the build pipeline. A long-lived refresh token in the build pipeline would itself be a leakage surface. The attack scenarios for the login flow are run manually, and the token is kept out of the context of AI tools during development.
Emergency stop and separate review
Switches that have never been tried may not work. The emergency stop is rehearsed: the platform switch, the organization switch, revoke all, blocking a single client and rotating the secret between the proxy and the server function. Everything must stop on the next call, with timestamps logged, and the app must be unaffected. One rehearsal showed that manual blocking of a single client and revocation across the whole platform were missing. Both are now in place.
The whole flow is reviewed separately, without build context, with a fixed checklist and a requirement for a failing test before the fix, for every finding. Before an organization connects, there must be zero serious findings, and every medium finding must be closed or accepted. Automated testing and such reviews can reduce the scope of an external security review, but cannot replace it. The builders, the internal reviews and the test generators may share blind spots. An external security review is therefore still needed.
Decisions I changed along the way
| Question | First choice | Current choice | Why |
|---|---|---|---|
| External agent surface? | No | Yes, from one registry | More and more people work in their own agents, and the registry was ready for it |
| Authorization server | The platform's built-in one | Dedicated and narrow | The built-in token could have enabled account takeover |
| Owner of the tool functions | A role that bypasses row-level security | A dedicated role without bypass, with the filters kept | A bug in the row policy or a tool's filter should not on its own expose data from another organization |
| Latency requirement for the dedicated database role | p95 under 100 ms | Warm calls govern, cold calls under 250 ms | A public entry point weighed more heavily |
| Token revocation | Without client binding | Bound to the client | RFC 7009 requires it |
| Arguments in the call log | Name and hash | Name and length, keyed hash for ids | A plain hash can be cracked with a dictionary |
| Read budget for agents | Observe, allow on failure | Always on, close on failure | A fault in the counter should not open up reading |
| Budget breach | Throttle the account | Lose the connection | The employee should not be punished for the agent |
| Hit on a decoy tool | Full block | Gradual, non-accusatory | The hit may come from injected content |
| Reduced name form | Mechanism with opt-in | Set aside | Pseudonym, role and link covered the need |
| Templates | Full template text | Structure and link | Less content out and less to copy |
| Receiving environments | EEA and adequacy | Also a European contracting party, only for tools without numbers about people and with a confirmed contract chain | The first default shut out the major clients |
| Usage insight per employee | For all administrators | A separate permission with purpose and audit | Control measures under Norwegian employment law and email regulations |
| Deadlines in agent responses | Exact time | Date, with no tasks from personal injury reports | The time revealed when the report was submitted |
| Automatic client blocking | Two organizations could trigger it | Several established organizations | One organization should not be able to shut a client out for everyone |
What the vendor cannot guarantee
- What has been disclosed is permanently outside my retention and deletion. That is why no names are sent until a separate assessment has been made, and why pseudonyms rotate.
- Which account and which processing environment the employee has connected the client to.
- What the employee writes to the agent is visible to the vendor. The system only logs the length of free text and cannot stop anyone from pasting in information about colleagues. The same goes for data the employee can read: if connecting is too cumbersome, it can be pasted into a consumer AI by hand, outside every control.
- Aggregates from very small organizations can make people identifiable. I treat them as personal data, and a lawyer is to assess the threshold.
- An agent with memory can collect responses over time and infer more than any single response shows.
- A stolen access token can be used until it expires or is revoked.
- The entry point and the helper functions for tokens, budgets and logs run with their owner's privileges. They are kept small, read only their own tables and are tested separately.
- Intermediaries that terminate TLS see the traffic in clear text. They are my sub-processors and are listed in the agreement.
- An emergency brake pulled at the very moment a new connection is created can let it through. The entry point rejects it on the next call.
- What the user understands from an approval page is something only a person can judge.
Checklist: a business system opened to external AI agents
Trust boundary and login
- Put the protection in what you control: who may ask and what goes out. No model on your side.
- Test the built-in OAuth server against your threat model before you commit to it. A token that is a full login session can enable account takeover if it leaks.
- Follow RFC 9700 and resource binding, use only authorization code with PKCE (S256), exact redirects and rotating refresh tokens with reuse detection.
- Give the agent a short-lived opaque token, with lifetimes as data.
- Require fresh two-factor authentication on every connection, bind the approval to the browser, and never show the client's own metadata.
- Keep technical approval, the organization's approval and the legal basis for processing apart.
Database and access
- Reach the database through a dedicated role that can only call the entry point, never through a service role or a public key. Have the tool functions owned by a role that cannot bypass row-level security, keep the filter in each function as a separate layer, and test each layer alone. Test the shared permission functions and the identity context separately.
- Compute access on every call, and make a denial look like an unknown.
Disclosure
- Treat disclosure as a separate question after read access.
- Approve receiving environments per client, and remember that an approved client is not an approved account.
- Classify every field by what it is meant for, filter in the database, and let the scanner be a safety net.
- No name search, no exports, and pseudonyms treated as personal data.
- Protect small numbers with a minimum cell size, fixed and nested windows, dates without times and a daily frozen snapshot. Give composite measures the same protection, and treat the change from the day before and inference over time as residual risk.
- Writing only as drafts a person approves, with no business effects before approval.
Operations and control
- A budget that closes on failure, and breaches that hit the connection.
- Decoy tools with a gradual, non-accusatory response.
- Off by default, approved clients, an overview, per-employee controls and a kill switch. Separate administration from insight into individual employees' usage, and tie that insight to the purposes the law allows.
- Log metadata, never argument values, responses or secrets.
- Revoke in the same transaction as the event, and require a new connection after reactivation.
- Test the disclosure boundary with canaries derived from the catalog, test by attacker role, rehearse the emergency stop, and require a failing test before the fix for every finding. Get an external security review before production.
Closing
The first article was about how a language model can get access to a business system without becoming the security boundary. This time I do not own the model, and the question becomes what may leave the system and who can shut it off again. I believe many business systems will gradually become tools in agents their vendors do not control. For users, that opens new possibilities. For the systems, it means that connecting should be easy, extracting more than intended should be hard, and access should be easy to shut off again.
Sources
- Model Context Protocol, specification, authorization: modelcontextprotocol.io/specification/
- RFC 9700, OAuth 2.0 Security Best Current Practice: www.rfc-editor.org/rfc/rfc9700
- RFC 7636, PKCE: www.rfc-editor.org/rfc/rfc7636
- RFC 8707, Resource Indicators for OAuth 2.0: www.rfc-editor.org/rfc/rfc8707
- RFC 8414, Authorization Server Metadata: www.rfc-editor.org/rfc/rfc8414
- RFC 9728, Protected Resource Metadata: www.rfc-editor.org/rfc/rfc9728
- RFC 9207, Authorization Server Issuer Identification: www.rfc-editor.org/rfc/rfc9207
- RFC 7009, Token Revocation: www.rfc-editor.org/rfc/rfc7009
- RFC 9449, DPoP: www.rfc-editor.org/rfc/rfc9449
- PostgreSQL, Row Security Policies: www.postgresql.org/docs/current/ddl-rowsecurity.html
- Supabase, OAuth 2.1 Server: supabase.com/docs/guides/auth/oauth-server
- Supabase, OAuth 2.1 Flows: supabase.com/docs/guides/auth/oauth-server/oauth-flows
- EDPB, Guidelines 01/2025 on Pseudonymisation: edpb.europa.eu/news/news/2025/edpb-adopts-pseudonymisation-guidelines-and-paves-way-improve-cooperation_en
- EDPB, Guidelines 02/2026 on Anonymisation (draft for public consultation): www.edpb.europa.eu/system/files/2026-07/edpb_guidelines_202602_anonymisation_v1_en_0.pdf
- EDPB, Guidelines 05/2021 on the interplay between Article 3 and Chapter V GDPR: www.edpb.europa.eu/system/files/2023-02/edpb_guidelines_05-2021_interplay_between_the_application_of_art3-chapter_v_of_the_gdpr_v2_en_0.pdf
- EDPB, Guidelines 07/2020 on the concepts of controller and processor: www.edpb.europa.eu/documents/guideline/guidelines-072020-on-the-concepts-of-controller-and-processor-in-the-gdpr_en
- Court of Justice of the EU, case C-413/23 P, EDPS v SRB (pseudonymised data): curia.europa.eu/juris/liste.jsf?num=C-413/23
- Statistical Disclosure Control (UK Government Analysis Function): analysisfunction.civilservice.gov.uk/policy-store/statistical-disclosure-control-for-tables-produced-from-surveys/
- OWASP GenAI Security Project: genai.owasp.org/
- GDPR, Regulation (EU) 2016/679: eur-lex.europa.eu/eli/reg/2016/679/oj
- AI Act, Regulation (EU) 2024/1689: eur-lex.europa.eu/eli/reg/2024/1689/oj
- Regulation (EU) 2026/1744 amending the AI Act: eur-lex.europa.eu/eli/reg/2026/1744/oj
- European Commission, guidelines on the definition of an AI system (6 February 2025): digital-strategy.ec.europa.eu/en/library/commission-publishes-guidelines-ai-system-definition-facilitate-first-ai-acts-rules-application
- Norwegian Working Environment Act, chapter 9, control measures (in Norwegian): lovdata.no/dokument/NL/lov/2005-06-17-62/KAPITTEL_9
- Norwegian regulation on employer access to email and other electronic material, FOR-2018-07-02-1108 (in Norwegian): lovdata.no/dokument/SF/forskrift/2018-07-02-1108