Connect UniFi On Prem to AI Agents: Orchestrate Identity and Access
Learn how to connect UniFi On Prem to AI agents for automated physical security, NFC provisioning, and door access management using Truto's unified tools.
You want to connect UniFi On Prem to an AI agent so your IT systems can independently provision NFC cards, manage visitor access policies, remotely unlock doors, and audit physical security logs based on natural language requests or automated triggers. Here is exactly how to do it using Truto's /tools endpoint and SDK, bypassing the need to manually build and maintain complex integrations bridging software with physical hardware.
Giving a Large Language Model (LLM) read and write access to your on-premise UniFi Access instance is an engineering headache. You either spend weeks building, tunneling, and maintaining a custom connector that understands the physical hardware polling requirements, or you use a managed infrastructure layer that handles the boilerplate for you. If your team uses ChatGPT, check out our guide on connecting UniFi On Prem to ChatGPT, or if you are building on Anthropic's models, read our guide on connecting UniFi On Prem to Claude. For developers building custom autonomous workflows, you need a programmatic way to fetch these tools and bind them to your agent framework.
This guide breaks down exactly how to fetch AI-ready tools for UniFi On Prem, bind them natively to an LLM using your framework of choice (LangChain, LangGraph, CrewAI, or Vercel AI SDK), and execute complex physical security operations. For a deeper look at the architecture behind this approach, refer to our research on architecting AI agents and the SaaS integration bottleneck.
The Engineering Reality of UniFi On Prem Integrations
Building AI agents is the easy part. Connecting them to external systems - especially systems that manage physical hardware like UniFi Access - is hard. Giving an LLM access to external APIs sounds simple in a prototype. You write a Node.js function that makes a fetch request and wrap it in an @tool decorator. In production, this approach collapses entirely, especially with an ecosystem as complex as UniFi On Prem.
If you decide to build this integration yourself, you own the entire API lifecycle. UniFi's architecture introduces several highly specific integration challenges that break standard LLM assumptions.
The Hardware State Polling Trap
Most SaaS APIs operate on synchronous REST paradigms. You send a POST request to create a user, and the API returns the user object. Physical access control systems do not work this way. When an agent needs to assign a new NFC card to an employee, it cannot just create a database record. It must wake up a physical UA reader hardware device, wait for a human to tap a card, and capture the token.
In the UniFi On Prem API, this is a multi-step process. First, you hit the /api/v1/developer/credentials/nfc_cards/enroll endpoint to initiate a session on a specific device_id. This returns a session_id. The agent must then know how to enter a polling loop on the /api/v1/developer/credentials/nfc_cards/enroll/status endpoint. Until the physical card is tapped, the API returns a pending status string rather than a standard JSON object containing the card_id and token.
If you hand-code this integration, you have to write complex prompts to teach the LLM to handle asynchronous polling, manage timeouts, and parse non-standard status payloads. When the LLM hallucinates and assumes the first response contains the token, it will crash your workflow.
Segmented Identity and Access Policies
Identity in UniFi is heavily fragmented across multiple overlapping endpoints. A user is not simply a record with an "access level." A physical identity in UniFi is a composite of a User Record, inherited User Group Access Policies, direct Access Policies, PIN codes, NFC cards, Touch Passes, and License Plates.
To onboard a new employee and grant them building access, an agent must orchestrate a sequence of calls:
- Create the user identity.
- Fetch the ID of the "Engineering" access policy.
- Assign the access policy to the user.
- Generate a secure PIN code.
- Assign the PIN code to the user.
Direct API tools push these quirks into the LLM's context. The model has to remember exactly which order to call these endpoints and which ID types (user IDs, policy IDs, hardware tokens) go where.
How Truto Normalizes the API Surface
Truto abstracts these complexities through its Proxy API architecture. Every integration on Truto is essentially a comprehensive JSON object that represents how an underlying product's API behaves. Integrations use the concept of Resources mapping to endpoints, enabling Truto to map any complex API into a predictable REST-based CRUD API.
The Methods on these Resources are what Truto provides as Proxy APIs, handling pagination, authentication, and query parameter processing automatically. For agentic workflows, Proxy APIs are ideal because they provide a clean, predictable schema for the LLM while allowing the agent to handle data reasoning using the raw, unopinionated data from the underlying product.
Fetching UniFi On Prem Tools for AI Agents
To bypass these integration headaches, Truto provides a /tools endpoint that dynamically generates standard JSON schemas for every method defined on the UniFi On Prem integration. You pass these schemas directly into your LLM framework.
First, you need an integrated account ID. Once a user has connected their UniFi instance to your application via the Truto interface, you can fetch the tool definitions.
// Fetch tools dynamically from Truto
const response = await fetch('https://api.truto.one/integrated-account/{account_id}/tools', {
headers: {
'Authorization': `Bearer ${process.env.TRUTO_API_KEY}`
}
});
const trutoTools = await response.json();
// trutoTools now contains an array of fully-formed tool schemas
// ready to be bound to your agent framework.When you pass these tools to an LLM, the model sees clean, descriptive functions like create_a_uni_fi_on_prem_visitor rather than raw endpoint paths.
Hero Tools for UniFi On Prem
While Truto exposes dozens of endpoints for the UniFi On Prem API, agentic workflows rely heavily on a few critical, high-leverage operations. These are the tools that handle the heaviest lifting in physical security automation.
1. create_a_uni_fi_on_prem_visitor
Visitor management is a prime candidate for AI automation. This tool registers a new visitor in UniFi Access, configuring their personal details, visit schedule, and the specific door access resources they are permitted to use.
Contextual Usage: Your agent should use this tool when parsing email requests for building access or integrating with a calendar system to automatically pre-register expected guests.
"I have a contractor named Jane Doe arriving tomorrow at 9 AM for maintenance. Register her as a visitor, grant her access to the Server Room group, and set her schedule to expire at 5 PM."
2. uni_fi_on_prem_users_assign_access_policy
Physical access control relies entirely on policies. This tool assigns or replaces the access policies for a specific user identity. It expects an array of access policy IDs.
Contextual Usage: If you pass an empty array, the tool removes all policies, making it highly effective for immediate offboarding or suspension workflows.
"Remove all physical access policies for John Smith immediately. Then verify his current status."
3. uni_fi_on_prem_credentials_enroll_nfc_card
This is the crucial bridge between software and hardware. Calling this tool wakes up a specific UA reader device and creates an NFC enrollment session.
Contextual Usage: Your agent must use this tool in conjunction with the polling tool (uni_fi_on_prem_credentials_get_nfc_enrollment_status). The agent will receive a session_id and must be instructed to monitor that session until the physical tap occurs.
"Initiate an NFC card enrollment session on the Front Desk Reader for the new engineering hire. Check the status every 10 seconds and let me know when the card is successfully tapped."
4. uni_fi_on_prem_doors_remote_unlock
Allows the agent to remotely trigger a door unlock command for a specified door_id.
Contextual Usage: Highly useful for IT helpdesks integrating with Slack or Teams, allowing an agent to verify a user's identity via chat and then trigger a remote unlock if they forgot their badge.
"Unlock the Main Entrance door for 10 seconds. Log the action under my actor name."
5. uni_fi_on_prem_doors_set_emergency_status
This tool modifies the emergency state of a door, allowing the agent to trigger lockdown or evacuation modes.
Contextual Usage: Should be heavily permission-gated within your agent framework. It is used for rapid response workflows triggered by external threat intelligence or security alerts.
"Trigger an emergency lockdown on all doors in the East Wing building group immediately."
6. uni_fi_on_prem_system_logs_list_resources
Retrieves the system logs associated with specific resources, door groups, and access policies.
Contextual Usage: Essential for automated security audits. Your agent can use this tool to compile a list of every time a specific high-security door was accessed outside of business hours.
"Pull the system logs for the Executive Suite door for the past 48 hours. Identify any access events that occurred between midnight and 6 AM."
To view the complete inventory of available operations and their exact schemas, visit the UniFi On Prem integration page.
Workflows in Action
Providing individual tools to an LLM is a start, but the real value is in autonomous multi-step orchestration. Here are two concrete examples of how an agent sequences these tools to solve complex IT and physical security problems.
Scenario 1: Automated Contractor Offboarding and Audit
When a contractor's engagement ends, their physical access must be revoked instantly, and security teams often require an audit of their final days on site.
"The contract for external vendor Alex Johnson has ended. Revoke all of his door access policies, unassign his PIN code, and generate an audit of which doors he accessed in the last 7 days."
- Search User: The agent calls
uni_fi_on_prem_users_searchpassing the query "Alex Johnson" to retrieve the internaluser_id. - Revoke Policies: The agent calls
uni_fi_on_prem_users_assign_access_policy, passing theuser_idand an empty array[]for the policy IDs, stripping all access. - Unassign PIN: The agent calls
uni_fi_on_prem_users_unassign_pin_codefor theuser_idto ensure fallback entry methods are disabled. - Audit Logs: The agent queries
list_all_uni_fi_on_prem_system_logs, filtering by the actor's ID and setting the time range to the past 7 days.
Result: The user is immediately locked out of all physical premises, and the agent returns a formatted summary of the contractor's last known physical locations based on badge taps.
Scenario 2: Just-In-Time Visitor Provisioning
A delivery driver arrives at a secure loading dock. An internal employee messages the IT support agent in Slack to grant temporary access.
"A delivery driver from FedEx is at the Loading Dock. Create a visitor pass for him for the next hour, assign a generated PIN code, and remote unlock the Loading Dock Bay 1 door now so he can pull in."
- Create Visitor: The agent calls
create_a_uni_fi_on_prem_visitorpassing "FedEx" as the name, setting the schedule to expire in one hour, and assigning the "Loading Dock" resource group. - Generate PIN: The agent calls
uni_fi_on_prem_credentials_generate_pin_codeto create a system-compliant PIN string. - Assign PIN: The agent calls
uni_fi_on_prem_visitors_assign_pin_codemapping the generated PIN to the new visitor ID. - Unlock Door: The agent calls
uni_fi_on_prem_doors_remote_unlockfor the specificdoor_idof Loading Dock Bay 1.
Result: The driver is granted immediate entry, receives a temporary PIN for the next hour to move freight, and the system auto-expires the access without human IT intervention.
Building Multi-Step Workflows
To build a resilient agent, you must understand how Truto handles the execution environment. Truto acts as the schema generator and the proxy transport layer, but Truto does not absorb your rate limits.
If your agent executes a loop that aggressively queries system logs, the upstream UniFi On Prem instance may reject the requests. When an upstream API returns an HTTP 429 Rate Limit error, Truto passes that exact error back to your caller. Truto normalizes the upstream rate limit data into standardized headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset) per the IETF specification.
Your agent execution loop is entirely responsible for detecting these 429 errors, parsing the ratelimit-reset header, and applying a backoff strategy before allowing the agent to retry the tool call.
Here is a conceptual architecture using LangGraph demonstrating how to bind Truto tools and manage execution:
flowchart TD
Start["User Request"] --> LLM["LLM Agent<br>(LangChain/LangGraph)"]
LLM -->|Decision| CallTool["Execute Tool Call<br>(e.g. create_visitor)"]
CallTool --> TrutoProxy["Truto Proxy API"]
TrutoProxy -->|HTTP Request| UniFi["UniFi On Prem API<br>(via local network)"]
UniFi -->|HTTP 429 Rate Limit| TrutoProxy
UniFi -->|HTTP 200 OK| TrutoProxy
TrutoProxy -->|Pass 429 + Headers| CheckStatus["Evaluate Response"]
TrutoProxy -->|Pass 200 JSON| ReturnData["Return Data to Context"]
CheckStatus -->|Is 429?| Backoff["Read ratelimit-reset<br>Sleep & Retry"]
Backoff --> CallTool
CheckStatus -->|Is Error?| ErrorHandle["Pass Error String<br>to LLM for correction"]
ErrorHandle --> LLM
ReturnData --> LLM
LLM -->|Final Answer| End["Return to User"]Here is how you initialize this in code using the Truto Langchain SDK. This setup fetches the tools, binds them to a model, and sets up the execution loop.
import { TrutoToolManager } from 'truto-langchainjs-toolset';
import { ChatOpenAI } from '@langchain/openai';
import { AgentExecutor, createToolCallingAgent } from 'langchain/agents';
import { ChatPromptTemplate } from '@langchain/core/prompts';
async function runUniFiAgent(prompt: string, integratedAccountId: string) {
// 1. Initialize the Truto Tool Manager for the UniFi account
const toolManager = new TrutoToolManager({
apiKey: process.env.TRUTO_API_KEY,
integratedAccountId: integratedAccountId
});
// 2. Fetch schemas for UniFi physical access methods
const tools = await toolManager.getTools({
methods: ['read', 'write', 'custom']
});
// 3. Bind tools to the LLM
const llm = new ChatOpenAI({
model: 'gpt-4o',
temperature: 0
});
const promptTemplate = ChatPromptTemplate.fromMessages([
['system', 'You are a physical security IT administrator. Use the provided tools to manage UniFi Access. If a tool fails due to a rate limit, the system will back off and retry. If a tool fails due to validation, adjust your input and try again.'],
['human', '{input}'],
['placeholder', '{agent_scratchpad}']
]);
const agent = createToolCallingAgent({
llm,
tools,
prompt: promptTemplate
});
// 4. Create the executor. In a production system, you would wrap this
// execution block in a custom loop that explicitly catches Truto's 429
// responses, reads the ratelimit-reset header, and pauses execution.
const executor = new AgentExecutor({
agent,
tools,
maxIterations: 10,
});
const result = await executor.invoke({
input: prompt
});
return result.output;
}When building these workflows, remember that physical security APIs lack the forgiveness of purely digital systems. A malformed request to a CRM just creates a bad record. A malformed request to a door controller might leave a building unlocked overnight. Relying on a unified tool layer that strictly enforces JSON schemas before the request ever reaches the local network is a critical safety measure.
Orchestrating the Physical Domain
Connecting AI agents to UniFi On Prem shifts your IT operations from reactive ticket processing to autonomous physical infrastructure management. By using Truto's /tools endpoint, you bypass the friction of managing polling loops, segmented identity models, and complex authentication flows. Your agents interact with stable, unified schemas, allowing your engineering team to focus on workflow logic rather than hardware API maintenance.
FAQ
- How do AI agents handle NFC enrollment in UniFi On Prem?
- Agents must sequence two tools: one to initiate the session on a physical reader (which returns a session ID), and a second tool called in a polling loop to check the status until the physical card is tapped and the token is captured.
- How do you handle UniFi On Prem API rate limits?
- Truto does not absorb, retry, or throttle rate limits. When the upstream UniFi API returns a 429 Rate Limit error, Truto passes it directly to the caller with standard IETF headers (ratelimit-reset). The agent framework is responsible for implementing the backoff strategy.
- Can an AI agent trigger an emergency lockdown via the API?
- Yes, by utilizing the `uni_fi_on_prem_doors_set_emergency_status` tool, an agent can set a door or group of doors into lockdown or evacuation mode based on external triggers or specific administrative prompts.
- Why use a unified tool layer instead of direct API calls for UniFi?
- Direct API calls require the LLM to understand complex, segmented identity models and hardware polling mechanisms. A unified tool layer provides strict JSON schemas and descriptive function names, drastically reducing the attack surface for AI hallucinations.