@agentguard/sdk
v0.1.4
Published
Official JavaScript/TypeScript SDK for AgentGuard AI authorization service
Maintainers
Readme
AgentGuard JavaScript/TypeScript SDK
Official JavaScript/TypeScript SDK for AgentGuard - AI-native authorization and compliance platform.
Installation
npm install @agentguard/sdk
# or
yarn add @agentguard/sdkQuick Start
import { AgentGuard } from '@agentguard/sdk';
// Initialize the client
const agentGuard = new AgentGuard({
apiKey: 'your-api-key-here',
baseUrl: 'https://agentguard-production.up.railway.app' // optional, this is the default
});
// Check authorization
const { allowed } = await agentGuard.authorize({
subject: 'user-123',
resource: 'gpt-4-model',
action: 'invoke',
context: {
ip: '192.168.1.1',
userRole: 'developer'
}
});
if (allowed) {
// Proceed with AI model invocation
} else {
// Handle unauthorized access
}API Reference
Initialize Client
const agentGuard = new AgentGuard({
apiKey: string; // Required: Your API key
baseUrl?: string; // Optional: API base URL (default: production URL)
timeout?: number; // Optional: Request timeout in ms (default: 30000)
retries?: number; // Optional: Number of retries (default: 3)
});Authorization
Check if a subject can perform an action on a resource:
const response = await agentGuard.authorize({
subject: string; // Required: User or service identifier
resource: string; // Required: Resource being accessed
action: string; // Required: Action being performed
context?: Record<string, any> // Optional: Additional context
});
// Response
{
allowed: boolean;
reason?: string;
metadata?: Record<string, any>;
}Audit Trails
Retrieve audit trails with filtering:
const trails = await agentGuard.getAuditTrails({
startDate?: string; // Optional: ISO date string
endDate?: string; // Optional: ISO date string
limit?: number; // Optional: Max results (default: 100)
offset?: number; // Optional: Pagination offset
});
// Response
{
audit_trails: Array<{
id: string;
timestamp: string;
event_type: string;
event_data: Record<string, any>;
signature: string;
previous_hash: string;
}>;
total_count: number;
limit: number;
offset: number;
}Export Audit Trails
Export audit trails in JSON or CSV format:
// Export as JSON
const jsonData = await agentGuard.exportAuditTrails('json', {
startDate?: string;
endDate?: string;
limit?: number;
offset?: number;
});
// Export as CSV
const csvData = await agentGuard.exportAuditTrails('csv', {
startDate?: string;
endDate?: string;
});Usage Statistics
Get usage statistics:
const usage = await agentGuard.getUsage({
startDate?: string; // Optional: ISO date string
endDate?: string; // Optional: ISO date string
resource?: string; // Optional: Filter by resource
});
// Response
{
usage: Array<{
resource: string;
action: string;
count: number;
}>;
total_requests: number;
period: {
start: string;
end: string;
};
}Storage Configuration
Configure storage provider:
await agentGuard.configureStorage({
provider: 'postgresql' | 'mysql' | 's3' | 'supabase';
config: {
// Provider-specific configuration
}
});Get current storage configuration:
const config = await agentGuard.getStorageConfig();Health Check
Check service health:
const health = await agentGuard.health();
// Response: { status: string; version: string; services: Record<string, any> }Error Handling
The SDK includes automatic retry logic for network errors and 5xx responses. Errors are formatted with additional context:
try {
await agentGuard.authorize({ ... });
} catch (error) {
if (error.name === 'AgentGuardError') {
console.error('API Error:', error.message);
console.error('Status:', error.status);
console.error('Code:', error.code);
console.error('Details:', error.details);
}
}TypeScript Support
This SDK is written in TypeScript and includes full type definitions. All request/response interfaces are exported:
import {
AuthorizeParams,
AuthorizeResponse,
AuditTrail,
UsageStats,
ApiError
} from '@agentguard/sdk';Examples
Protecting an AI Endpoint
import express from 'express';
import { AgentGuard } from '@agentguard/sdk';
const app = express();
const agentGuard = new AgentGuard({ apiKey: process.env.AGENTGUARD_API_KEY });
app.post('/api/ai/complete', async (req, res) => {
try {
// Check authorization
const { allowed, reason } = await agentGuard.authorize({
subject: req.user.id,
resource: 'gpt-4',
action: 'complete',
context: {
ip: req.ip,
promptLength: req.body.prompt.length,
userTier: req.user.tier
}
});
if (!allowed) {
return res.status(403).json({ error: reason });
}
// Proceed with AI completion
const completion = await callOpenAI(req.body.prompt);
res.json({ completion });
} catch (error) {
console.error('Authorization error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});Audit Trail Retrieval
// Get today's audit trails
const today = new Date();
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
const trails = await agentGuard.getAuditTrails({
startDate: yesterday.toISOString(),
endDate: today.toISOString(),
limit: 50
});
console.log(`Found ${trails.total_count} audit events`);
trails.audit_trails.forEach(trail => {
console.log(`${trail.timestamp}: ${trail.event_type}`);
});