core-plainid
Core library for integrating PlainID authorization into your AI applications. Provides text anonymization, message categorization, SQL query authorization, tool call authorization for MCP and other agent tools, and low-level PlainID API clients.
All components fully support both synchronous and asynchronous execution. The examples below use the async API; replace await calls with their sync counterparts (e.g. aanonymize → anonymize, acategorize → categorize, aget_permissions → get_permissions) for synchronous usage.
Installation
pip install core-plainid
The base install includes authorization clients, permissions provider, retrieval related classes and general utility functions. Additional features require optional extras:
pip install core-plainid[categorization-llm] # LLM-based categorization via LiteLLM
pip install core-plainid[categorization-zeroshot] # Zero-shot classification via Hugging Face
pip install core-plainid[anonymization] # Presidio-based PII anonymization
pip install core-plainid[anonymization-ahds] # Anonymization + Azure Health De-identification
pip install core-plainid[all] # Everything
The Content Controls Service integrations (PlainIDContentControlsClient, ContentControlsCategoryClassifierProvider, ContentControlsAnonymizer) need no extra: they call the service over HTTP instead of running models or Presidio in your process.
Upgrading from 3.x
Version 4.0.0 adds tool call authorization (see Tools Authorization) and has one change that can affect existing code:
- The default tools resource type of
PlainIDPermissionsProvideris nowMCP-TOOLinstead ofTools. If your PlainID tool assets use theToolstemplate, passplainid_tools_resource_type="Tools"to keep the previous result ofpermissions.tools.
SQLAuthorizerResponse has two new optional fields, outcome and coverage; existing code is not affected.
The framework packages move to new major versions with it, because they require core-plainid 4.x: langchain-plainid 4.0.0, langgraph-plainid 4.0.0 and maf-plainid 3.0.0.
Upgrading from 2.x
Version 3.0.0 has five changes that can affect existing code:
BaseCategorizerno longer takesall_categories. Its constructor takes onlyclassifier_providerandpermissions_provider. A custom subclass ofBaseCategorizerthat needs the category list must store it itself, or subclassCategorizer, which still takesall_categories. Code that usesCategorizerdoes not change.- A custom
CategoryClassifierProvidermust accept an optionalrequest_idargument inclassifyandaclassify, and inclassify_conversationandaclassify_conversationif it overrides them.Categorizerpasses it on every call. LLMCategoryClassifierProvidertakes its timeout fromtimeoutonly; arequest_timeoutkeyword is no longer turned into the timeout.PreparedRequestandResponseModelare no longer importable fromcore_plainid.clients.base_plainid_client. ImportPreparedRequestfromcore_plainid.models.request.prepared_requestandResponseModelfromcore_plainid.clients.base_http_client.- A subclass of
Categorizerthat overridescategorizeoracategorizemust also overridecategorize_conversationandacategorize_conversation. The LangChain, LangGraph and Microsoft Agent Framework integrations now call the conversation methods for message input, andCategorizer's conversation methods do not callcategorize.
The framework packages move to new major versions with it, because they require core-plainid 3.x: langchain-plainid 3.0.0, langgraph-plainid 3.0.0 and maf-plainid 2.0.0.
If you used the Content Controls integration from the unreleased 2.1.0 development version, also note:
ContentControlsCategoryClassifierProvidertakespermissions_providerinstead ofasset_type_id, and no longer takesmax_conversation_messagesormax_conversation_chars.- A conversation goes to
categorize_conversation, notcategorize. PlainIDContentControlsClienthas noclose,acloseor context manager, andtimeout=NoneraisesValueError.- The request and response models are in one file each under
core_plainid.models.requestandcore_plainid.models.response, andlast_user_messageis incore_plainid.utils.conversation_utils.
Setup with PlainID
Once you have installed the library, you can set up PlainID access.
- Retrieve your PlainID credentials to access the platform — client ID and client secret.
- Find your PlainID base URL. For the production platform you can use
https://platform-product.us1.plainid.io. Note the URL starts withplatform-product.
These are the 3 parameters you need to use with the library.
Note: Never share your credentials or store them in your code. Use environment variables or a secret management tool to store them securely.
Authentication
All components support three authentication modes. At least one must be available at request time.
| Mode | When to use |
|---|---|
| Client credentials | Provide client_id and client_secret at construction time. |
| JWT token | Provide only client_id at construction time and pass an auth_token per request via RequestContext. The Bearer prefix is added automatically if missing. |
| IDP provider | Provide only client_id at construction time along with an IdpAuthProvider for automatic OAuth2 token management. The provider fetches and caches tokens from your Identity Provider. |
When multiple modes are configured, the priority is: auth_token (per request) > IDP provider > client_secret. A per-request auth_token always takes precedence. If no auth_token is provided, the IDP provider is used to fetch a token. Only when neither is available does the client fall back to client_secret.
Using an IDP Provider
The IdpAuthProvider obtains and caches OAuth2 access tokens from an external Identity Provider. Tokens are fetched lazily on first use and automatically refreshed when they expire.
from core_plainid.utils.idp_auth_provider import IdpAuthProvider
idp_provider = IdpAuthProvider(
token_url="https://your-idp.com/oauth/token",
client_id="your_idp_client_id",
client_secret="your_idp_client_secret",
audience="https://your-api-audience.com", # optional, depends on your IDP
resource="my-resource", # any additional custom fields are passed in the token request body
)
Pass the provider to any component that accepts idp_auth_provider:
permissions_provider = PlainIDPermissionsProvider(
base_url="https://platform-product.us1.plainid.io",
client_id="your_client_id",
idp_auth_provider=idp_provider,
)
When idp_auth_provider is set and no auth_token is provided per request, the provider automatically fetches a token from the IDP and uses it for authentication.
The provider's token belongs to your application (the agent): it comes from a client-credentials flow and names no user. The SDK uses it only to authenticate the request and never sends it as the user's identity. The identity still comes from the RequestContext: an entity_id, or a user token in auth_token. To make PlainID see the agent as an identity too, see Passing the agent's own token as an identity under Multiple Identities.
| Parameter | Type | Required | Description |
|---|---|---|---|
token_url |
str |
Yes | The IDP's token endpoint URL |
client_id |
str |
Yes | OAuth2 client ID for the IDP |
client_secret |
str |
Yes | OAuth2 client secret for the IDP |
grant_type |
str |
No | OAuth2 grant type (default "client_credentials") |
audience |
str |
No | Audience parameter included in the token request |
**kwargs |
No | Additional fields to include in every token request body |
Timeouts
Every class that makes network calls takes an optional timeout in seconds. The defaults keep the behavior of earlier versions. A timeout must be a positive, finite number; any other value, None included, raises ValueError. LLMCategoryClassifierProvider also accepts an httpx.Timeout, as LiteLLM does.
| Class | Parameter | Default |
|---|---|---|
PlainIDPermissionsProvider, FilterProvider and its subclasses |
timeout |
5 |
PlainIDAuthClient, PlainIDSQLAuthorizerClient |
timeout |
5 |
IdpAuthProvider |
timeout |
5 |
PlainIDContentControlsClient |
timeout |
30 |
LLMCategoryClassifierProvider |
timeout |
600, the LiteLLM completion default |
PresidioAnonymizer with enable_ahds=True |
ahds_timeout |
300, the Azure SDK default, for both connect and read |
A timeout raises the class's exception, and the categorizer, anonymizer or authorizer then denies.
Identity Context
PlainID supports two identity resolution modes:
- Explicit identity — via
entity_id,entity_type_id, and optionallyadditional_identitiesin the request body. - Header-based identity — via the
headersfield, which forwards the headers directly to the PlainID API where they are matched against configured values to resolve the relevant entities. In this mode,entity_id,entity_type_id, andadditional_identitiesare not required.
request_context = RequestContext(
auth_token="your_jwt_token",
headers={
"x-custom-header": "value_to_match",
"x-another-header": "value_to_match",
},
)
Request ID
Set request_id to correlate the SDK's calls to the Content Controls Service with your own request, for example with the X-Request-ID your agent received. It must be 1 to 128 visible ASCII characters, without spaces, because it is sent as a header and written to logs. For another value, the service call carries a generated id instead, and the SDK logs a warning:
request_context = RequestContext(entity_id="alice", entity_type_id="User", request_id=incoming_request_id)
Categorizer and ContentControlsAnonymizer send it as the X-Request-ID of their service calls, so the service logs carry your id. Without it, each call gets a new UUID. The id comes from the request context passed to the call, not from the one given at construction. It is not an identity attribute and is not sent to the PlainID authorization service.
Multiple Identities
PlainID supports sending multiple identities in a single request. Each identity is evaluated independently, and the final decision is based on the combined evaluation (logical AND).
Note: The PlainID runtime currently supports a maximum of 3 identities of 3 different types per request.
How the identities are passed depends on how the scope resolves identity.
Explicit identities (scope with identity "Sent in Request"): the user goes in entity_id / entity_type_id and the others in additional_identities.
from core_plainid.models.context.request_context import AdditionalIdentity, RequestContext
request_context = RequestContext(
entity_id="alice",
entity_type_id="User",
additional_identities=[
AdditionalIdentity(entity_id="billing-agent", entity_type_id="Agents"),
],
)
entity_type_id is the Identity Template ID shown in the identity workspace's settings in PlainID, which can differ from the workspace's display name (for example EntraAgents for a workspace named "Entra Agents"). With a wrong value PlainID answers <value> is not a valid identity type.
Identities from headers (scope with identity matchers): each identity template in PlainID reads its own place in the request headers, so each identity must arrive in the header its template reads. The user's token goes in auth_token (sent as Authorization); anything else goes in headers under the name the other template is configured for.
Passing the agent's own token as an identity
An agent that runs with its own credentials usually has a token of its own, for example the one an IdpAuthProvider fetches. The SDK does not add that token to the identities by itself. To have PlainID evaluate the agent together with the user, put the agent's token into the request context yourself:
from core_plainid.models.context.request_context import RequestContext
from core_plainid.utils.idp_auth_provider import IdpAuthProvider
agent_idp = IdpAuthProvider(
token_url="https://your-idp.com/oauth/token",
client_id="your_agent_client_id",
client_secret="your_agent_client_secret",
audience="https://your-api-audience.com",
)
def build_request_context(user_token: str) -> RequestContext:
return RequestContext(
auth_token=user_token, # the user
headers={"x-agent-authorization": f"Bearer {agent_idp.get_token()}"}, # the agent
)
In PlainID, the agent's identity template must read that same header, both in its matcher and in the mapper that takes the agent's id, for example $.request.headers.x-agent-authorization.JWT.azp. The header name is yours to choose; it only has to be the one the template reads. A template that reads Authorization, as the user's template usually does, cannot be used for a second token.
For an agent that acts without a user, pass only the agent's token, in the header its template reads, and no auth_token:
request_context = RequestContext(
headers={"x-agent-authorization": f"Bearer {agent_idp.get_token()}"},
)
PlainID then resolves the agent as the only identity, and the agent needs policies of its own.
Notes:
- Build the request context for every request.
get_token()returns a cached token and refreshes it when it expires, but aRequestContextholds the text of the token: one that is created once and reused will carry an expired token. - Use
await agent_idp.aget_token()in async code.
Permissions Provider
The PlainIDPermissionsProvider connects to PlainID and retrieves the permissions assigned to a given identity. It is used internally by the anonymizer and categorizer, but can also be used directly to retrieve categories, entities, and tools permissions.
The provider supports multiple identities through the additional_identities field in RequestContext. This is designed for agentic scenarios where a primary identity (e.g. a User) and an additional agentic identity (e.g. an AI Agent) are both required when resolving permissions.
from core_plainid.utils.plainid_permissions_provider import PlainIDPermissionsProvider
from core_plainid.models.context.request_context import AdditionalIdentity, RequestContext
permissions_provider = PlainIDPermissionsProvider(
base_url="https://platform-product.us1.plainid.io",
client_id="your_client_id",
client_secret="your_client_secret",
)
request_context = RequestContext(
entity_id="your_entity_id",
entity_type_id="your_entity_type",
additional_identities=[
AdditionalIdentity(
entity_id="your_additional_entity_id",
entity_type_id="your_additional_entity_type",
),
],
)
permissions = await permissions_provider.aget_permissions(request_context)
print(permissions.categories) # allowed category names
print(permissions.entities) # anonymization entity actions
print(permissions.tools) # allowed tool names
You can also provide request_context at construction time to eagerly load permissions once and reuse them across multiple calls without passing the context each time:
permissions_provider = PlainIDPermissionsProvider(
base_url="https://platform-product.us1.plainid.io",
client_id="your_client_id",
client_secret="your_client_secret",
request_context=RequestContext(
entity_id="your_entity_id",
entity_type_id="your_entity_type",
),
)
permissions = permissions_provider.get_permissions()
Category Filtering
The Categorizer classifies user messages into categories and verifies that the classified categories are allowed by PlainID policies. If the message's categories are not permitted, a PlainIDCategorizerException is raised. Multiple identities are supported through RequestContext.
PlainID Setup
To use category filtering, configure a ruleset in PlainID using the Prompt_Control template and set up the available categories as assets (e.g. contract, HR, finance):
# METADATA
# custom:
# plainid:
# kind: Ruleset
# name: All
ruleset(asset, identity, requestParams, action) if {
asset.template == "Prompt_Control"
}
Usage
from core_plainid.categorization.categorizer import Categorizer
from core_plainid.utils.plainid_permissions_provider import PlainIDPermissionsProvider
from core_plainid.models.context.request_context import RequestContext
permissions_provider = PlainIDPermissionsProvider(
base_url="https://platform-product.us1.plainid.io",
client_id="your_client_id",
client_secret="your_client_secret",
)
categorizer = Categorizer(
classifier_provider=classifier, # see Category Classifiers below
permissions_provider=permissions_provider,
all_categories=["contract", "HR", "finance"],
)
request_context = RequestContext(
entity_id="your_entity_id",
entity_type_id="your_entity_type",
)
result = await categorizer.acategorize(
"I'd like to know the weather forecast for today",
request_context=request_context,
)
The all_categories parameter specifies the full list of possible categories for classification. The categorizer classifies the user message using the provided classifier, then verifies the result against the categories allowed by PlainID. If the classified categories are not a subset of the allowed categories, a PlainIDCategorizerException is raised.
The LLM and zero-shot classifiers classify against all_categories, so they require a non-empty list. With an empty list, creating the categorizer raises PlainIDCategorizerException. A custom provider that classifies against the list can override validate_categories, which the categorizer calls once when it is created. ContentControlsCategoryClassifierProvider does not use the list.
Conversation input
A follow-up such as "and for next year?" has no category of its own. Call categorize_conversation (or acategorize_conversation) with the conversation, as a sequence of ConversationMessage in chronological order. The categorizer returns that sequence unchanged when the categories are permitted:
from core_plainid import ConversationMessage
conversation = [
ConversationMessage(role="user", content="How many PTO days do I have left?"),
ConversationMessage(role="assistant", content="You have 12 days left."),
ConversationMessage(role="user", content="And for next year?"),
]
await categorizer.acategorize_conversation(conversation, request_context=request_context)
Roles are user, assistant and system. Tool results are not accepted: they can carry instructions injected through retrieved content and must not steer an authorization decision. The conversation must contain at least one user message.
The framework adapters call categorize for a message string and categorize_conversation for messages. A custom subclass of BaseCategorizer must implement categorize and acategorize. It inherits conversation methods that categorize the last user message alone; override them to use the history. A subclass of Categorizer that overrides categorize must also override categorize_conversation if the change applies to conversations too.
Which messages the classifier sees depends on the provider. ContentControlsCategoryClassifierProvider sends the whole conversation to the service, within the service's input limits (see Input limits below). LLMCategoryClassifierProvider, ZeroShotCategoryClassifierProvider and any custom provider classify the last user message, exactly as they do for a single message; a custom provider can override classify_conversation and aclassify_conversation to use the history. Every classify method also receives the caller's request_id, which a provider that calls a service can send on.
Category Classifiers
Three built-in classifiers are available: two run in your process, and one calls the PlainID AI Content Controls Service.
LLMCategoryClassifierProvider
Requires:
pip install core-plainid[categorization-llm]
Uses an LLM to classify user messages. Model calls are powered by LiteLLM, which supports 100+ LLM providers (OpenAI, Anthropic, Azure, Bedrock, Ollama, etc.) through a unified interface.
Set the appropriate environment variables for your chosen provider:
# OpenAI
export OPENAI_API_KEY="your_openai_api_key"
# Anthropic
export ANTHROPIC_API_KEY="your_anthropic_api_key"
# Azure OpenAI
export AZURE_API_KEY="your_azure_api_key"
export AZURE_API_BASE="https://your-resource.openai.azure.com"
export AZURE_API_VERSION="2024-02-01"
For the full list of supported providers and their environment variables, see the LiteLLM Providers documentation.
from core_plainid.categorization.llm_category_classifier_provider import LLMCategoryClassifierProvider
llm_classifier = LLMCategoryClassifierProvider(model="openai/gpt-4o")
The model parameter follows LiteLLM's provider/model naming convention (e.g. openai/gpt-4o, anthropic/claude-sonnet-4-20250514, ollama/llama3).
Use with caution — classification quality depends on the LLM you choose. Some base models may return poor or incorrect results, so prefer larger models (OpenAI, Anthropic, etc.) or models trained for classification tasks.
ZeroShotCategoryClassifierProvider
Requires:
pip install core-plainid[categorization-zeroshot]
Uses a Hugging Face zero-shot classification model. The model is downloaded automatically on first use.
from core_plainid.categorization.zeroshot_category_classifier_provider import ZeroShotCategoryClassifierProvider
zeroshot_classifier = ZeroShotCategoryClassifierProvider(
model_name="facebook/bart-large-mnli",
threshold=0.5,
)
The threshold parameter (default 0.5) controls the minimum confidence score for a category to be included. Use this classifier if you want better classification results without relying on an external LLM API, but note it requires disk space for the downloaded model.
ContentControlsCategoryClassifierProvider
Requires: the base install only, and a reachable PlainID AI Content Controls Service.
Sends the user message to the PlainID AI Content Controls Service, which classifies it against the category catalog of a PlainID asset type. The service loads that catalog from the PlainID Platform and classifies against the category descriptions, so you do not pass all_categories. Nothing heavy runs in your agent process.
from core_plainid.categorization.categorizer import Categorizer
from core_plainid.categorization.content_controls_category_classifier_provider import (
ContentControlsCategoryClassifierProvider,
)
from core_plainid.clients.plainid_content_controls_client import PlainIDContentControlsClient
content_controls = PlainIDContentControlsClient(base_url="http://content-controls:8080")
permissions_provider = PlainIDPermissionsProvider(
base_url="https://platform-product.us1.plainid.io",
client_id="your_client_id",
client_secret="your_client_secret",
plainid_categories_resource_type="Prompt_Control",
)
categorizer = Categorizer(
classifier_provider=ContentControlsCategoryClassifierProvider(
client=content_controls,
permissions_provider=permissions_provider,
),
permissions_provider=permissions_provider,
)
result = await categorizer.acategorize("How many PTO days do I have left?", request_context=request_context)
- The provider returns category ids. An id is the asset path, which is what PlainID grants, so the permission check matches it directly. Display names are never compared.
- The service classifies against the catalog of the permissions provider's
plainid_categories_resource_type. Pass the same permissions provider to the classifier provider and to the categorizer, so that the classified categories and the PlainID grants describe the same asset type. classifier="llm"orclassifier="zeroshot"selects the classifier on the service. It must be enabled on the deployment. Omit it to use the deployment default.- Every failure raises
PlainIDCategorizerException. Itsoriginal_exceptionis aPlainIDContentControlsClientExceptionwith the service'serror_codeandretryablewhen the service returned an error.
Input limits
The service classifies a limited amount of input. The SDK sends the conversation as it receives it and does not shorten it, so keep the input within the limits of your deployment. The service defaults are:
| Input | Default limit | Service setting |
|---|---|---|
| Single message | 32,000 characters | classification.input.max_prompt_chars |
| Conversation, messages | 20 messages, system messages included | classification.conversation.max_messages |
| Conversation, size | 8,000 tokens. The service counts one token for every four characters of message content, so about 32,000 characters | classification.conversation.max_tokens |
When the input is over a limit, the service by default classifies only part of it (classification.input.on_exceed: truncate):
- It drops the oldest messages of a conversation first, and system messages last.
- A last user message that is alone over the size limit is dropped completely.
- A single message keeps only its last 32,000 characters.
The response does not say which part was dropped, so the provider raises PlainIDCategorizerException when the service reports that it dropped anything, or does not report whether it did. The categorizer then denies. With on_exceed: reject, the service returns an error instead, and the categorizer also denies.
To stay within the limits:
- Send the recent part of a long conversation, and always include the last user message.
- The LangChain, LangGraph and Microsoft Agent Framework integrations classify the agent's message history without tool messages. A session whose history is over the limits is denied until the history is shorter.
- Ask the operator of the service for the limits when they differ from the defaults.
PlainIDContentControlsClient
The client used by both Content Controls integrations.
| Parameter | Default | Description |
|---|---|---|
base_url |
— | Service base URL |
timeout |
30.0 |
Request timeout in seconds. Classification calls an LLM, so it is longer than the httpx default |
headers |
None |
Extra headers on every request, for example a credential for an authenticating proxy in front of the service |
The service has no caller authentication of its own. Deploy it where only your agents can reach it, or put an authenticating proxy in front of it and pass the proxy's credential in headers.
Every request carries an X-Request-ID header: the request_id argument of the method, or a new UUID4. Categorizer and ContentControlsAnonymizer pass RequestContext.request_id (see Request ID). The id is part of every error message, so a failure in your agent logs can be found in the service logs.
Create the client once and reuse it, as the other PlainID clients: it keeps its connections open for the life of the process. Custom headers may not set Content-Type or X-Request-ID; the client removes them, in any letter case, and sets its own.
Anonymization
Requires:
pip install core-plainid[anonymization]
The PresidioAnonymizer detects and anonymizes PII (Personally Identifiable Information) in text using Microsoft Presidio. It supports two actions: MASK (replaces PII with ***) and ENCRYPT (encrypts the detected PII using a provided key). Multiple identities are supported through RequestContext.
The list of supported PII entities is based on Presidio's supported entities.
PlainID Setup
To use anonymization, configure rulesets in PlainID using the Output_Control template. Each entity type you want to detect needs its own ruleset:
# METADATA
# custom:
# plainid:
# kind: Ruleset
# name: PERSON
ruleset(asset, identity, requestParams, action) if {
asset.template == "Output_Control"
asset["path"] == "PERSON"
action.id in ["MASK"]
}
Custom Regex Entities
You can define custom entities using regex patterns. Configure them in PlainID with a REGEX path prefix and a regexValue attribute containing the pattern:
# METADATA
# custom:
# plainid:
# kind: Ruleset
# name: REGEX_EMAIL
ruleset(asset, identity, requestParams, action) if {
asset.template == "Output_Control"
asset["path"] == "REGEX_EMAIL"
asset["regexValue"] == "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}"
action.id in ["MASK"]
}
Azure Health De-identification (AHDS) Entities
For medical/health data, you can enable Azure Health Data Services de-identification to detect health-specific PHI entities (e.g. DOCTOR, PATIENT, AGE). Configure them in PlainID the same way:
# METADATA
# custom:
# plainid:
# kind: Ruleset
# name: DOCTOR
ruleset(asset, identity, requestParams, action) if {
asset.template == "Output_Control"
asset["path"] == "DOCTOR"
action.id in ["MASK"]
}
Usage
from core_plainid.anonymization.presidio_anonymizer import PresidioAnonymizer
from core_plainid.utils.plainid_permissions_provider import PlainIDPermissionsProvider
from core_plainid.models.context.request_context import RequestContext
permissions_provider = PlainIDPermissionsProvider(
base_url="https://platform-product.us1.plainid.io",
client_id="your_client_id",
client_secret="your_client_secret",
)
anonymizer = PresidioAnonymizer(
permissions_provider=permissions_provider,
encrypt_key="your_16_char_key!",
)
request_context = RequestContext(
entity_id="your_entity_id",
entity_type_id="your_entity_type",
)
result = await anonymizer.aanonymize(
"John Smith lives in New York",
request_context=request_context,
)
print(result) # "*** lives in ***"
The encrypt_key parameter is optional and only required if you use the ENCRYPT action. The key is used for AES encryption and must be 128, 192, or 256 bits long (16, 24, or 32 characters).
Enabling Azure Health De-identification (AHDS)
Requires:
pip install core-plainid[anonymization-ahds]
To detect health-specific PHI entities, enable AHDS by passing enable_ahds=True and setting the following environment variables:
export AHDS_ENDPOINT="https://your-deid-service.api.deid.azure.com"
export AZURE_TENANT_ID="your_azure_tenant_id"
export AZURE_CLIENT_ID="your_azure_client_id"
export AZURE_CLIENT_SECRET="your_azure_client_secret"
anonymizer = PresidioAnonymizer(
permissions_provider=permissions_provider,
encrypt_key="your_16_char_key!",
enable_ahds=True,
)
Using the Content Controls Service
ContentControlsAnonymizer reads the same Output_Control grants as PresidioAnonymizer and asks the PlainID AI Content Controls Service to apply them. Presidio and its language model run in the service, not in your agent.
from core_plainid.anonymization.content_controls_anonymizer import ContentControlsAnonymizer
from core_plainid.clients.plainid_content_controls_client import PlainIDContentControlsClient
anonymizer = ContentControlsAnonymizer(
permissions_provider=permissions_provider,
client=PlainIDContentControlsClient(base_url="http://content-controls:8080"),
)
result = await anonymizer.aanonymize("John Smith lives in New York", request_context=request_context)
print(result) # "*** lives in New York"
MASK, ENCRYPT and custom REGEX entities work as described above. regex_score (default 1.0) sets the confidence the service gives a REGEX match; keep it at 1.0 unless you know the service's detection threshold, because a match scored below it is silently not masked. When no entity is granted MASK or ENCRYPT, the text is returned unchanged and the service is not called. Differences from PresidioAnonymizer:
PresidioAnonymizer |
ContentControlsAnonymizer |
|
|---|---|---|
| Encryption key | encrypt_key constructor argument |
configured on the service; no SDK argument |
| ENCRYPT granted, no key configured | falls back to *** |
the service refuses the request and PlainIDAnonymizerException is raised |
| AHDS health entities | enable_ahds=True |
enabled on the service deployment (its AHDS profile); no SDK parameter |
Tools Authorization
Tool authorization lets PlainID policies decide which tools an AI agent may see and call for the current user. A tool is an asset in PlainID whose path is the tool's name; it can be a tool of an MCP (Model Context Protocol) server or any other tool of the agent. There are two parts:
- Listing:
PlainIDPermissionsProviderreturns the tools the user is entitled to, so the agent can hide the others from the model. - Authorizing a call:
PlainIDToolAuthorizerasks PlainID before each tool call. This is the enforcement; hiding a tool does not stop a call to it.
The langchain-plainid, langgraph-plainid and maf-plainid packages wrap both parts for their frameworks. Multiple identities are supported through RequestContext.
PlainID Setup
Configure a ruleset in PlainID using the MCP-TOOL template and set up the available tools as assets (e.g. search_tool, run_query, email_sender). The asset path must equal the tool's name exactly, including case:
# METADATA
# custom:
# plainid:
# kind: Ruleset
# name: All
ruleset(asset, identity, requestParams, action) if {
asset.template == "MCP-TOOL"
}
If your tool assets use another template, pass its name as plainid_tools_resource_type to PlainIDPermissionsProvider and as tools_resource_type to PlainIDToolAuthorizer. The two must be equal.
Listing the allowed tools
from core_plainid.utils.plainid_permissions_provider import PlainIDPermissionsProvider
from core_plainid.models.context.request_context import RequestContext
permissions_provider = PlainIDPermissionsProvider(
base_url="https://platform-product.us1.plainid.io",
client_id="your_client_id",
client_secret="your_client_secret",
)
request_context = RequestContext(
entity_id="your_entity_id",
entity_type_id="your_entity_type",
)
permissions = await permissions_provider.aget_permissions(request_context)
allowed_tools = permissions.tools # e.g. ["search_tool", "run_query"]
If PlainID cannot be reached, PlainIDPermissionsException is raised; the agent is never given an empty list because of an outage.
Authorizing a tool call
from core_plainid import (
PlainIDDecisionClient,
PlainIDSQLAuthorizerClient,
PlainIDToolAuthorizer,
RequestContext,
)
decision_client = PlainIDDecisionClient(
base_url="https://platform-product.us1.plainid.io",
client_id="your_client_id",
client_secret="your_client_secret",
)
tool_authorizer = PlainIDToolAuthorizer(
decision_client=decision_client,
permissions_provider=permissions_provider, # optional, needed only for listing
sql_authorizer_client=PlainIDSQLAuthorizerClient( # optional, see "SQL obligation"
base_url="https://your-sql-authorizer.example.com",
client_id="your_client_id",
client_secret="your_client_secret",
),
)
request_context = RequestContext(entity_id="your_entity_id", entity_type_id="your_entity_type")
decision = await tool_authorizer.aauthorize_call(
"run_query",
{"sql": "SELECT id, name FROM employees", "limit": 50},
request_context,
)
if decision.allowed:
result = await run_query(**decision.arguments) # use the returned arguments
else:
result = decision.denied_message # "Access Denied"
Always run the tool with decision.arguments: when the policy carries a SQL obligation they hold the rewritten query. authorize_call is the synchronous version.
For each call the SDK sends one request to POST {base_url}/runtime/5.0/decisions/permit-deny: the tool name as the path, the tool's arguments as the body, and the tool as an asset of the tools resource type. Additional meta.runtimeFineTune keys can be passed with runtime_fine_tune={...}.
PlainIDToolAuthorizer argument |
Description |
|---|---|
decision_client |
PlainIDDecisionClient for the permit-deny API |
permissions_provider |
PlainIDPermissionsProvider; needed only for allowed_tool_names |
sql_authorizer_client |
PlainIDSQLAuthorizerClient; needed only when policies grant a SQL obligation |
sql_authorizer_options |
SQLAuthorizerOptions sent with every SQL Authorizer request |
tools_resource_type |
Resource type of the tool assets. Default MCP-TOOL |
runtime_fine_tune |
Extra meta.runtimeFineTune keys for the decision request |
denied_message |
Text returned to the model for a refused call. Default Access Denied |
tool_name_resolver |
Function that maps the framework's tool name to the asset path, for example to strip a prefix |
Outcomes
A call ends in one of three ways. In the last two the tool must not run.
| Outcome | When | What you get |
|---|---|---|
| Allowed | The policy permits the call | decision.allowed is True; decision.arguments holds the arguments to run with |
| Refused | The policy does not permit the call; the policy grants an obligation the SDK does not support, or obligations on two arguments; the argument named by a SQL obligation is missing, not text or empty; the SQL Authorizer could not fully apply the policy to the query | decision.allowed is False; return decision.denied_message to the model as the tool's error, so that the agent can go on |
| Failed | PlainID or the SQL Authorizer cannot be reached or answers an error; the answer cannot be read; a SQL obligation applies and no SQL Authorizer is configured, or the user cannot be identified for it | An exception: PlainIDDecisionClientException, PlainIDSQLAuthorizerClientException or PlainIDToolAuthorizationException |
The reason of a refusal is written to the log and is not part of the message for the model. A failure is never reported as a refusal: an outage raises, so that it cannot be mistaken for a policy decision.
SQL obligation
A policy can allow a tool on the condition that a SQL argument is filtered first. Grant the action FILTER:SQL:<argument> on the tool asset, where <argument> is the name of the tool argument that holds the query (for example FILTER:SQL:sql), in the same policy as the tool rule. When the decision carries this action, the SDK sends the query to the SQL Authorizer (POST /resql), and the tool runs with the returned query in that argument; the other arguments are not changed.
- Pass a
PlainIDSQLAuthorizerClientto the authorizer. Without one, an obligated call fails withPlainIDToolAuthorizationException. Deployments whose policies grant no such action need no SQL Authorizer. SQLAuthorizerOptions(flags, runtime fine-tune and the other request fields, see SQL Database Authorizer) configure the request.- The SQL Authorizer must be a version that returns
coveragein its answer. The tool runs only when coverage isCOMPLETEorNOT_APPLICABLE;PARTIALorNONEis a refusal. - The original query never runs once an obligation applies.
Identity
The identity in RequestContext is passed to PlainID in every form it is given:
auth_tokenandheadersare sent as request headers for PlainID to match, for a scope whose identity is resolved from the token or headers.entity_idandentity_type_id(the Identity Template ID), andadditional_identities, are sent inmeta.runtimeFineTune, for a scope whose identity is taken from the request.
A user and an agent can be authorized together; see Multiple Identities for both ways of passing them, including the agent's own token.
Authentication method
How the SDK authenticates must match the Scope Auth Method of your PlainID scope. Set it with auth_method on PlainIDDecisionClient, PlainIDPermissionsProvider (or PlainIDAuthClient) and PlainIDSQLAuthorizerClient:
auth_method |
What is sent |
|---|---|
"secret-body" |
The client secret in the request body. A user token of the request context is sent as the user's identity |
"secret-header" |
The client secret in the x-client-secret header. A user token of the request context is sent as the user's identity |
"token" |
A JWT (the request context's auth_token, or one from an IdpAuthProvider) authenticates the request; no client secret is sent |
| not set | Automatic: a token when one is available, otherwise the client secret in the request body. This is the behaviour of earlier versions |
credentials = {
"client_id": "your_client_id",
"client_secret": "your_client_secret",
"auth_method": "secret-header",
}
decision_client = PlainIDDecisionClient(base_url="https://platform-product.us1.plainid.io", **credentials)
permissions_provider = PlainIDPermissionsProvider(base_url="https://platform-product.us1.plainid.io", **credentials)
sql_authorizer_client = PlainIDSQLAuthorizerClient(base_url="https://your-sql-authorizer.example.com", **credentials)
Set the method explicitly when the scope takes a client secret and you also pass a user token: with the automatic behaviour the token would be used instead of the secret, and the scope would reject the request. The client id is always sent, in the x-client-id header or in the request body.
With "secret-header" the SQL Authorizer receives the client id and secret as the x-client-id and x-client-secret headers and must be configured to pass them on to PlainID (ALLOWED_FOR_PASS_THROUGH_HEADERS: X-Client-Id,X-Client-Secret).
Limiting enforcement to some tools
PlainIDToolAuthorizer decides every call it is asked about. The framework packages accept an applies_to selection (tool names, or a function of the tool) to authorize only some of the agent's tools, for example only the tools of an MCP server; see their READMEs. A tool outside the selection runs with no PlainID check.
SQL Database Authorizer
The PlainIDSQLAuthorizerClient dynamically modifies SQL queries based on PlainID authorization policies, enforcing Row-Level Security (RLS) and Column-Level Security (CLS) at query time.
Note: The SQL Authorizer does not currently support multiple identities. Only a single identity context (
entity_id/entity_type_id) can be provided per request.
Usage
from core_plainid.clients.plainid_sql_authorizer_client import PlainIDSQLAuthorizerClient
from core_plainid.models.request.sql_authorizer_request import (
SQLAuthorizerRequest,
SQLAuthorizerFlags,
PoliciesJoinOperation,
)
sql_authorizer = PlainIDSQLAuthorizerClient(
base_url="https://your-sql-authz.plainid.cloud",
client_id="your_client_id",
client_secret="your_client_secret",
)
request = SQLAuthorizerRequest(
sql="SELECT * FROM accounts WHERE country = 'US'",
entity_id="your_entity_id",
entity_type_id="your_entity_type",
flags=SQLAuthorizerFlags(
empty_rls_treat_as_denied=True,
empty_cls_treat_as_permitted=True,
expand_star_column=True,
policies_join_operation=PoliciesJoinOperation.OR,
),
)
response = sql_authorizer.authorize_sql(request)
print(response.sql) # the modified SQL query
print(response.was_modified) # True if policies were applied
Using a JWT token instead of client secret:
sql_authorizer = PlainIDSQLAuthorizerClient(
base_url="https://your-sql-authz.plainid.cloud",
client_id="your_client_id",
)
response = sql_authorizer.authorize_sql(request, auth_token="your_jwt_token")
Using an IDP provider:
sql_authorizer = PlainIDSQLAuthorizerClient(
base_url="https://your-sql-authz.plainid.cloud",
client_id="your_client_id",
idp_auth_provider=idp_provider,
)
response = sql_authorizer.authorize_sql(request)
PlainID Auth Client
The PlainIDAuthClient is the low-level client used internally by PlainIDPermissionsProvider to communicate with the PlainID API. It provides get_token / aget_token for retrieving user access tokens and get_resolution / aget_resolution for fetching resolution data. In most cases you should use PlainIDPermissionsProvider instead of interacting with this client directly.
All three authentication modes (client credentials, JWT token, IDP provider) and both identity approaches (explicit entity ID or HTTP headers matching) are supported — see the Authentication and Identity Context sections above.
from core_plainid.clients.plainid_auth_client import PlainIDAuthClient
client = PlainIDAuthClient(
base_url="https://platform-product.us1.plainid.io",
client_id="your_client_id",
client_secret="your_client_secret",
)
token_response = await client.aget_token(
entity_id="your_entity_id",
entity_type_id="your_entity_type",
)
Exceptions
The library provides specific exceptions to help identify which component caused an error. All exceptions inherit from PlainIDException and include the error message and the original_exception (if applicable).
| Exception | Description |
|---|---|
PlainIDException |
Base exception for all PlainID errors |
PlainIDAuthClientException |
Errors in the PlainID Auth client |
PlainIDPermissionsException |
Errors in permissions processing |
PlainIDCategorizerException |
Errors in the categorizer component |
PlainIDAnonymizerException |
Errors in the anonymizer component |
PlainIDSQLAuthorizerClientException |
Errors in the SQL Authorizer client |
PlainIDDecisionClientException |
Errors in the decision (permit-deny) client |
PlainIDToolAuthorizationException |
A tool call could not be decided: an unreadable answer, a failed SQL obligation or a missing configuration. Never raised for a policy refusal |
PlainIDContentControlsClientException |
Errors in the Content Controls client; carries status_code, error_code and retryable when the service returned an error |
PlainIDFilterException |
Errors in filter processing |
PlainIDRetrieverException |
Errors in the retriever components |
LlmResponseException |
Malformed or unexpected LLM responses |
from core_plainid.exceptions.plainid_exceptions import PlainIDAnonymizerException
try:
result = await anonymizer.aanonymize(query, request_context=request_context)
except PlainIDAnonymizerException as e:
print(f"Anonymization error: {e.message}")
Metadata
Release files for core-plainid 4.0.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| core_plainid-4.0.0-py3-none-any.whl | Python 3 | none | any | Details for core_plainid-4.0.0-py3-none-any.whl |
Release files / core_plainid-4.0.0-py3-none-any.whl
| Download URL | core_plainid-4.0.0-py3-none-any.whl |
|---|---|
| Size | 81.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
89dbc26ccb0497b3bf122dae8fa063ee9ebdb7d9152130c11df33bd821819e22
|
|
BLAKE2b-256 checksum How to use checksums |
d93a96a8dc073a1d3b8c46cf9d8638f0fe80ff5287c1de2d71deaa2db3098c8e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.9.30 {"installer":{"name":"uv","version":"0.9.30","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"12","id":"bookworm","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for core-plainid 4.0.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.