npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

agentguard-sdk

v0.2.2

Published

TypeScript/JavaScript SDK for AI Agent Security Platform

Readme

AgentGuard SDK

npm version TypeScript License: MIT

TypeScript/JavaScript SDK for the AI Agent Security Platform. Secure your AI agents with comprehensive security evaluation, policy enforcement, and audit trails.

🚀 Quick Start

Installation

npm install agentguard-sdk

Basic Usage

import { AgentGuard } from 'agentguard-sdk';

// Initialize the SDK
const agentGuard = new AgentGuard({
  apiKey: 'your-api-key',
  ssaUrl: 'http://localhost:3001'
});

// Secure tool execution
const result = await agentGuard.executeTool(
  'web-search',
  { query: 'AI security best practices' },
  undefined,
  async (toolName, params) => {
    // Your tool execution logic here
    return await executeWebSearch(params.query);
  }
);

if (result.success) {
  console.log('Tool executed successfully:', result.data);
} else {
  console.log('Tool execution denied:', result.error?.message);
}

📋 Features

  • 🔒 Security Evaluation: Evaluate tool calls before execution
  • 🛡️ Policy Enforcement: Automatic policy-based decision making
  • 🔄 Request Transformation: Safe transformation of risky operations
  • 📊 Audit Trail: Complete audit logging for compliance
  • ⚡ Performance: < 100ms security evaluation overhead
  • 🔧 TypeScript Support: Full type safety and IntelliSense
  • 🌐 Framework Agnostic: Works with any JavaScript/Node.js agent

🏗️ Architecture

The AgentGuard SDK acts as a security middleware between your AI agent and its tool executions:

Your AI Agent → AgentGuard SDK → Security Sidecar Agent → Policy Decision → Tool Execution

📖 API Reference

AgentGuard Class

Constructor

new AgentGuard(config: AgentGuardConfig)

Configuration Options:

| Option | Type | Required | Default | Description | |--------|------|----------|---------|-------------| | apiKey | string | ✅ | - | API key for SSA authentication | | ssaUrl | string | ✅ | - | Security Sidecar Agent URL | | agentId | string | ❌ | auto-generated | Unique agent identifier | | timeout | number | ❌ | 5000 | Request timeout in milliseconds | | retries | number | ❌ | 3 | Number of retry attempts | | debug | boolean | ❌ | false | Enable debug logging |

Methods

executeTool<T>(toolName, parameters, context?, toolExecutor?): Promise<ToolExecutionResult<T>>

Execute a tool with security evaluation.

const result = await agentGuard.executeTool(
  'web-search',
  { query: 'AI security' },
  { sessionId: 'session-123' },
  async (toolName, params) => {
    return await myToolExecutor(toolName, params);
  }
);
evaluateTool(toolName, parameters, context?): Promise<SecurityDecision>

Evaluate tool security without execution.

const decision = await agentGuard.evaluateTool('system-command', { cmd: 'ls' });
console.log(decision.action); // 'allow', 'deny', or 'transform'
healthCheck(): Promise<HealthStatus>

Check Security Sidecar Agent health.

const health = await agentGuard.healthCheck();
console.log(health.status); // 'healthy'
getAuditTrail(options?): Promise<AuditTrailResponse>

Get audit trail for the current agent.

const audit = await agentGuard.getAuditTrail({ limit: 10 });
console.log(audit.auditTrail.entries);
getStatistics(): SDKStatistics

Get SDK usage statistics.

const stats = agentGuard.getStatistics();
console.log(`Success rate: ${stats.allowedRequests / stats.totalRequests * 100}%`);

🔒 Security Decisions

The SDK handles three types of security decisions:

Allow ✅

Safe operations that can proceed normally.

// Example: Web search
const result = await agentGuard.executeTool('web-search', { query: 'AI news' });
// result.securityDecision.action === 'allow'

Deny ❌

Dangerous operations that are blocked.

// Example: System command
const result = await agentGuard.executeTool('system-command', { cmd: 'rm -rf /' });
// result.success === false
// result.securityDecision.action === 'deny'

Transform 🔄

Risky operations that are modified for safety.

// Example: File write → File read
const result = await agentGuard.executeTool('file-write', { path: '/tmp/test.txt' });
// result.securityDecision.action === 'transform'
// result.securityDecision.transformedRequest.toolName === 'file-read'

