TypeScript package for AppSec AI Agent management
npm install appsec-agentA TypeScript package that provides AI-powered agents for Application Security (AppSec) tasks, built on top of the Claude Agent SDK. It helps automate mundane application security operations and streamline workflows.
๐ฆ Available on npm: Install with npm install appsec-agent
- AI-Powered AppSec Automation: Leverage Claude's capabilities for application security
- Multiple Agent Types: Simple query agent, code review agent, and threat modeler for different use cases
- Tool Permission Management: Advanced tool permission callbacks with bypass mode for trusted operations
- Code Review Capabilities: Automated security and privacy issue detection in code
- Modular Agent Architecture: Easy to extend and customize agents for specific use cases
- Simple Integration: Built on the Claude Agent SDK for seamless AI integration
- Production Ready: Stable package with proper error handling and configuration
- Thread-Safe for Web Applications: Designed for concurrent usage in web applications with isolated instance state
- Comprehensive Testing: Full test coverage including concurrency tests for web application scenarios
- Installation
- Quick Start
- Configuration
- Available Agents
- Web Application Usage
- Architecture
- Usage Examples
- Development
- Testing
- Node.js 18.0 or higher
- npm or yarn
- Anthropic API key
``bash`
$ npm install -g @anthropic-ai/claude-code@2.0.58
`bash`
$ npm install appsec-agent
Or if you prefer global installation (to use the CLI command directly):
`bash`
$ npm install -g appsec-agent
The package includes pre-built JavaScript files, so no build step is required for usage.
Add these to your shell profile (.bashrc, .zshrc, etc.):
`bash`Anthropic API Configuration
export ANTHROPIC_API_KEY="your-anthropic-api-key"
export ANTHROPIC_BASE_URL="https://api.anthropic.com"
You can run the agent using the CLI command:
`bashIf installed globally
$ agent-run
๐ง Configuration
The agents can be configured through environment variables and configuration files. Key configuration options include:
-
ANTHROPIC_API_KEY: Your Anthropic API key (required)
- ANTHROPIC_BASE_URL: API endpoint URL (default: https://api.anthropic.com)
- MAX_TURNS: Maximum conversation turns (default: 1)Configuration file:
conf/appsec_agent.yaml๐ค Available Agents
$3
A general-purpose AppSec assistant that can:
- Answer security-related questions
- Help with security analysis tasks
- Provide guidance on security best practices
- Interactive query processing
- Search and analyze file directories (with --src_dir option)$3
A specialized agent for automated code analysis that can:
- Review code for security vulnerabilities
- Detect privacy issues in codebases
- Generate comprehensive security reports
- Support multiple output formats (Markdown, JSON, XML, CSV, XLSX)
- Analyze entire project directories
- Use advanced tools: Read, Grep, and Write capabilities
- Accept deployment context via -c/--context for environment-specific analysis
- PR-focused review mode via -d/--diff-context for optimized token usage$3
A specialized agent for comprehensive threat modeling that can:
- Generate ASCII text-based Data Flow Diagrams (DFD)
- Perform STRIDE methodology threat modeling on DFDs
- Create detailed risk registry reports with remediation plans
- Analyze codebases for security threats and vulnerabilities
- Generate multiple deliverable reports๐ Usage Examples
$3
`bash
Interactive query agent
$ npx agent-runQuery agent with source code directory context
$ npx agent-run -r simple_query_agent -s /path/to/source
`$3
`bash
Review code in current directory
$ npx agent-run -r code_reviewerReview specific source directory
$ npx agent-run -r code_reviewer -s /path/to/sourceCustom output file and format
$ npx agent-run -r code_reviewer -o security_report.html -f htmlReview with deployment context for more targeted analysis
$ npx agent-run -r code_reviewer -s ./src \
-c "AWS Lambda function in production VPC, handles user authentication via API Gateway, processes PII data"Kubernetes microservice with compliance context
$ npx agent-run -r code_reviewer -s ./payment-service \
-c "Kubernetes microservice on GKE, PCI-DSS compliant environment, internal service mesh only"Internal tool with access context
$ npx agent-run -r code_reviewer -s ./admin-cli \
-c "Internal CLI tool run by DevOps, requires VPN access, elevated AWS IAM permissions"
`The
-c/--context option provides deployment and environment information that helps the agent:
- Focus on environment-specific vulnerabilities (e.g., Lambda event injection, K8s secrets exposure)
- Consider infrastructure mitigations already in place
- Prioritize findings based on actual threat landscape
- Recommend best practices appropriate for the stated architecture$3
For Pull Request reviews, use the
-d/--diff-context option to provide a JSON file containing only the changed code. This significantly reduces token usage by focusing the review on actual changes rather than the entire codebase.`bash
Review a PR using diff context
$ npx agent-run -r code_reviewer -d pr-diff.jsonCombine with source directory for full file access when needed
$ npx agent-run -r code_reviewer -d pr-diff.json -s ./srcWith additional deployment context
$ npx agent-run -r code_reviewer -d pr-diff.json -c "Production API, handles PII"
`The diff context JSON file should follow this structure:
`json
{
"prNumber": 123,
"baseBranch": "main",
"headBranch": "feature/auth",
"headSha": "abc123def456",
"owner": "your-org",
"repo": "your-repo",
"files": [
{
"filePath": "src/auth/login.ts",
"language": "typescript",
"fileType": "modified",
"imports": "import bcrypt from 'bcrypt';",
"hunks": [
{
"startLine": 42,
"endLine": 55,
"beforeContext": "// Previous context",
"changedCode": "+const password = req.body.password;",
"afterContext": "// Following context",
"containingFunction": "async function login(req, res)"
}
]
}
],
"totalFilesChanged": 1,
"totalLinesAdded": 10,
"totalLinesRemoved": 5
}
`Note: If
--diff-context is provided without the code_reviewer role, a warning will be displayed as the option is only applicable to code reviews.$3
`bash
Run threat modeler on current directory
$ npx agent-run -r threat_modelerRun threat modeler on specific source directory
$ npx agent-run -r threat_modeler -s /path/to/source
`$3
`bash
$ npx agent-run -l
`$3
`bash
$ npx agent-run -v
`Note: If you installed the package globally, you can use
agent-run directly instead of npx agent-run.๐ Web Application Usage
This package is designed to be thread-safe for use in web applications where multiple requests may be processed concurrently.
$3
- Instance Isolation: Each
AgentActions and AgentOptions instance maintains isolated state
- Conversation History Isolation: Conversation history is stored per instance, preventing cross-contamination between requests
- Tool Usage Log Management: Tool usage logs are private and can be cleared between requests
- Working Directory Safety: Working directory is captured once per request to prevent race conditions$3
1. Create New Instances Per Request: Always create a new
AgentActions instance for each HTTP request:`typescript
import { AgentActions, AgentArgs, loadYaml } from 'appsec-agent';app.post('/api/query', async (req, res) => {
const confDict = loadYaml('conf/appsec_agent.yaml');
const args: AgentArgs = {
role: 'simple_query_agent',
environment: 'default',
verbose: false
};
// Create new instance per request
const agentActions = new AgentActions(confDict, 'default', args);
// Use agentActions for this request only
const result = await agentActions.simpleQueryClaudeWithOptions(req.body.query);
res.json({ result });
});
`2. Clear Tool Usage Logs: If reusing
AgentOptions instances, clear logs between requests:`typescript
const agentOptions = new AgentOptions(confDict, environment);
// ... use agentOptions ...
agentOptions.clearToolUsageLog(); // Clear before next request
`3. Pass Working Directory Explicitly: When using file operations, pass the working directory explicitly:
`typescript
import { validateOutputFilePath } from 'appsec-agent';// In web application context
const workingDir = process.cwd(); // Capture once per request
const outputPath = validateOutputFilePath('report.md', workingDir);
`$3
- โ
Safe: Creating new instances per request
- โ
Safe: Using captured working directory
- โ Unsafe: Reusing the same instance across multiple requests
- โ Unsafe: Calling
process.cwd() multiple times in concurrent contexts๐ Architecture
The AppSec AI Agent is built with a modular architecture consisting of several key components:
$3
-
AgentActions: Handles async interactions with Claude agents, including simple queries, code reviews, and threat modeling. Maintains isolated conversation history per instance.
- AgentOptions: Manages configuration, tool permissions, and permission modes for different agent types. Provides private tool usage logging with getter and clear methods.
- utils: Utility functions for file operations, YAML loading, and project management with thread-safe path validation
- agent-run: Command-line interface script for running agents$3
`
appsec-agent/
โโโ src/
โ โโโ agent_actions.ts # Agent interaction logic
โ โโโ agent_options.ts # Agent configuration management
โ โโโ main.ts # Main application logic
โ โโโ utils.ts # Utility functions
โ โโโ __tests__/
โ โโโ concurrency.test.ts # Concurrency and thread-safety tests
โ โโโ ... # Other test files
โโโ bin/
โ โโโ agent-run.ts # CLI script (TypeScript source)
โโโ dist/ # Compiled output (generated)
โ โโโ src/ # Compiled library code
โ โโโ bin/
โ โโโ agent-run.js # Compiled CLI entry point
โโโ conf/
โ โโโ appsec_agent.yaml # General configuration file
โโโ package.json
โโโ tsconfig.json
โโโ README.md
`$3
#### AgentOptions Methods
-
getToolUsageLog(): Returns a copy of the tool usage log (read-only access)
- clearToolUsageLog(): Clears the tool usage log (useful for web applications)
- toolPermissionCallback(): Handles tool permission requests
- getSimpleQueryAgentOptions(): Gets options for simple query agent
- getCodeReviewerOptions(): Gets options for code reviewer
- getThreatModelerOptions(): Gets options for threat modeler
- getDiffReviewerOptions(): Gets options for PR diff-focused code reviewer#### Diff Context Functions
-
validateDiffContext(data): Validates diff context JSON structure with comprehensive field validation
- formatDiffContextForPrompt(context): Formats diff context into a prompt for AI analysis#### Path Validation Functions
-
validateInputFilePath(filePath, baseDir): Validates input file paths for security concerns
- validateOutputFilePath(filePath, baseDir): Validates output file paths to prevent directory traversal
- isSafePath(filePath, allowAbsolute): Checks if a path is safe from traversal attacks๐ Development
This section is for developers who want to contribute to the package or modify it locally.
$3
1. Clone the repository:
`bash
$ git clone
$ cd appsec-agent
`2. Install dependencies:
`bash
$ npm install
`3. Build the project:
`bash
$ npm run build
`This will compile the TypeScript source files to JavaScript in the
dist/ directory.$3
`bash
Build the package
$ npm run buildClean build artifacts
$ npm run clean
`$3
During development, you can run the agent directly from source:
`bash
Using ts-node (no build needed)
$ npx ts-node bin/agent-run.tsOr build first, then run
$ npm run build
$ node dist/bin/agent-run.js
`๐งช Testing
The project includes comprehensive test coverage including concurrency tests for web application scenarios.
$3
`bash
Run all tests
$ npm testRun tests in watch mode
$ npm run test:watchRun tests with coverage
$ npm run test:coverageRun specific test file
$ npm test -- concurrency.test.ts
``- Unit Tests: Core functionality for all components
- Integration Tests: End-to-end agent workflows
- Concurrency Tests: Thread-safety verification for web application usage
- Conversation history isolation
- Tool usage log isolation
- Concurrent file operations
- Race condition prevention
- Memory leak prevention
All tests pass including:
- โ
187 total tests
- โ
11 concurrency tests
- โ
51 diff context validation tests
- โ
Full coverage of core functionality
- Claude Agent SDK Documentation
- Anthropic API Documentation
- Claude Code Documentation
This project is licensed under the MIT License.
Sam Li - Initial work - yang.li@owasp.org
---
Built with โค๏ธ for the AppSec community