Real-World Examples
Complete, copy-paste examples for common AI agent authorization patterns. Each includes the full code and expected output.
1
E-Commerce Purchase Bot
An agent that processes purchases on behalf of users, with spending limits and vendor restrictions.
Code
import { PermitNetworks } from '@permitnetworks/sdk';
const permit = new PermitNetworks({ apiKey: process.env.PERMIT_API_KEY });
async function processPurchase(item: string, amount: number, vendor: string) {
// Authorize the purchase before executing
const decision = await permit.authorize({
agent: 'purchase-bot',
action: 'spend',
resource: 'company-funds',
context: {
amount,
currency: 'USD',
vendor,
item,
category: 'office-supplies'
}
});
if (!decision.allowed) {
console.log(`Purchase denied: ${decision.reason}`);
return { success: false, reason: decision.reason };
}
// Decision is allowed — proceed with purchase
const order = await executeOrder(item, amount, vendor);
return { success: true, orderId: order.id };
}Expected Output
// Allowed: $150 purchase from approved vendor
{ "allowed": true, "latency": "0.3ms", "policies": ["daily-spend-limit: PASS", "approved-vendors: PASS"] }
// Denied: $5,000 exceeds daily limit
{ "allowed": false, "reason": "daily spending limit exceeded ($5,000 > $2,000)", "latency": "0.4ms" }2
Customer Support Agent
A support agent that can only access data related to the current ticket, using scope locking.
Code
async function handleSupportTicket(ticketId: string, customerId: string) {
// Create a scoped session — agent can ONLY access this customer's data
const scope = await permit.createScope({
agent: 'support-agent',
task: 'handle-ticket',
context: { ticketId, customerId },
allowedActions: ['read:customer', 'read:orders', 'update:shipping'],
excludeActions: ['delete:*', 'read:payment-info', 'export:*'],
ttl: 600 // 10 minute limit
});
// All subsequent actions are checked against this scope
const customer = await permit.authorize({
agent: 'support-agent',
action: 'read:customer',
resource: `customer/${customerId}`,
scopeId: scope.id
});
// Attempting to read a DIFFERENT customer will be denied
const otherCustomer = await permit.authorize({
agent: 'support-agent',
action: 'read:customer',
resource: 'customer/other-id', // Not in scope!
scopeId: scope.id
});
// → DENIED: resource not within scope boundary
}Expected Output
// Reading scoped customer: ALLOWED
{ "allowed": true, "scope": "TKT-4892", "resource": "customer/cust_28a1f3" }
// Reading out-of-scope customer: DENIED
{ "allowed": false, "reason": "resource 'customer/other-id' outside scope boundary" }3
Multi-Agent Approval Chain
A workflow where high-value actions require approval from a supervisor agent before execution.
Code
async function requestHighValuePurchase(amount: number) {
// First, the purchasing agent requests authorization
const decision = await permit.authorize({
agent: 'purchase-bot',
action: 'spend',
resource: 'company-funds',
context: { amount, requiresApproval: amount > 5000 }
});
if (decision.status === 'pending_approval') {
// High-value: route to supervisor agent for approval
const approval = await permit.requestApproval({
originalRequest: decision.requestId,
approver: 'supervisor-agent',
metadata: {
amount,
reason: 'Purchase exceeds $5,000 threshold',
deadline: '2h'
}
});
if (approval.approved) {
// Supervisor approved — execute with elevated permission
return await executeWithApproval(approval.token);
}
return { success: false, reason: 'Supervisor denied the request' };
}
// Under $5,000 — auto-approved
return await executePurchase(amount);
}Expected Output
// Under threshold: auto-approved
{ "allowed": true, "autoApproved": true, "latency": "0.4ms" }
// Over threshold: pending supervisor approval
{ "status": "pending_approval", "approver": "supervisor-agent", "deadline": "2h" }
// After supervisor approves
{ "allowed": true, "approvedBy": "supervisor-agent", "approvalToken": "apv_..." }4
Fintech Trading Bot with Compliance
A trading agent with position limits, compliance checks, and real-time audit logging.
Code
async function executeTrade(symbol: string, side: string, quantity: number, price: number) {
const totalValue = quantity * price;
const decision = await permit.authorize({
agent: 'trading-bot-alpha',
action: 'trade',
resource: `market/${symbol}`,
context: {
side, // "buy" or "sell"
quantity,
price,
totalValue,
market: 'NYSE',
riskScore: await calculateRiskScore(symbol, quantity),
portfolioExposure: await getPortfolioExposure(symbol)
}
});
if (!decision.allowed) {
// Log the denied trade for compliance reporting
await permit.audit.log({
event: 'trade_denied',
agent: 'trading-bot-alpha',
details: { symbol, side, totalValue, reason: decision.reason }
});
return { executed: false, reason: decision.reason };
}
// Execute the trade
const trade = await broker.execute({ symbol, side, quantity, price });
// Every executed trade is automatically logged to the Merkle audit trail
return { executed: true, tradeId: trade.id, auditHash: decision.auditHash };
}Expected Output
// Normal trade: ALLOWED
{ "allowed": true, "policies": ["position-limit: PASS", "risk-threshold: PASS", "daily-volume: PASS"] }
// High risk trade: DENIED
{ "allowed": false, "reason": "risk score 0.82 exceeds threshold 0.7 for trades over $50,000" }
// Audit trail entry
{ "auditHash": "0x7f3a...e91c", "merkleRoot": "0xab12...", "signature": "ed25519:..." }