🛠️ Examples

JavaScript Example

const { AgentGuard } = require('agentguard-sdk');

const agentGuard = new AgentGuard({
  apiKey: 'test-api-key-12345',
  ssaUrl: 'http://localhost:3001',
  debug: true
});

// Simple tool execution
agentGuard.executeTool('web-search', { query: 'AI security' })
  .then(result => {
    if (result.success) {
      console.log('Search completed:', result.data);
    } else {
      console.log('Search denied:', result.error.message);
    }
  })
  .catch(console.error);

TypeScript Example

import { AgentGuard, ToolExecutionResult } from 'agentguard-sdk';

interface SearchResult {
  query: string;
  results: Array<{ title: string; url: string }>;
}

const agentGuard = new AgentGuard({
  apiKey: process.env.AGENT_GUARD_API_KEY!,
  ssaUrl: process.env.SSA_URL!
});

const searchTool = async (query: string): Promise<SearchResult> => {
  const result: ToolExecutionResult<SearchResult> = await agentGuard.executeTool(
    'web-search',
    { query },
    undefined,
    async (toolName, params) => {
      // Your search implementation
      return {
        query: params.query,
        results: await performWebSearch(params.query)
      };
    }
  );

  if (!result.success) {
    throw new Error(`Search denied: ${result.error?.message}`);
  }

  return result.data!;
};

🔧 Error Handling

The SDK provides comprehensive error handling with specific error types:

import { isAgentGuardError, AgentGuardErrorCode } from 'agentguard-sdk';

try {
  const result = await agentGuard.executeTool('my-tool', { param: 'value' });
} catch (error) {
  if (isAgentGuardError(error)) {
    switch (error.code) {
      case AgentGuardErrorCode.AUTHENTICATION_ERROR:
        console.error('Invalid API key');
        break;
      case AgentGuardErrorCode.NETWORK_ERROR:
        console.error('Cannot connect to SSA');
        break;
      case AgentGuardErrorCode.SECURITY_DENIED:
        console.error('Tool execution denied by security policy');
        break;
      default:
        console.error('AgentGuard error:', error.message);
    }
  } else {
    console.error('Unknown error:', error);
  }
}

📊 Monitoring & Analytics

Statistics

const stats = agentGuard.getStatistics();
console.log({
  totalRequests: stats.totalRequests,
  successRate: (stats.allowedRequests + stats.transformedRequests) / stats.totalRequests,
  averageResponseTime: stats.averageResponseTime,
  errorRate: stats.errorCount / stats.totalRequests
});

Audit Trail

const audit = await agentGuard.getAuditTrail({ limit: 50 });

// Analyze security decisions
const decisions = audit.auditTrail.entries.filter(e => e.type === 'security_decision');
const deniedRequests = decisions.filter(e => e.action === 'deny');

console.log(`Denied requests: ${deniedRequests.length}/${decisions.length}`);

🧪 Testing

The SDK includes comprehensive testing utilities:

// Mock the SSA for testing
const mockAgentGuard = new AgentGuard({
  apiKey: 'test-key',
  ssaUrl: 'http://localhost:3001'
});

// Test security evaluation
const decision = await mockAgentGuard.evaluateTool('test-tool', { param: 'value' });
expect(decision.action).toBe('allow');

🔗 Integration Examples

LangChain Integration

import { AgentGuard } from 'agentguard-sdk';
import { Tool } from 'langchain/tools';

class SecureWebSearchTool extends Tool {
  name = 'web-search';
  description = 'Search the web securely';
  
  private agentGuard = new AgentGuard({
    apiKey: process.env.AGENT_GUARD_API_KEY!,
    ssaUrl: process.env.SSA_URL!
  });

  async _call(query: string): Promise<string> {
    const result = await this.agentGuard.executeTool(
      'web-search',
      { query },
      undefined,
      async (toolName, params) => {
        return await this.performSearch(params.query);
      }
    );

    if (!result.success) {
      throw new Error(`Search denied: ${result.error?.message}`);
    }

    return JSON.stringify(result.data);
  }

  private async performSearch(query: string): Promise<any> {
    // Your search implementation
  }
}

📚 Advanced Usage

See the examples directory for more advanced usage patterns:

🤝 Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🆘 Support

🔄 Changelog

See CHANGELOG.md for a list of changes and version history.