# https://github.com/AgentsID-dev/agentsid 项目说明书

生成时间：2026-05-15 06:46:29 UTC

## 目录

- [Project Introduction](#project-introduction)
- [Quick Start Guide](#quick-start-guide)
- [High-Level Architecture](#high-level-architecture)
- [Deny-First Permission System](#permission-system)
- [Token Authentication and Security](#token-authentication)
- [Tamper-Evident Audit System](#audit-system)
- [Backend API Reference](#backend-api)
- [Approval Gates and Webhooks](#approval-workflows)
- [Web Dashboard](#web-dashboard)
- [Multi-Language SDKs](#multi-language-sdks)

<a id='project-introduction'></a>

## Project Introduction

### 相关页面

相关主题：[Quick Start Guide](#quick-start-guide), [High-Level Architecture](#high-level-architecture)

<details>
<summary>Relevant Source Files</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/AgentsID-dev/agentsid/blob/main/README.md)
- [web/src/pages/landing.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/landing.tsx)
- [web/src/pages/guides.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/guides.tsx)
- [web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)
- [web/src/pages/research.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/research.tsx)
- [web/src/pages/privacy.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/privacy.tsx)
- [web/src/pages/terms.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/terms.tsx)
- [server/src/services/notifications.py](https://github.com/AgentsID-dev/agentsid/blob/main/server/src/services/notifications.py)
</details>

# Project Introduction

AgentsID is an identity, permissions, and audit infrastructure platform designed specifically for AI agents. Positioned as "The Auth0 for the agent economy," it provides a standardized way to identify AI agents, control what actions they can perform, and maintain complete audit trails of their activities.

## Overview

AI agents are increasingly accessing databases, sending emails, calling APIs, and making purchases on behalf of users. However, there has been no standard way to identify these agents, limit their capabilities, or trace their actions back to the humans who authorized them.

AgentsID solves this fundamental infrastructure gap by providing:

- **Identity management** for AI agents
- **Permission controls** to restrict tool access
- **Audit logging** with tamper-evident hash chains
- **Security scanning** for MCP (Model Context Protocol) servers

资料来源：[README.md:1-20]()

## The Problem

Current AI agent deployments suffer from significant security and visibility gaps:

| Statistic | Finding |
|-----------|---------|
| MCP servers requiring authentication | 88% |
| MCP servers actually using OAuth | Only 8.5% |
| Servers relying on static API keys in environment variables | 53% |
| Organizations unable to track agent activities in real-time | 80% |

资料来源：[README.md:25-29]()

### Why Traditional Auth Fails

Auth0 and similar identity platforms were designed for human users, not autonomous AI agents. AgentsID specifically addresses the unique requirements of agent-to-tool interactions, including:

- Machine-to-machine authentication
- Granular tool-level permissions
- Audit trails that capture the full context of agent decisions
- Integration with MCP servers without requiring developers to build custom auth

## Core Concepts

### Projects

A **project** is the fundamental organizational unit in AgentsID. Each project contains:

- Agent definitions
- Permission rules
- Audit logs
- API credentials (project key)

Projects are created via CLI with the `init` command or through the dashboard. Each project receives a unique project key (prefixed with `aid_proj_`) that servers use to communicate with the AgentsID API.

```bash
$ npx agentsid init "My Production App"
Creating project "My Production App"...
Project created successfully!

  Project ID:  proj_a1b2c3d4e5f6
  API Key:     aid_proj_xR7kM2pQ9...
  Plan:        free
```

资料来源：[web/src/pages/guides.tsx:1-15](), [web/src/pages/docs.tsx:1-12]()

### Agents

An **agent** is an AI-powered entity registered within a project. Each agent:

- Has a unique agent ID (prefixed with `agt_`)
- Receives an authentication token (prefixed with `aid_tok_`)
- Operates on behalf of a human user
- Has specific tool permissions assigned

Agents are registered using the CLI:

```bash
$ npx agentsid register-agent --name "Email Assistant" --on-behalf-of "user_abc123" --permissions "send_email,read_contacts" --ttl 24
Agent registered!

  Agent ID:   agt_7x9k2mNpQ4rS1tUv
  Token:      aid_tok_eyJzdWIiOi...
  Expires:    2026-03-26T14:30:00Z
```

资料来源：[web/src/pages/docs.tsx:15-35]()

### Permissions

AgentsID uses a pattern-based permission system. Permission rules are defined as tool name patterns with an allow or deny action:

| Tool | Parameters Required | Result | Reason |
|------|---------------------|--------|--------|
| `search_memories` | any | Allowed | Matches `search_*` allow rule |
| `delete_memory` | any | Denied | Condition requires params, fail-closed |
| `list_categories` | any | Denied | No matching rule, default deny |

资料来源：[web/src/pages/docs.tsx:100-115]()

Default behavior is **deny-all** — if no rule matches a tool call, the request is blocked. This fail-closed approach ensures that agents can only access tools explicitly permitted.

### Audit Logs

Every tool call made through AgentsID generates an audit log entry containing:

- Timestamp
- Agent ID
- Tool name
- Action (ALLOW/DENY)
- Result (success/blocked)
- Delegating user ID
- Parameters passed
- Error messages (if any)

The audit system maintains a **SHA-256 hash chain** where each entry is cryptographically linked to its predecessor. The first entry uses `"genesis"` as its initial previous hash value.

资料来源：[web/src/pages/docs.tsx:120-135]()

## Architecture

### System Flow

```mermaid
graph TD
    A[Your Application] -->|Tool Call| B[AgentsID SDK]
    B -->|Validate + Log| C[AgentsID API]
    C -->|Check Permissions| D[Permission Engine]
    D -->|Allow/Deny| C
    C -->|Audit Entry| E[(Audit Log DB)]
    C -->|Response| B
    B -->|Result| A
    
    F[Dashboard] -->|Manage| G[Projects & Agents]
    F -->|View| E
    H[Scanner] -->|Security Audit| G
```

### SDK Integration

AgentsID provides a lightweight SDK approach with a 200-line bash hook. The integration philosophy emphasizes:

> "No SDK to learn, no language runtime to match. If your agent can run a shell script before a tool call, AgentsID works."

资料来源：[web/src/pages/landing.tsx:1-50]()

Available SDK packages:

| Package Manager | Package Name |
|----------------|--------------|
| npm | `@agentsid/sdk` |
| pip | `agentsid` |
| RubyGems | `agentsid` |

### Registry and Scanner

The platform maintains a **public registry** of MCP servers that have been security-scanned. Each server receives a security grade based on findings:

```mermaid
graph LR
    A[MCP Server] -->|Scan| B[AgentsID Scanner]
    B -->|Findings| C[Grade Calculator]
    C -->|Grade A-F| D[Public Registry]
    C -->|Recommendations| E[Dashboard]
```

The scanner analyzes servers for:

- Authentication mechanisms
- Dangerous patterns
- Deceptive language
- Invisible characters
- Context weighting issues

资料来源：[web/src/pages/research.tsx:1-30](), [web/src/pages/grade.tsx:1-40]()

## Key Features

### Security and Privacy

AgentsID implements privacy-first data practices:

| Data Type | Storage Policy |
|-----------|---------------|
| Email addresses | Stored for account management |
| Project data | Stored in project container |
| Agent definitions | Stored in project container |
| Audit logs | Stored with SHA-256 hash chain |
| API keys | Only hashes stored, never raw |
| Analytics | PostHog, opt-in only, consent-gated |

资料来源：[web/src/pages/privacy.tsx:20-35]()

### CLI Commands

| Command | Description |
|---------|-------------|
| `init` | Create a new project |
| `register-agent` | Register a new agent |
| `list-agents` | List all agents in project |
| `audit` | Query audit logs |
| `claim` | Claim a server on the registry |

Usage: `npx agentsid <command>`

资料来源：[web/src/pages/docs.tsx:1-90]()

### Acceptable Use

AgentsID permits any lawful use but explicitly prohibits:

- Platform abuse (malformed requests, resource exhaustion)
- Security circumvention (bypassing HMAC verification, tampering with audit logs)
- Illegal agent registrations
- Unauthorized data scraping
- White-label resale without agreement
- Impersonation of AgentsID

资料来源：[web/src/pages/terms.tsx:1-50]()

## Quick Start

To integrate AgentsID into your application:

```bash
# Step 1: Install the setup CLI
$ npx @agentsid/setup@latest

# Step 2: Initialize a project
$ npx agentsid init "My Protected Server"

# Step 3: Install the SDK
$ npm install @agentsid/sdk

# Step 4: Register an agent
$ npx agentsid register-agent --name "My Agent" --on-behalf-of "user_id"

# Step 5: Integrate the bash hook before tool calls
```

The AgentsID hook can be embedded directly into your agent's tool-calling workflow, requiring no SDK dependencies in your agent code.

资料来源：[web/src/pages/landing.tsx:35-55](), [web/src/pages/guides.tsx:20-60]()

## Platform Components

| Component | Purpose | Access |
|-----------|---------|--------|
| Dashboard | Project and agent management | agentsid.dev/dashboard |
| Registry | Public MCP server listings | agentsid.dev/registry |
| Scanner | Security analysis tool | `npx @agentsid/scanner` |
| Documentation | Guides and API reference | agentsid.dev/docs |
| CLI | Command-line interface | `npx agentsid` |

All research and scanner tools are open source and available on [GitHub](https://github.com/AgentsID-dev/agentsid-scanner).

资料来源：[web/src/pages/research.tsx:25-35]()

## Data Flow Summary

```mermaid
sequenceDiagram
    participant User
    participant Agent
    participant SDK
    participant AgentsID
    participant Tool
    
    User->>Agent: Authorize action
    Agent->>SDK: Call tool (e.g., send_email)
    SDK->>AgentsID: Validate request
    AgentsID->>AgentsID: Check permissions
    Alt Permission granted
        AgentsID->>Tool: Forward request
        Tool->>AgentsID: Response
        AgentsID->>SDK: Allow + log
        SDK->>Agent: Success
        Agent->>User: Result
    Else Permission denied
        AgentsID->>SDK: Block
        SDK->>Agent: Blocked response
        Agent->>User: Move on
    end
```

## Summary

AgentsID addresses a critical gap in the AI agent ecosystem by providing:

1. **Standardized identity** for AI agents operating across different platforms
2. **Fine-grained permissions** with pattern-based rules and fail-closed defaults
3. **Tamper-evident audit trails** using cryptographic hash chains
4. **Security visibility** through automated MCP server scanning
5. **Privacy compliance** with minimal data collection and opt-in analytics

By treating AI agents as first-class principals in your security model, AgentsID enables organizations to deploy AI agents with the same confidence and controls they have for human users.

资料来源：[README.md:15-25](), [web/src/pages/privacy.tsx:30-45]()

---

<a id='quick-start-guide'></a>

## Quick Start Guide

### 相关页面

相关主题：[Project Introduction](#project-introduction), [Multi-Language SDKs](#multi-language-sdks)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [web/src/pages/guides.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/guides.tsx)
- [web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)
- [web/src/pages/landing.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/landing.tsx)
- [web/src/pages/spec.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/spec.tsx)
- [web/src/components/dashboard/AuditFeed.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/components/dashboard/AuditFeed.tsx)
- [web/src/components/dashboard/OverviewTab.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/components/dashboard/OverviewTab.tsx)
- [web/src/pages/privacy.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/privacy.tsx)

</details>

# Quick Start Guide

This guide provides everything you need to integrate AgentsID into your AI agent workflow. AgentsID is an agent identity and permission management platform that allows you to register agents, define tool permissions, and audit all agent activity through a tamper-proof chain.

## Prerequisites

Before starting, ensure you have:

| Requirement | Version/Details |
|-------------|-----------------|
| Node.js | v18+ (for SDK usage) |
| npm/yarn | Latest stable |
| Account | agentsid.dev/dashboard |
| Project | Created via `npx agentsid init` |

资料来源：[web/src/pages/landing.tsx:1-50]()

## Installation

### Using the Setup Command (Recommended)

The fastest way to get started is using the official setup script:

```bash
npx @agentsid/setup@latest
```

资料来源：[web/src/pages/landing.tsx:50-80]()

### Using NPM/Yarn Directly

Alternatively, install the SDK directly into your project:

```bash
npm install @agentsid/sdk
# or
yarn add @agentsid/sdk
```

资料来源：[web/src/pages/guides.tsx:1-100]()

## Quick Start Workflow

```mermaid
graph TD
    A[Create Project] --> B[Get API Key]
    B --> C[Install SDK]
    C --> D[Register Agent]
    D --> E[Define Permissions]
    E --> F[Integrate Hook]
    F --> G[Monitor via Audit Trail]
```

资料来源：[web/src/pages/guides.tsx:100-200]()

## Step-by-Step Setup

### Step 1: Create a Project

Initialize a new AgentsID project using the CLI:

```bash
npx agentsid init "My Production App"
```

Expected output:

```
Creating project "My Production App"...
Project created successfully!

  Project ID:  proj_a1b2c3d4e5f6
  API Key:     aid_proj_xR7kM2pQ9...
  Plan:        free

  Store your API key securely. It will not be shown again.
```

资料来源：[web/src/pages/docs.tsx:1-80]()

### Step 2: Copy Your Project Key

After project creation, retrieve your project key from the dashboard at [agentsid.dev/dashboard](https://agentsid.dev/dashboard). The key format is `aid_proj_xxx...`.

资料来源：[web/src/pages/guides.tsx:200-300]()

### Step 3: Install the SDK

```bash
npm install @agentsid/sdk
```

This lightweight library handles:
- Communication with AgentsID API
- Token validation
- Event logging
- Permission enforcement

资料来源：[web/src/pages/guides.tsx:300-400]()

### Step 4: Register an Agent

Agents represent the AI entities in your system. Register them to receive authentication tokens:

```typescript
import { AgentsID } from '@agentsid/sdk';

const client = new AgentsID({
  projectKey: 'aid_proj_your_key_here',
});

const { agent, token, tokenId, expiresAt } = await client.registerAgent({
  name: 'production-claude',
  onBehalfOf: 'user_abc123',
  permissions: ['search_notes', 'save_note', 'list_notes'],
  ttlHours: 24,
  metadata: { version: '1.0.0' }
});
```

资料来源：[web/src/pages/docs.tsx:80-150]()

### Step 5: Configure MCP Server

For Claude Code or Cursor integration, create a server configuration:

```javascript
// server.mjs
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import { AgentsID } from '@agentsid/sdk';

const client = new AgentsID({ projectKey: process.env.AGENTSID_PROJECT_KEY });

const server = new McpServer({
  name: 'my-notes-server',
  version: '1.0.0'
});

server.tool(
  'save_note',
  'Create a new note',
  { content: z.string(), title: z.string() },
  async ({ content, title }) => {
    const result = await client.check({
      agentToken: process.env.AGENTSID_AGENT_TOKEN,
      tool: 'save_note',
      parameters: { content, title }
    });
    
    if (!result.allowed) {
      return { content: `Tool call blocked: ${result.reason}` };
    }
    
    // Execute tool logic here
    return { content: 'Note saved successfully' };
  }
);
```

资料来源：[web/src/pages/guides.tsx:400-500]()

### Step 6: Add to IDE Configuration

For Cursor, edit `.cursor/mcp.json`:

```json
{
  "mcpServers": {
    "my-notes-server": {
      "command": "node",
      "args": ["server.mjs"],
      "env": {
        "AGENTSID_PROJECT_KEY": "aid_proj_your_key_here",
        "AGENTSID_AGENT_TOKEN": "at_your_token_here"
      }
    }
  }
}
```

资料来源：[web/src/pages/guides.tsx:500-600]()

## Agent Management API

### SDK Methods Reference

| Method | Parameters | Returns | Description |
|--------|------------|---------|-------------|
| `registerAgent` | name, onBehalfOf, permissions?, ttlHours?, metadata? | `{ agent, token, tokenId, expiresAt }` | Create a new agent and issue its first token |
| `getAgent` | agentId | Agent | Get agent details by ID |
| `listAgents` | status?, limit? | Agent[] | List agents, optionally filtered by status |
| `updateAgent` | agentId, name?, metadata? | Agent | Update agent name or metadata |
| `refreshToken` | agentId, ttlHours? | `{ token, tokenId, expiresAt }` | Issue new token, revoke all previous |
| `check` | agentToken, tool, parameters | Decision | Validate a tool call against permissions |

资料来源：[web/src/pages/docs.tsx:150-200]()

### CLI Commands

| Command | Description |
|---------|-------------|
| `npx agentsid init` | Create a new project |
| `npx agentsid register-agent` | Register a new agent |
| `npx agentsid audit` | View audit logs |
| `npx agentsid verify` | Verify audit chain integrity |

资料来源：[web/src/pages/landing.tsx:80-120]()

## Permission Configuration

### Default Permission States

| Tool | Default Permission | Description |
|------|-------------------|--------------|
| `search_notes` | Allowed | Search notes by keyword |
| `save_note` | Allowed | Create a new note |
| `list_notes` | Allowed | List all notes |
| `delete_note` | Denied | Delete a note by ID |
| `admin_reset` | Denied | Wipe all data |

资料来源：[web/src/pages/guides.tsx:600-700]()

The agent has access to all five tools, but AgentsID will block any attempt to use `delete_note` or `admin_reset`. The agent doesn't even know it's being restricted—it just gets a "blocked" response.

## Audit Trail

### Viewing Audit Logs

The dashboard provides a real-time feed of all agent activity:

```mermaid
graph LR
    A[Tool Call] --> B[AgentsID API]
    B --> C{Allowed?}
    C -->|Yes| D[Execute Tool]
    C -->|No| E[Block & Log]
    D --> F[Create Audit Entry]
    E --> F
    F --> G[Update Hash Chain]
```

资料来源：[web/src/pages/components/dashboard/AuditFeed.tsx:1-60]()

### Audit Entry Structure

Each entry in the audit log contains:

```json
{
  "entryId": "entry_abc123",
  "timestamp": "2026-03-29T12:34:56.789Z",
  "agentId": "agent_def456",
  "delegationId": "del_xyz789",
  "tool": "github.push_files",
  "parameters": { "owner": "myorg", "repo": "myrepo", "branch": "main" },
  "decision": "allow",
  "matchedRule": 2,
  "constraintsEvaluated": ["rateLimit", "schedule"],
  "durationMs": 3,
  "prevEntryHash": "sha256:e3b0c44298fc1c149afb...",
  "entryHash": "sha256:a665a45920422f9d417e..."
}
```

资料来源：[web/src/pages/spec.tsx:1-80]()

### Chain Verification

AgentsID implements a hash chain for tamper detection:

```javascript
entryHash = SHA-256(canonicalize(entry with entryHash=null))
// First entry uses prevEntryHash: "genesis"
```

资料来源：[web/src/pages/spec.tsx:80-120]()

### Verification API

```bash
curl "https://api.agentsid.dev/api/v1/audit/verify" \
  -H "Authorization: Bearer aid_proj_xR7kM2pQ9..."
```

Response (chain intact):
```json
{
  "verified": true,
  "entries_checked": 1523,
  "message": "Integrity chain verified"
}
```

Response (chain broken):
```json
{
  "verified": false,
  "entries_checked": 1523,
  "broken_at_id": 42,
  "message": "Integrity chain broken at entry 42 -- possible tampering"
}
```

资料来源：[web/src/pages/docs.tsx:200-280]()

## Security & Privacy

### Data Handling

| Data Type | Storage | Retention |
|-----------|---------|-----------|
| Email | Encrypted | Until account deletion |
| Project Data | Encrypted | Until project deletion |
| Audit Logs | Hash-chained | 90 days (free), indefinite (paid) |
| API Keys | Hash only | Until key rotation |
| Analytics | Opt-in | PostHog's retention policy |

资料来源：[web/src/pages/privacy.tsx:1-100]()

### Key Security Points

- **No raw API keys stored** — Only hashed versions are retained
- **Analytics opt-in only** — Gated behind cookie consent banner
- **No data selling** — Explicitly prohibited in privacy policy
- **GDPR compliance** — Full data export and deletion capabilities

资料来源：[web/src/pages/privacy.tsx:100-200]()

## Dashboard Overview

### Main Features

| Section | Description |
|---------|-------------|
| **Overview Tab** | Recent activity feed, agent constellation view, quick stats |
| **Agents Tab** | Manage registered agents, view tokens, update permissions |
| **Audit Tab** | Searchable log of all tool decisions with chain verification |
| **Settings** | Project configuration, API keys, team management |

资料来源：[web/src/components/dashboard/OverviewTab.tsx:1-100]()

### Activity Feed Display

The audit feed displays:

- **Tool** — Name of the tool called
- **Decision** — `allow` or `deny`
- **Timestamp** — Full ISO 8601 format
- **Agent ID** — Registered agent identifier
- **Delegation Chain** — If sub-agents are involved

资料来源：[web/src/components/dashboard/AuditFeed.tsx:60-140]()

## Next Steps

After completing this guide:

1. **Explore the Registry** — View security grades of popular MCP tools at `/registry`
2. **Read the Specification** — Deep dive into the audit chain at `/spec`
3. **Join Research** — Access security research at `/research`
4. **Subscribe to Updates** — Get weekly security digests at `/digest`

资料来源：[web/src/pages/landing.tsx:120-180]()

## Troubleshooting

| Issue | Solution |
|-------|----------|
| `401 Unauthorized` | Verify your project key is correct |
| `403 Forbidden` | Agent token may be expired; refresh via `refreshToken()` |
| Chain verification fails | Contact support or check recent key rotations |
| Rate limiting | Upgrade plan or implement exponential backoff |

资料来源：[web/src/pages/docs.tsx:280-350]()

---

<a id='high-level-architecture'></a>

## High-Level Architecture

### 相关页面

相关主题：[Project Introduction](#project-introduction), [Backend API Reference](#backend-api), [Deny-First Permission System](#permission-system)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [web/src/pages/spec.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/spec.tsx) - Technical specifications
- [web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx) - API and SDK documentation
- [web/src/pages/guides.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/guides.tsx) - Integration guides
- [web/src/pages/privacy.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/privacy.tsx) - Privacy and data handling
- [web/src/pages/landing.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/landing.tsx) - Product overview
- [web/src/components/dashboard/AuditFeed.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/components/dashboard/AuditFeed.tsx) - Audit feed component
- [web/src/components/dashboard/OverviewTab.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/components/dashboard/OverviewTab.tsx) - Dashboard overview
- [README.md](https://github.com/AgentsID-dev/agentsid/blob/main/README.md) - Project overview
</details>

# High-Level Architecture

AgentsID is an identity, permissions, and audit infrastructure platform designed for AI agents. It functions as an authorization layer that sits between AI agents and the tools they execute, providing fine-grained access control, comprehensive audit logging, and tamper-evident verification capabilities.

## System Overview

AgentsID implements a centralized authorization model where every tool invocation is validated against a configurable rule engine before execution is permitted. The system maintains a cryptographic hash chain of all audit entries to detect tampering and provides real-time visibility into agent activity through a web-based dashboard.

```mermaid
graph TD
    A["🤖 AI Agent"] --> B["AgentsID SDK / MCP Server"]
    B --> C["Validation Middleware"]
    C --> D{"Allowed?"}
    D -->|Yes| E["Execute Tool"]
    D -->|No| F["Block + Log"]
    C --> G["Audit Log Service"]
    G --> H["Hash Chain"]
    G --> I["Dashboard"]
    H --> J["Verification API"]
```

## Core Components

### 1. SDK and Client Libraries

AgentsID provides multi-language SDKs for seamless integration into agent runtimes.

| Package | Registry | Purpose |
|---------|----------|---------|
| `@agentsid/sdk` | npm | Node.js/JavaScript integration |
| `agentsid` | PyPI | Python integration |
| `agentsid` | RubyGems | Ruby integration |

资料来源：[README.md:1-15](https://github.com/AgentsID-dev/agentsid/blob/main/README.md)

### 2. Agent Management API

The SDK exposes methods for registering and managing agents within a project.

| Method | Parameters | Returns | Description |
|--------|------------|---------|-------------|
| `registerAgent` | name, onBehalfOf, permissions?, ttlHours?, metadata? | { agent, token, tokenId, expiresAt } | Create a new agent and issue its first token |
| `getAgent` | agentId | Agent | Get agent details by ID |
| `listAgents` | status?, limit? | Agent[] | List agents, optionally filtered by status |
| `updateAgent` | agentId, name?, metadata? | Agent | Update agent name or metadata |
| `refreshToken` | agentId, ttlHours? | { token, tokenId, expiresAt } | Issue new token, revoke all previous |

资料来源：[web/src/pages/docs.tsx:1-80](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)

### 3. Validation Middleware

The core security component intercepts tool calls and validates them against configured permissions. Every tool call goes through a validation function before execution.

```mermaid
graph LR
    A["Tool Call Request"] --> B["Extract agent_token"]
    B --> C["Call AgentsID API"]
    C --> D{"Decision?"}
    D -->|allow| E["Execute Tool"]
    D -->|deny| F["Return blocked"]
```

资料来源：[web/src/pages/guides.tsx:1-50](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/guides.tsx)

## Audit Logging System

### Entry Schema

Every tool invocation generates an immutable audit entry with the following structure:

```json
{
  "entryId": "entry_abc123",
  "timestamp": "2026-03-29T12:34:56.789Z",
  "agentId": "agent_def456",
  "delegationId": "del_xyz789",
  "tool": "github.push_files",
  "parameters": { "owner": "myorg", "repo": "myrepo", "branch": "main" },
  "decision": "allow",
  "matchedRule": 2,
  "constraintsEvaluated": ["rateLimit", "schedule"],
  "durationMs": 3,
  "prevEntryHash": "sha256:e3b0c44298fc1c149afb...",
  "entryHash": "sha256:a665a45920422f9d417e..."
}
```

资料来源：[web/src/pages/spec.tsx:1-50](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/spec.tsx)

### Hash Chain Integrity

The audit log uses a cryptographic hash chain to ensure tamper-evidence. Each entry's hash includes the previous entry's hash, creating an immutable chain.

```javascript
entryHash = SHA-256(canonicalize(entry with entryHash=null))
// First entry uses prevEntryHash: "genesis"
```

Verification process iterates through entries and validates the hash chain:

```javascript
function verifyChain(entries: AuditEntry[]): boolean {
  for (let i = 1; i < entries.length; i++) {
    const prev = entries[i - 1]
    // Verify prevEntryHash matches previous entryHash
  }
}
```

资料来源：[web/src/pages/spec.tsx:1-50](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/spec.tsx)

### Audit Feed Component

The dashboard's AuditFeed component displays audit entries with delegation chain visualization:

| Field | Display |
|-------|---------|
| Agent ID | Monospace font, truncated |
| Timestamp | Full date/time format |
| Delegation Chain | Visual arrow-separated badges |
| Delegated By | Type and ID badges |

资料来源：[web/src/components/dashboard/AuditFeed.tsx:1-60](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/components/dashboard/AuditFeed.tsx)

## Permission and Constraint Engine

### Supported Constraint Types

The system supports multiple constraint types for fine-grained control:

| Type | Configuration | Purpose |
|------|---------------|---------|
| Rate Limit | `{"type": "rateLimit", "max": 100, "windowSeconds": 3600}` | Limit tool calls per time window |
| Schedule | `{"type": "schedule", "allow": ["09:00-17:00"]}` | Restrict execution to time windows |
| Budget | `{"type": "budget", "currency": "usd", "max": 10.00, "windowSeconds": 86400}` | Limit monetary cost |
| Sequence | `{"type": "sequence", "requires": ["filesystem.read_file"], "forbids": ["github.push_files"]}` | Enforce operation ordering |
| Session Limit | `{"type": "sessionLimit", "max": 5}` | Limit concurrent sessions |
| Risk Score | `{"type": "riskScore", "maxScore": 0.7}` | Block high-risk operations |
| IP Allowlist | `{"type": "ipAllowlist", "cidrs": ["10.0.0.0/8"]}` | Restrict by IP range |
| Chain Depth | `{"type": "chainDepth", "max": 2}` | Limit delegation depth |
| Cooldown | `{"type": "cooldown", "seconds": 300}` | Enforce wait periods |
| Anomaly Detection | `{"type": "anomaly"}` | ML-based behavior analysis |

资料来源：[web/src/pages/spec.tsx:1-80](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/spec.tsx)

### Example Permission Matrix

| Tool | Permission |
|------|------------|
| `search_notes` | allowed |
| `save_note` | allowed |
| `list_notes` | allowed |
| `delete_note` | denied |
| `admin_reset` | denied |

资料来源：[web/src/pages/guides.tsx:50-100](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/guides.tsx)

## API Endpoints

### Verification Endpoint

```
GET /api/v1/audit/verify
Authorization: Bearer <project_key>
```

**Response 200 OK (chain intact):**
```json
{
  "verified": true,
  "entries_checked": 1523,
  "message": "Integrity chain verified"
}
```

**Response 200 OK (chain broken):**
```json
{
  "verified": false,
  "entries_checked": 1523,
  "broken_at_id": 42,
  "message": "Integrity chain broken at entry 42 -- possible tampering"
}
```

### Usage Endpoint

```
GET /api/v1/audit/usage
Authorization: Bearer <project_key>
```

**Response:**
```json
{
  "events_this_month": 1200,
  "events_limit": 10000,
  "agents_active": 5,
  "agents_limit": 25,
  "plan": "free"
}
```

资料来源：[web/src/pages/docs.tsx:1-120](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)

## Model Context Protocol (MCP) Integration

AgentsID supports integration with MCP-compatible AI tools like Claude Code and Cursor through environment variable configuration:

```json
{
  "mcpServers": {
    "my-notes-server": {
      "command": "node",
      "args": ["server.mjs"],
      "env": {
        "AGENTSID_PROJECT_KEY": "aid_proj_your_key_here",
        "AGENTSID_AGENT_TOKEN": "at_your_token_here"
      }
    }
  }
}
```

资料来源：[web/src/pages/guides.tsx:100-150](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/guides.tsx)

## Data Flow

```mermaid
sequenceDiagram
    participant Agent as AI Agent
    participant SDK as AgentsID SDK
    participant API as AgentsID API
    participant Rules as Rule Engine
    participant Audit as Audit Service
    participant Hash as Hash Chain
    participant Dashboard as Web Dashboard

    Agent->>SDK: tool_call(tool_name, params)
    SDK->>API: validate(agent_token, tool_name, params)
    API->>Rules: evaluate(tool_name, constraints)
    Rules-->>API: allow/deny decision
    API-->>SDK: decision
    SDK-->>Agent: execute or block
    API->>Audit: log_entry(decision, metadata)
    Audit->>Hash: append_hash()
    Hash-->>Audit: hash_verified
    Dashboard->>API: fetch_entries()
    API-->>Dashboard: audit_feed
```

## Dashboard Overview

The web dashboard provides real-time visibility into agent activity:

| Component | Function |
|-----------|----------|
| Overview Tab | Activity feed, agent constellation, quick actions |
| Audit Feed | Filterable audit log with delegation chain |
| Agent Constellation | Visual representation of agent relationships |
| Quick Actions | Register agent, view audit, manage permissions |

资料来源：[web/src/components/dashboard/OverviewTab.tsx:1-80](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/components/dashboard/OverviewTab.tsx)

## Security Model

### Authentication

Projects use API keys with prefix `aid_proj_` for authentication. Agent tokens use prefix `at_` for individual agent authentication.

### Data Privacy

| Data Type | Handling |
|-----------|----------|
| API Keys | Only hashed values stored |
| User Email | Collected for account management |
| Project Data | Stored with project isolation |
| Agent Configurations | Stored with project isolation |
| Audit Logs | Stored with cryptographic integrity |
| Analytics | Opt-in only via PostHog with consent banner |

资料来源：[web/src/pages/privacy.tsx:1-60](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/privacy.tsx)

## Research and Scanner

AgentsID maintains an open research initiative:

- **137,070** MCP servers scanned
- Findings documented and publicly available
- Scanner available via `npx @agentsid/scanner`

资料来源：[web/src/pages/research.tsx:1-30](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/research.tsx)

## Deployment Architecture

```mermaid
graph TD
    subgraph "Client Side"
        A[AI Agent]
        B[MCP Server]
        C[Custom Integration]
    end
    
    subgraph "AgentsID Cloud"
        D[API Gateway]
        E[Auth Service]
        F[Rule Engine]
        G[Audit Service]
        H[Hash Chain Service]
    end
    
    subgraph "Data Layer"
        I[(PostgreSQL)]
        J[(Redis Cache)]
    end
    
    A --> D
    B --> D
    C --> D
    D --> E
    E --> F
    F --> G
    G --> H
    G --> I
    H --> I
    D --> J
```

## Summary

AgentsID provides a comprehensive identity and authorization layer for AI agents through:

1. **Multi-language SDKs** for easy integration
2. **Fine-grained permission engine** with 10+ constraint types
3. **Tamper-evident audit logging** via cryptographic hash chains
4. **Real-time dashboard** for activity monitoring
5. **MCP protocol support** for Cursor and Claude Code
6. **Opt-in analytics** respecting user privacy

The architecture prioritizes security through hash chain verification, least-privilege permissions, and cryptographically secure token management.

---

<a id='permission-system'></a>

## Deny-First Permission System

### 相关页面

相关主题：[Token Authentication and Security](#token-authentication), [Approval Gates and Webhooks](#approval-workflows)

<details>
<summary>Related Source Files</summary>

以下源码文件用于生成本页说明：

- [web/src/pages/spec.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/spec.tsx)
- [web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)
- [web/src/pages/guides.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/guides.tsx)
- [sdk-python/README.md](https://github.com/AgentsID-dev/agentsid/blob/main/sdk-python/README.md)
- [sdk-typescript/README.md](https://github.com/AgentsID-dev/agentsid/blob/main/sdk-typescript/README.md)
- [sdk-ruby/README.md](https://github.com/AgentsID-dev/agentsid/blob/main/sdk-ruby/README.md)
- [sdk-java/src/main/java/dev/agentsid/AgentsID.java](https://github.com/AgentsID-dev/agentsid/blob/main/sdk-java/src/main/java/dev/agentsid/AgentsID.java)
- [README.md](https://github.com/AgentsID-dev/agentsid/blob/main/README.md)
</details>

# Deny-First Permission System

The Deny-First Permission System is the core security mechanism in AgentsID. It implements a "deny-first" security model where every tool call is blocked by default unless explicitly allowed through permission rules. This security paradigm ensures that AI agents have zero access to tools unless deliberately permitted, preventing unintended actions and providing granular control over agent capabilities.

## Overview

The permission system provides fine-grained control over what tools an AI agent can invoke. By default, all tool access is denied, and administrators must create explicit "allow" rules to grant access. The system supports wildcards, conditions, priorities, schedules, rate limits, and approval gates to accommodate complex permission scenarios.

```mermaid
graph TD
    A[Tool Call Request] --> B{Permission Check}
    B -->|No Matching Rule| C[Default Deny]
    B -->|Matching Rule Found| D{Action = Allow?}
    D -->|Yes| E[Execute Tool]
    D -->|No| F[Deny Tool]
    E --> G[Log to Audit]
    F --> G
    C --> G
```

资料来源：[web/src/pages/spec.tsx:1-50]()

## Permission Rule Structure

A permission policy is a structured JSON object that defines an agent's permissions. Each policy contains metadata and an array of permission rules.

### Policy Format

```json
{
  "version": "1.0",
  "agentId": "agent_abc123",
  "issuedAt": "2026-03-29T00:00:00Z",
  "expiresAt": "2026-04-29T00:00:00Z",
  "rules": [ ...PermissionRule[] ]
}
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `version` | string | Yes | Policy format version |
| `agentId` | string | Yes | Unique agent identifier |
| `issuedAt` | string | Yes | ISO 8601 timestamp when policy was created |
| `expiresAt` | string | No | Expiration timestamp for the policy |
| `rules` | array | Yes | Array of PermissionRule objects |

资料来源：[web/src/pages/spec.tsx:50-65]()

### Permission Rule Components

Each rule within a policy consists of the following components:

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `tool_pattern` | string | Yes | Tool name or glob pattern (supports `*` wildcards) |
| `action` | string | Yes | `"allow"` or `"deny"` |
| `conditions` | object | No | Parameter constraints (AND logic) |
| `priority` | integer | No | Higher priority rules are evaluated first (default: 0) |
| `requires_approval` | boolean | No | Whether this action requires human approval |

资料来源：[sdk-python/README.md:1-30]()

## Tool Pattern Matching

The permission system uses glob-style patterns to match tool names. This allows administrators to grant or deny access to groups of tools efficiently.

### Pattern Syntax

| Pattern | Matches | Doesn't Match |
|---------|---------|---------------|
| `*` | Any single tool name segment | Namespaced tools |
| `**` | Any tool name, including namespaced tools | Nothing |
| `github.*` | All tools in the github namespace | Other namespaces |
| `filesystem.read_file` | Exactly one tool | Any variation |
| `!filesystem.write_*` | Negation — exclude write tools | N/A |

资料来源：[web/src/pages/spec.tsx:80-95]()

### Pattern Examples

| Pattern | Example Matches |
|---------|-----------------|
| `search_*` | search_docs, search_code, search_users |
| `*_file` | read_file, write_file, delete_file |
| `*` | Everything |
| `read_*` | read_file, read_config, read_log |

资料来源：[web/src/pages/guides.tsx:1-30]()

## Constraint Types

The permission system defines 13 distinct constraint types organized into 5 categories, providing comprehensive control over agent behavior.

### Constraint Categories

| Category | Constraint Types |
|----------|------------------|
| Access | Tool Patterns, Conditions, Data Classification, IP Allowlists |
| Time & Rate | Schedule, Rate Limits, Cooldown |
| Behavioral | Sequence Requirements, Risk Score |
| Resource | Budget Caps, Session Limits |
| Governance | Approval Gates, Chain Depth Limits |

资料来源：[web/src/pages/docs.tsx:1-50]()

### Parameter Conditions

Conditions allow restricting tool access based on parameter values. Only allow a tool when specific parameters match:

```json
{
  "tool_pattern": "read_customer",
  "action": "allow",
  "conditions": {
    "params": { "customer_id": "cust_123" }
  }
}
```

This rule means: "Allow `read_customer`, but only for customer `cust_123`."

资料来源：[web/src/pages/guides.tsx:30-50]()

## Evaluation Algorithm

The permission engine evaluates rules in a specific order, short-circuiting on the first match:

```mermaid
graph LR
    A[Tool Call] --> B[Sort Rules by Priority]
    B --> C{Higher Priority First}
    C --> D{Match Tool Pattern?}
    D -->|Yes| E{All Conditions Met?}
    E -->|Yes| F[Apply Action]
    E -->|No| G[Continue to Next Rule]
    D -->|No| G
    F --> H[Allow or Deny]
    G --> C
    C -->|No More Rules| I[Default Deny]
```

### Priority System

Rules are evaluated in priority order (highest to lowest). When a matching rule is found with all conditions satisfied, that rule's action is applied immediately.

| Priority Value | Meaning |
|----------------|---------|
| 1000 (max) | Evaluated first |
| 100-999 | High priority |
| 10-99 | Medium priority |
| 0 (default) | Low priority |

Example with priority:

```python
await aid.set_permissions("agt_abc123", [
    {"tool_pattern": "search_*", "action": "allow", "priority": 10},
    {"tool_pattern": "delete_*", "action": "deny", "priority": 20},
])
```

In this example, `delete_*` is evaluated first due to higher priority, ensuring delete operations are blocked before any general allow rules.

资料来源：[sdk-python/README.md:10-25]()

## API Endpoints

### Set Permissions

Replace all permission rules for an agent.

```
PUT /api/v1/agents/{agent_id}/permissions
```

Any existing rules are deleted and replaced with the provided set.

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `tool_pattern` | string | Yes | Tool name or wildcard pattern |
| `action` | string | No | allow or deny (defaults to allow) |
| `conditions` | object | No | Key-value constraints on tool parameters |
| `priority` | integer | No | Rule priority (0-1000) |

资料来源：[web/src/pages/docs.tsx:50-100]()

### Get Permissions

Retrieve the current permission rules for an agent.

```
GET /api/v1/agents/{agent_id}/permissions
```

Returns rules ordered by priority (highest first):

```json
{
  "agent_id": "agt_7x9k2mNpQ4rS1tUv",
  "rules": [
    {"tool_pattern": "delete_*", "action": "deny", "priority": 10},
    {"tool_pattern": "save_memory", "action": "allow", "priority": 1},
    {"tool_pattern": "search_memories", "action": "allow", "priority": 0}
  ]
}
```

资料来源：[web/src/pages/docs.tsx:100-150]()

### Check Permission

Check if an agent is allowed to call a specific tool.

```
POST /api/v1/check
```

**Request Body:**

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `agent_id` | string | Yes | Agent identifier |
| `tool` | string | Yes | Tool name to check |
| `params` | object | No | Tool parameters for condition evaluation |

**Response (allowed):**

```json
{
  "allowed": true,
  "reason": "Allowed by rule: save_memory",
  "matched_rule": {
    "tool_pattern": "save_memory",
    "action": "allow"
  }
}
```

**Response (denied):**

```json
{
  "allowed": false,
  "reason": "No matching rule -- default deny",
  "matched_rule": null
}
```

资料来源：[web/src/pages/docs.tsx:150-200]()

### Example curl Command

```bash
curl -X POST https://api.agentsid.dev/api/v1/check \
  -H "Authorization: Bearer aid_proj_xR7kM2pQ9..." \
  -H "Content-Type: application/json" \
  -d '{"agent_id": "agt_7x9k2mNpQ4rS1tUv", "tool": "delete_memory"}'
```

资料来源：[web/src/pages/docs.tsx:200-220]()

## SDK Implementation

### Python SDK

```python
from agentsid import AgentsID

aid = AgentsID(api_key="aid_proj_...")

# Set permissions
await aid.set_permissions("agt_abc123", [
    {"tool_pattern": "search_*", "action": "allow", "priority": 10},
    {"tool_pattern": "delete_*", "action": "deny", "priority": 20},
    {
        "tool_pattern": "send_email",
        "action": "allow",
        "conditions": {"recipient_domain": "company.com"},
    },
])

# Get permissions
rules = await aid.get_permissions("agt_abc123")

# Check permission
check = await aid.check_permission("agt_abc123", "delete_user", params={"user_id": "u_789"})
if not check["allowed"]:
    print(check["reason"])
```

资料来源：[sdk-python/README.md:1-50]()

### TypeScript SDK

```typescript
import { AgentsID } from '@agentsid/sdk';

const aid = new AgentsID({ apiKey: 'aid_proj_...' });

// Set permissions
await aid.setPermissions('agt_abc123', [
  { toolPattern: 'search_*', action: 'allow', priority: 10 },
  { toolPattern: 'delete_*', action: 'deny', priority: 20 },
  {
    toolPattern: 'send_email',
    action: 'allow',
    conditions: { recipient_domain: 'company.com' },
  },
]);

// Get permissions
const rules = await aid.getPermissions('agt_abc123');

// Check permission
const check = await aid.checkPermission('agt_abc123', 'delete_user', { userId: 'u_789' });
```

资料来源：[sdk-typescript/README.md:1-50]()

### Ruby SDK

```ruby
require 'agentsid'

client = AgentsID.new(api_key: 'aid_proj_...')

# Set permissions
client.set_permissions('agt_abc123', [
  { tool_pattern: 'search_*', action: 'allow', priority: 10 },
  { tool_pattern: 'delete_*', action: 'deny', priority: 20 },
  {
    tool_pattern: 'send_email',
    action: 'allow',
    conditions: { 'recipient_domain' => 'company.com' }
  }
])

# Get permissions
rules = client.get_permissions('agt_abc123')

# Check permission
check = client.check_permission('agt_abc123', 'delete_user', params: { user_id: 'u_789' })
unless check['allowed']
  puts check['reason']
end
```

资料来源：[sdk-ruby/README.md:1-50]()

### Java SDK

```java
import dev.agentsid.AgentsID;

AgentsID aid = new AgentsID("aid_proj_...");

// Set permissions
List<JSONObject> rules = new ArrayList<>();
JSONObject rule = new JSONObject();
rule.put("tool_pattern", "search_*");
rule.put("action", "allow");
rules.add(rule);

JSONObject response = aid.setPermissions("agt_abc123", rules);
```

资料来源：[sdk-java/src/main/java/dev/agentsid/AgentsID.java:1-50]()

## Common Use Cases

### Code Assistant Template

An agent that can read and search code freely, but writing files requires human approval. Execution and deployment are completely blocked.

```json
[
  { "tool_pattern": "read_file",    "action": "allow" },
  { "tool_pattern": "search_code",  "action": "allow" },
  { "tool_pattern": "list_files",   "action": "allow" },
  { "tool_pattern": "write_file",   "action": "allow", "requires_approval": true },
  { "tool_pattern": "execute_*",   "action": "deny" },
  { "tool_pattern": "deploy_*",    "action": "deny" },
  { "tool_pattern": "delete_*",    "action": "deny" }
]
```

### Result Summary

| Action | Status |
|--------|--------|
| read_file | Allowed |
| search_code | Allowed |
| list_files | Allowed |
| write_file | Requires Approval |
| execute_command, execute_script | Denied |
| deploy_staging, deploy_production | Denied |
| delete_file, delete_branch | Denied |

资料来源：[web/src/pages/guides.tsx:50-100]()

### Minimal Access Template

```json
[
  { "tool_pattern": "search_*", "action": "allow" },
  { "tool_pattern": "write_*",  "action": "deny" },
  { "tool_pattern": "delete_*", "action": "deny" },
  { "tool_pattern": "deploy_*", "action": "deny" }
]
```

资料来源：[web/src/pages/guides.tsx:100-120]()

## Advanced Features

### Approval Gates

Sensitive actions can be configured to pause for human approval. When an agent attempts to call a tool marked with `requires_approval: true`, the request is held until a human approves or denies it.

```typescript
const pending = await aid.listApprovals();
await aid.approve(approvalId, { decidedBy: 'admin@example.com' });
```

### Rate Limits

Tools can be restricted by rate limits within permission rules:

```typescript
await aid.setPermissions(agentId, [
  { toolPattern: 'deploy_*', action: 'allow',
    schedule: { hoursStart: 9, hoursEnd: 17, timezone: 'US/Pacific' },
    rateLimit: { max: 5, per: 'hour' } },
]);
```

### Schedules

Permission rules can include schedule constraints to limit when tools can be used:

| Field | Type | Description |
|-------|------|-------------|
| `hoursStart` | integer | Start hour (0-23) |
| `hoursEnd` | integer | End hour (0-23) |
| `timezone` | string | Timezone (e.g., "US/Pacific") |

资料来源：[README.md:1-50]()

## Integration with HTTP Middleware

The TypeScript SDK provides HTTP middleware for automatic permission validation:

```typescript
import { createHttpMiddleware } from '@agentsid/sdk';

const guard = createHttpMiddleware({ projectKey: 'aid_proj_...' });
// Every tool call is now validated automatically.
```

资料来源：[README.md:50-80]()

## Security Model Summary

The Deny-First Permission System provides several layers of security:

1. **Default Deny**: All tool access is blocked unless explicitly allowed
2. **Priority-Based Evaluation**: Rules are evaluated in priority order with short-circuiting
3. **Parameter Conditions**: Fine-grained control over parameter values
4. **Approval Gates**: Human oversight for sensitive operations
5. **Rate Limits**: Protection against abuse and resource exhaustion
6. **Schedule Constraints**: Time-based access restrictions

All 13 constraint types compose freely. A single permission rule can combine IP restrictions, budget caps, schedule windows, and approval gates—the engine evaluates them all in sequence and short-circuits on the first failure. This enables policies like "allow fund transfers only from the VPC, during business hours, under $1000/day, with human approval" in a single rule.

资料来源：[web/src/pages/docs.tsx:50-80]()

---

<a id='token-authentication'></a>

## Token Authentication and Security

### 相关页面

相关主题：[Deny-First Permission System](#permission-system), [Tamper-Evident Audit System](#audit-system)

<details>
<summary>Relevant Source Files</summary>

以下源码文件用于生成本页说明：

- [web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)
- [ARCHITECTURE.md](https://github.com/AgentsID-dev/agentsid/blob/main/ARCHITECTURE.md)
- [web/src/pages/terms.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/terms.tsx)
- [web/src/pages/privacy.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/privacy.tsx)
- [web/src/pages/guides.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/guides.tsx)
</details>

# Token Authentication and Security

## Overview

AgentsID provides a comprehensive token-based authentication system for AI agents. The system enables secure identity verification, permission enforcement, and audit logging for agent-to-tool interactions. Every AI agent interacting with MCP (Model Context Protocol) servers must obtain a token through the registration process, which then serves as the authentication credential for all subsequent tool calls.

The token architecture is designed around JWT-like tokens signed with HMAC-SHA256, allowing stateless validation without database calls while maintaining the ability to revoke tokens when necessary.

---

## Token Format and Structure

AgentsID tokens follow a structured format that encodes all necessary identity and authorization information:

```
aid_tok_<base64url(header.payload.signature)>
```

### Token Components

| Component | Description | Example Value |
|-----------|-------------|---------------|
| **Header** | Algorithm and token type | `{"alg": "HS256", "typ": "AID"}` |
| **Payload** | Claims containing identity data | sub, prj, dby, iat, exp, jti |
| **Signature** | HMAC-SHA256 of header + payload | Binary signature |

### Token Payload Claims

| Claim | Name | Type | Description |
|-------|------|------|-------------|
| `sub` | Subject | string | Agent ID (e.g., `agt_7x9k2mNpQ4rS1tUv`) |
| `prj` | Project | string | Project ID the agent belongs to |
| `dby` | Delegated By | string | Human user who delegated (e.g., `user_abc`) |
| `iat` | Issued At | integer | Unix timestamp when token was created |
| `exp` | Expires At | integer | Unix timestamp when token expires |
| `jti` | JWT ID | string | Unique token identifier for revocation tracking |

资料来源：[ARCHITECTURE.md](https://github.com/AgentsID-dev/agentsid/blob/main/ARCHITECTURE.md)

### Token Lifetime

Tokens support configurable lifetimes between 1 and 720 hours (30 days). When registering or refreshing a token, the `ttl_hours` parameter controls the expiration window.

```json
{
  "token": "aid_tok_eyJzdWIiOiJhZ3RfN3g5azJt...",
  "expires_at": "2024-03-26T12:00:00+00:00",
  "agent_id": "agt_7x9k2mNpQ4rS1tUv"
}
```

资料来源：[web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)

---

## Authentication Flow

The authentication process involves multiple steps that validate tokens before allowing tool access. The middleware intercepts requests from agents to MCP servers and performs a sequence of checks.

```mermaid
sequenceDiagram
    participant Agent
    participant Middleware
    participant Cache
    participant Database
    participant MCP_Server

    Agent->>Middleware: Request with Bearer token
    Middleware->>Middleware: 1. Extract token from header
    Middleware->>Middleware: 2. Validate HMAC signature
    Middleware->>Middleware: 3. Check expiry (iat/exp)
    Middleware->>Cache: 4. Check revocation (jti)
    Cache-->>Middleware: Cache miss/hit
    alt Cache miss
        Middleware->>Database: Lookup jti
        Database-->>Middleware: Revoked or valid
    end
    Middleware->>Cache: 5. Load permissions
    Cache-->>Middleware: Permission rules
    Middleware->>Middleware: 6. Match tool against rules
    Middleware->>Middleware: 7. Allow or deny
    Middleware->>Agent: Decision
    Middleware->>Audit: 8. Log async (non-blocking)
```

### Step-by-Step Validation

| Step | Action | Purpose |
|------|--------|---------|
| 1 | Extract token | Parse `Authorization: Bearer <token>` header |
| 2 | Validate signature | HMAC-SHA256 verification against project secret |
| 3 | Check expiry | Verify `exp` claim is in the future |
| 4 | Check revocation | Look up `jti` in revocation list (cached 60s) |
| 5 | Load permissions | Retrieve permission rules (cached 60s) |
| 6 | Match tool | Compare requested tool against permission patterns |
| 7 | Allow/Deny | Return authorization decision |
| 8 | Audit log | Record event asynchronously |

资料来源：[ARCHITECTURE.md](https://github.com/AgentsID-dev/agentsid/blob/main/ARCHITECTURE.md)

---

## Agent Authentication Middleware

The middleware acts as a gatekeeper between AI agents and MCP servers. It enforces the authentication and authorization decisions for every tool call.

### Middleware Workflow

```
Agent → MCP Server (with AgentsID middleware)
  Authorization: Bearer aid_tok_<token>
```

The middleware performs validation without making database calls for the critical path (signature and expiry checks). Database access is only required for revocation checks and permission loading, and these are cached for 60 seconds to minimize latency.

### Caching Strategy

| Data Type | Cache TTL | Purpose |
|-----------|-----------|---------|
| Revocation status | 60 seconds | Avoid repeated DB lookups for jti |
| Permission rules | 60 seconds | Minimize DB load for permission loading |

资料来源：[ARCHITECTURE.md](https://github.com/AgentsID-dev/agentsid/blob/main/ARCHITECTURE.md)

---

## Permission Engine

The permission engine determines whether an agent is authorized to call a specific tool. It uses a rule-based system with explicit allow and deny patterns.

### Evaluation Order

The permission engine follows a specific evaluation order to ensure consistent security decisions:

```mermaid
graph TD
    A[Tool Call Request] --> B{Any DENY rules match?}
    B -->|Yes| C[Deny - Explicit DENY wins]
    B -->|No| D{Any ALLOW rules match?}
    D -->|Yes| E[Allow - Explicit ALLOW]
    D -->|No| F[Deny - Default Deny]
```

| Priority | Rule Type | Behavior |
|----------|-----------|----------|
| 1 (highest) | Explicit DENY | Deny always wins, regardless of other rules |
| 2 | Explicit ALLOW | Allow if a rule matches |
| 3 (fallback) | Default | Deny if no rules match |

资料来源：[ARCHITECTURE.md](https://github.com/AgentsID-dev/agentsid/blob/main/ARCHITECTURE.md)

### Permission Rule Structure

```json
{
  "permissions": [
    {"tool_pattern": "search_memories", "action": "allow"},
    {"tool_pattern": "save_memory", "action": "allow"},
    {"tool_pattern": "admin_*", "action": "deny"}
  ]
}
```

### Wildcard Pattern Matching

The permission engine supports wildcard patterns using `*` to match multiple tool names:

| Pattern | Matches |
|---------|---------|
| `*` | All tools |
| `admin_*` | Any tool starting with `admin_` |
| `delete_*` | Any tool starting with `delete_` |

资料来源：[web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)

### Permission Validation Response

**Allowed Response:**
```json
{
  "allowed": true,
  "reason": "Allowed by rule: save_memory",
  "matched_rule": {
    "tool_pattern": "save_memory",
    "action": "allow"
  }
}
```

**Denied Response:**
```json
{
  "allowed": false,
  "reason": "No matching rule -- default deny",
  "matched_rule": null
}
```

资料来源：[web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)

---

## Security Features

### Threat Model and Mitigations

AgentsID implements multiple security layers to protect against common attack vectors:

| Threat | Mitigation | Implementation |
|--------|-------------|----------------|
| Token forgery | HMAC-SHA256 signature | Server-side secret verification |
| Replay after revocation | jti lookup | Cache-backed revocation check |
| Timing attacks | Constant-time comparison | `hmac.compare_digest` |
| Cross-project token use | Token `prj` claim verification | Project ID validation against API key |
| Permission escalation | Scope narrowing on delegation | Child permissions limited to parent scope |
| Sensitive data in logs | Automatic redaction | Passwords, secrets, tokens, api_key, credentials, keys |
| Error message leakage | Generic error messages | Details server-side only |
| Project creation spam | Rate limiting | 5/minute per IP |

资料来源：[web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)

### Security Headers

All API responses include security headers to protect against common web vulnerabilities:

| Header | Value | Purpose |
|--------|-------|---------|
| `Strict-Transport-Security` | `max-age=31536000; includeSubDomains` | Forces HTTPS for 1 year |
| `X-Content-Type-Options` | `nosniff` | Prevents MIME type sniffing |
| `X-Frame-Options` | `DENY` | Prevents clickjacking |
| `Cache-Control` | `no-store` | Prevents caching of tokens |

资料来源：[web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)

### API Key Storage

AgentsID never stores raw API keys. Only hashed versions are retained in the database.

> AgentsID stores API key **hashes**, never raw keys. If you lose an API key, you will need to rotate it — we cannot recover it for you.

资料来源：[web/src/pages/terms.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/terms.tsx)

### Data Classification

| Data Type | Storage Format | Purpose |
|-----------|----------------|---------|
| Raw API keys | Never stored | N/A |
| API key hashes | SHA-256 hash | Verification |
| Agent tokens | HMAC-SHA256 signed JWT | Authentication |
| Permission rules | JSON | Authorization |
| Audit logs | Protected by hash chain | Compliance |

资料来源：[web/src/pages/privacy.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/privacy.tsx)

---

## Token Delegation

AgentsID supports token delegation, allowing an agent to create subordinate agents with limited permissions.

### Delegation Constraints

| Constraint | Description |
|------------|-------------|
| Permission narrowing | Child permissions cannot exceed parent permissions |
| TTL limitation | Child tokens have shorter lifetimes than parent |
| Chain tracking | `dby` claim maintains delegation history |

### Delegation API Example

```bash
curl -X POST https://api.agentsid.dev/api/v1/agents/delegate \
  -H "Authorization: Bearer aid_proj_xR7kM2pQ9..." \
  -H "Content-Type: application/json" \
  -d '{
    "parent_agent_id": "agt_7x9k2mNpQ4rS1tUv",
    "parent_token": "aid_tok_eyJzdWIiOi...",
    "child_name": "sub-researcher",
    "child_permissions": ["search_memories"],
    "ttl_hours": 12
  }'
```

### Delegation Error Responses

| Code | Reason |
|------|--------|
| `401` | Invalid or missing API key |
| `403` | Permission scope violation — child permissions exceed parent's scope |
| `404` | Parent agent not found |

资料来源：[web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)

---

## Audit Logging

Every tool call is logged to the audit trail for compliance and security monitoring.

### Audit Log Contents

Audit logs capture:
- Tool call records
- Allow/deny decisions
- Timestamps
- Agent identity
- Request parameters (redacted sensitive fields)

### Hash Chain Integrity

> Audit logs are protected by a tamper-evident hash chain. This means we can detect if any log entry has been altered after the fact.

```json
{
  "verified": false,
  "entries_checked": 1523,
  "broken_at_id": 42,
  "message": "Integrity chain broken at entry 42 -- possible tampering"
}
```

### Verification Endpoint

```bash
curl "https://api.agentsid.dev/api/v1/audit/verify" \
  -H "Authorization: Bearer aid_proj_xR7kM2pQ9..."
```

资料来源：[web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)

### Data Retention by Plan

| Plan | Retention |
|------|-----------|
| Free | 7 days |
| Paid | Plan-specific |

> If you downgrade from a paid plan to Free, your audit logs will be trimmed to the Free tier retention window (7 days) within 30 days of the plan change.

资料来源：[web/src/pages/terms.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/terms.tsx)

---

## API Endpoints

### Token Management Endpoints

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/api/v1/agents/register` | POST | Register new agent and issue token |
| `/api/v1/agents/{agent_id}/refresh` | POST | Issue new token, revoke all previous |
| `/api/v1/agents/{agent_id}` | DELETE | Revoke agent and all tokens |
| `/api/v1/agents/delegate` | POST | Create delegated agent token |

### Validation Endpoints

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/api/v1/validate` | POST | Validate token and check permissions |
| `/api/v1/check` | POST | Check if tool call is allowed |

### Validate Endpoint

```bash
curl -X POST https://api.agentsid.dev/api/v1/validate \
  -H "Authorization: Bearer aid_proj_xR7kM2pQ9..." \
  -H "Content-Type: application/json" \
  -d '{
    "token": "aid_tok_eyJzdWIiOiJhZ3RfN3g5azJt...",
    "tool": "save_memory",
    "params": {"category": "note"}
  }'
```

### Validation Response (Valid Token)

```json
{
  "valid": true,
  "agent_id": "agt_7x9k2mNpQ4rS1tUv",
  "project_id": "proj_xR7kM2pQ9...",
  "expires_at": 1711411200,
  "permission": {
    "allowed": true,
    "reason": "Allowed by rule: save_memory",
    "matched_rule": {"tool_pattern": "save_memory", "action": "allow"}
  }
}
```

### Validation Response (Invalid Token)

```json
{
  "valid": false,
  "reason": "Token validation failed"
}
```

> **Note:** The same error message is returned for expired tokens, invalid signatures, revoked tokens, and project mismatches to prevent information leakage.

资料来源：[web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)

---

## Token Lifecycle Management

```mermaid
stateDiagram-v2
    [*] --> Registered: Agent Registration
    Registered --> Active: Token Issued
    Active --> Expired: TTL Reached
    Active --> Revoked: Manual Revocation
    Active --> Refreshed: Token Refresh
    Expired --> [*]: Cleanup
    Revoked --> [*]: Cleanup
    Refreshed --> Active: New Token Issued
    Refreshed --> Revoked: Old Tokens Revoked
```

### Token Refresh Behavior

When a token is refreshed:
1. All previous tokens for the agent are immediately revoked
2. A new token with fresh `iat` and `exp` claims is issued
3. The old `jti` values are added to the revocation list

### Agent Update Behavior

Updating an agent's name or metadata **does not affect** tokens or permissions.

| Field | Update Effect |
|-------|---------------|
| `name` | No effect on tokens |
| `metadata` | No effect on tokens |
| Permission rules | Immediately effective (cached 60s) |

资料来源：[web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)

---

## Quick Start: Registering an Agent

```bash
curl -X POST https://agentsid.dev/api/v1/agents/register \
  -H "Authorization: Bearer YOUR_PROJECT_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "claude-notes-agent",
    "permissions": [
      {"tool_pattern": "search_notes", "action": "allow"},
      {"tool_pattern": "save_note", "action": "allow"},
      {"tool_pattern": "list_notes", "action": "allow"},
      {"tool_pattern": "delete_note", "action": "deny"},
      {"tool_pattern": "admin_*", "action": "deny"}
    ]
  }'
```

The response includes an `agent_token` which serves as the authentication credential for the agent.

资料来源：[web/src/pages/guides.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/guides.tsx)

---

## Summary

AgentsID provides a robust token authentication system with the following key characteristics:

- **Stateless Validation**: HMAC-SHA256 signatures enable verification without database calls
- **Flexible Permissions**: Pattern-based rules with wildcard support and explicit deny precedence
- **Revocation Support**: Unique token IDs (jti) enable revocation tracking with cached lookups
- **Audit Trail**: Hash-chain protected logs for compliance and security monitoring
- **Delegation**: Hierarchical agent relationships with permission narrowing
- **Security Hardening**: Timing-safe comparisons, sensitive data redaction, and comprehensive security headers

---

<a id='audit-system'></a>

## Tamper-Evident Audit System

### 相关页面

相关主题：[Token Authentication and Security](#token-authentication), [Approval Gates and Webhooks](#approval-workflows)

<details>
<summary>Relevant Source Files</summary>

以下源码文件用于生成本页说明：

- [web/src/pages/spec.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/spec.tsx)
- [web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)
- [web/src/pages/privacy.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/privacy.tsx)
- [web/src/pages/guides.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/guides.tsx)
- [web/src/components/dashboard/AuditFeed.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/components/dashboard/AuditFeed.tsx)
- [web/src/components/dashboard/AgentDetail.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/components/dashboard/AgentDetail.tsx)
- [PRODUCT.md](https://github.com/AgentsID-dev/agentsid/blob/main/PRODUCT.md)
</details>

# Tamper-Evident Audit System

The Tamper-Evident Audit System is a core security feature of AgentsID that provides cryptographically-linked, append-only logging of all agent tool calls. Every evaluation decision—whether allowed or denied—is permanently recorded with integrity guarantees that make tampering mathematically detectable.

## Overview

The audit system operates as a **hash-chained append-only ledger**. Each log entry is cryptographically linked to the previous entry via SHA-256 hashing, creating an immutable chain that proves exactly what happened, when, and under whose authority. 资料来源：[web/src/pages/spec.tsx:1-50]()

### Design Principles

| Principle | Description |
|-----------|-------------|
| **Deny-first** | Absent a matching allow rule, all tool calls are denied |
| **Tamper-evident** | Hash chain makes any modification mathematically detectable |
| **Auditable** | Every evaluation decision is logged with cryptographic integrity |
| **Portable** | The spec is a JSON schema, not a platform dependency |

资料来源：[web/src/pages/spec.tsx:50-70]()

## Audit Entry Schema

Each audit log entry captures a complete record of a tool call evaluation. The schema follows a standardized format that ensures consistency across all logged events.

```json
{
  "entryId": "entry_abc123",
  "timestamp": "2026-03-29T12:34:56.789Z",
  "agentId": "agent_def456",
  "delegationId": "del_xyz789",
  "tool": "github.push_files",
  "parameters": { "owner": "myorg", "repo": "myrepo", "branch": "main" },
  "decision": "allow",
  "matchedRule": 2,
  "constraintsEvaluated": ["rateLimit", "schedule"],
  "durationMs": 3,
  "prevEntryHash": "sha256:e3b0c44298fc1c149afb...",
  "entryHash": "sha256:a665a45920422f9d417e..."
}
```

资料来源：[web/src/pages/spec.tsx:70-90]()

### Field Descriptions

| Field | Type | Description |
|-------|------|-------------|
| `entryId` | string | Unique identifier for the audit entry |
| `timestamp` | ISO 8601 | When the evaluation occurred |
| `agentId` | string | Which agent made the tool call |
| `delegationId` | string | Delegation chain reference |
| `tool` | string | The tool being evaluated (e.g., `github.push_files`) |
| `parameters` | object | What data was sent to the tool |
| `decision` | string | `allow` or `deny` |
| `matchedRule` | number | Index of the policy rule that matched |
| `constraintsEvaluated` | array | List of constraints checked (rateLimit, schedule) |
| `durationMs` | number | Evaluation time in milliseconds |
| `prevEntryHash` | string | SHA-256 hash of the previous entry |
| `entryHash` | string | SHA-256 hash of this entry (with entryHash set to null) |

资料来源：[web/src/pages/guides.tsx:100-130]()

## Hash Chain Integrity

The foundation of tamper-evidence is the cryptographic hash chain that links all audit entries together. This mechanism ensures data integrity without requiring a centralized trusted authority.

### Hash Calculation

```javascript
entryHash = SHA-256(canonicalize(entry with entryHash=null))
// First entry uses prevEntryHash: "genesis"
```

资料来源：[web/src/pages/spec.tsx:90-95]()

### Verification Algorithm

```javascript
function verifyChain(entries: AuditEntry[]): boolean {
  for (let i = 1; i < entries.length; i++) {
    const prev = entries[i - 1]
    // Verify prevEntryHash matches previous entry's entryHash
    // Verify canonicalized hash matches stored entryHash
  }
}
```

资料来源：[web/src/pages/spec.tsx:95-105]()

### Integrity Verification Response

**Chain Intact (200 OK):**
```json
{
  "verified": true,
  "entries_checked": 1523,
  "message": "All entries verified -- chain intact"
}
```

**Chain Broken (200 OK):**
```json
{
  "verified": false,
  "entries_checked": 1523,
  "broken_at_id": 42,
  "message": "Integrity chain broken at entry 42 -- possible tampering"
}
```

资料来源：[web/src/pages/docs.tsx:1-50]()

## Architecture

```mermaid
graph TD
    A[Agent Tool Call] --> B[Policy Evaluator]
    B --> C{Audit Entry Created}
    C --> D[SHA-256 Hash Calculation]
    D --> E[Append to Chain]
    E --> F[prevEntryHash set to previous entryHash]
    F --> G[Audit Log Stored]
    G --> H[Dashboard Display]
    
    I[Verification Request] --> J[Traverse Chain]
    J --> K{Hash Match?}
    K -->|Yes| L[Continue]
    K -->|No| M[Flag Tampering]
    
    style M fill:#ffcccc
    style G fill:#ccffcc
```

## Audit API Methods

The AgentsID SDK provides three primary methods for interacting with the audit system.

### Method Reference

| Method | Parameters | Returns | Description |
|--------|------------|---------|-------------|
| `getAuditLog` | `agentId?`, `tool?`, `action?`, `since?`, `limit?`, `offset?` | `{ entries[], total, limit, offset }` | Query audit log with filters |
| `getAuditStats` | `days?` | `{ totalEvents, byAction, byTool, denyRatePct }` | Aggregate statistics |
| `verifyAuditChain` | `(none)` | `{ verified, entriesChecked, message }` | Verify hash chain integrity |

资料来源：[web/src/pages/docs.tsx:50-80]()

### Statistics Response Format

```json
{
  "total_events": 1423,
  "events_by_action": {
    "allow": 1308,
    "deny": 115
  },
  "events_by_tool": {
    "save_memory": 800,
    "search_memories": 500,
    "delete_memory": 123,
    "list_categories": 100
  },
  "deny_rate_pct": 8.1
}
```

资料来源：[web/src/pages/docs.tsx:80-120]()

## Audit Feed Dashboard

The dashboard provides a real-time audit feed that displays events as they happen. The interface includes filtering capabilities and visual indicators for allowed versus denied actions.

### Visual Design

The audit feed uses color coding to distinguish between allowed and denied events:

- **Allowed actions**: Green background tint (`bg-green-500/5` → `bg-green-500/10` on hover)
- **Denied actions**: Red background tint (`bg-red-500/5` → `bg-red-500/10` on hover)

```typescript
className={`cursor-pointer border-b border-border transition-colors ${
  isAllow
    ? "bg-green-500/5 hover:bg-green-500/10"
    : "bg-red-500/5 hover:bg-red-500/10"
} ${isNew ? "animate-in slide-in-from-top-2 fade-in duration-400" : ""}`}
```

资料来源：[web/src/components/dashboard/AuditFeed.tsx:1-50]()

### Filtering Capabilities

The dashboard supports filtering by:
- **Agent**: Filter by specific agent ID
- **Tool**: Filter by specific tool name
- **Result**: Filter by allowed or denied status
- **Time range**: Filter by date/time window

### Activity Timeline Component

The agent detail page includes an Activity Timeline component that displays the audit entries for a specific agent:

```tsx
<div className="bg-card border border-border rounded-2xl p-5">
  <ActivityTimeline entries={data?.audit ?? []} loading={!data} />
</div>
```

资料来源：[web/src/components/dashboard/AgentDetail.tsx:1-50]()

## Security Properties

The tamper-evident audit system provides several security guarantees:

### Encryption in Transit
All communication between clients and the AgentsID API uses TLS 1.2 or higher.

### HMAC Token Signing
Agent tokens are signed with HMAC-SHA256. The signing secret never leaves the server. Raw API keys are never stored—only their hashes.

### Tamper-Evident Logs
Each log entry is chained to the previous via a hash, making unauthorized modifications mathematically detectable.

资料来源：[web/src/pages/privacy.tsx:100-130]()

## Use Cases

### Debugging
> "The agent did something weird at 3pm." Go to the audit trail, find the 3pm entries, see exactly what tools were called and with what parameters.

### Compliance
Need to prove that your AI agent never accessed customer data it shouldn't have? The audit trail is your evidence.

### Security Review
After an incident, review all denied calls. Multiple denied calls for the same dangerous tool might indicate a prompt injection attack.

### Performance Monitoring
See which tools are called most often and how they're being used.

资料来源：[web/src/pages/guides.tsx:50-80]()

## Data Retention

| Plan | Retention Period | Notes |
|------|------------------|-------|
| Free | 7 days | Audit logs trimmed after plan downgrade |
| Pro | 30 days | Standard retention |
| Enterprise | Custom | Configurable retention policies |

When downgrading from Pro to Free, audit logs are trimmed to the 7-day window within 30 days. Users should export logs before downgrading if preservation is needed.

资料来源：[web/src/pages/privacy.tsx:1-30]()

## Reference Implementation

| Component | Package | Description |
|-----------|---------|-------------|
| Policy evaluator | `@agentsid/sdk` | Core evaluation engine (TypeScript) |
| MCP middleware | `@agentsid/sdk` | MCP protocol integration |
| Audit API | `api.agentsid.dev` | REST API for audit operations |

资料来源：[web/src/pages/spec.tsx:200-220]()

## AuditEntry Data Model

From the product specification, the core data model for audit entries:

```
AuditEntry {
  id: "aud_..."
  timestamp: ISO 8601
  agent_id: "agt_..."
  delegated_by: "user_..."      // human in the chain
  tool: "save_memory"
  action: "allow" | "deny"
  params: { ... }               // what was passed to the tool
  result: "success" | "error"
  delegation_chain: [user_abc → agt_xyz]
}
```

Queryable by: agent, user, tool, time range, action.
Exportable as JSON or CSV for compliance.

资料来源：[PRODUCT.md:1-50]()

---

<a id='backend-api'></a>

## Backend API Reference

### 相关页面

相关主题：[High-Level Architecture](#high-level-architecture)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)
- [web/src/pages/spec.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/spec.tsx)
- [web/src/pages/guides.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/guides.tsx)
- [README.md](https://github.com/AgentsID-dev/agentsid/blob/main/README.md)
- [web/src/pages/privacy.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/privacy.tsx)
- [web/src/pages/research.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/research.tsx)
</details>

# Backend API Reference

## Overview

The AgentsID Backend API provides a comprehensive identity, permissions, and audit system for AI agents. The API serves as the central control plane for managing agent identities, enforcing permission rules, and maintaining tamper-proof audit logs.

**Base URL:** `https://api.agentsid.dev/api/v1`

All endpoints (except project creation and health checks) require a project API key in the `Authorization` header:

```
Authorization: Bearer aid_proj_<your_project_key>
```

## Authentication

### Project API Key

Every project is assigned a unique API key during initialization. This key authenticates the project owner and grants access to all project resources including agents, permissions, and audit logs.

**Key Format:** `aid_proj_` prefix followed by a 16+ character alphanumeric string

**Example:**
```bash
curl https://api.agentsid.dev/api/v1/audit/usage \
  -H "Authorization: Bearer aid_proj_xR7kM2pQ9..."
```

### Agent Tokens

Agent tokens are short-lived credentials issued to individual agents. Each agent receives a token upon registration with an optional TTL (time-to-live):

```json
{
  "agent": "agt_7x9k2mNpQ4rS1tUv",
  "token": "aid_tok_...",
  "tokenId": "tok_abc123",
  "expiresAt": "2026-03-26 14:30:00+00:00"
}
```

资料来源：[web/src/pages/guides.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/guides.tsx)

## API Endpoints

### Projects

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/api/v1/projects` | POST | Create a new project |
| `/api/v1/projects/{project_id}` | GET | Get project details |
| `/api/v1/projects/{project_id}` | PATCH | Update project settings |

资料来源：[web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)

### Agents

#### Register Agent

```
POST /api/v1/agents/register
```

Creates a new agent and issues its first authentication token.

**Request Body:**
```json
{
  "name": "research-assistant",
  "onBehalfOf": "user_abc",
  "permissions": ["search_memories", "save_memory"],
  "ttlHours": 24,
  "metadata": {
    "framework": "langchain"
  }
}
```

**Response:**
```json
{
  "id": "agt_7x9k2mNpQ4rS1tUv",
  "name": "research-assistant",
  "project_id": "proj_a1b2c3d4e5f6",
  "created_by": "user_abc",
  "status": "active",
  "expires_at": "2026-03-26 14:30:00+00:00",
  "metadata": {"framework": "langchain"},
  "created_at": "2026-03-25 14:30:00+00:00",
  "revoked_at": null
}
```

#### List Agents

```
GET /api/v1/agents/?status=active&limit=10
```

Returns a paginated list of agents within the project.

**Query Parameters:**
| Parameter | Type | Description |
|-----------|------|-------------|
| `status` | string | Filter by status: `active`, `revoked` |
| `limit` | integer | Maximum results (default: 10) |

#### Get Agent

```
GET /api/v1/agents/{agent_id}
```

Retrieves details for a specific agent.

**Response Codes:**
| Code | Reason |
|------|--------|
| `200 OK` | Agent found |
| `401 Unauthorized` | Invalid or missing API key |
| `404 Not Found` | Agent not found or does not belong to this project |

#### Update Agent

```
PATCH /api/v1/agents/{agent_id}
```

Updates an agent's name or metadata. Does not affect tokens or permissions.

**Request Body:**
```json
{
  "name": "new-agent-name",
  "metadata": {
    "version": "2.0"
  }
}
```

资料来源：[web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)

### Permissions

#### Check Permission

```
POST /api/v1/check
```

Validates whether an agent is permitted to execute a specific tool. This is the core enforcement endpoint.

**Request Body:**
```json
{
  "agent_id": "agt_7x9k2mNpQ4rS1tUv",
  "tool": "delete_memory"
}
```

**Response (Allowed):**
```json
{
  "allowed": true,
  "reason": "Allowed by rule: save_memory",
  "matched_rule": {
    "tool_pattern": "save_memory",
    "action": "allow"
  }
}
```

**Response (Denied):**
```json
{
  "allowed": false,
  "reason": "No matching rule -- default deny",
  "matched_rule": null
}
```

**curl Example:**
```bash
curl -X POST https://api.agentsid.dev/api/v1/check \
  -H "Authorization: Bearer aid_proj_xR7kM2pQ9..." \
  -H "Content-Type: application/json" \
  -d '{"agent_id": "agt_7x9k2mNpQ4rS1tUv", "tool": "delete_memory"}'
```

#### Permission Rule Structure

```json
{
  "tool_pattern": "github.push_files",
  "action": "allow",
  "constraints": [
    { "type": "rateLimit", "max": 10, "windowSeconds": 3600 }
  ]
}
```

**Tool Pattern Matching:**
| Pattern | Description |
|---------|-------------|
| `*` | Match all tools |
| `github.*` | Match all GitHub-related tools |
| `save_memory` | Exact match |

资料来源：[web/src/pages/spec.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/spec.tsx)

### Validation

#### Validate Tool Parameters

```
POST /api/v1/validate
```

Validates parameters for a specific tool against defined schemas.

### Audit

#### Verify Integrity Chain

```
GET /api/v1/audit/verify
```

Verifies the cryptographic integrity of the audit log chain. Each entry contains a SHA-256 hash linking to the previous entry, creating a tamper-evident chain.

**Response (Chain Valid):**
```json
{
  "verified": true,
  "entries_checked": 1523,
  "message": "Integrity chain verified"
}
```

**Response (Chain Broken):**
```json
{
  "verified": false,
  "entries_checked": 1523,
  "broken_at_id": 42,
  "message": "Integrity chain broken at entry 42 -- possible tampering"
}
```

#### Get Usage Statistics

```
GET /api/v1/audit/usage
```

Returns current usage statistics and plan limits for the authenticated project.

**Response:**
```json
{
  "events_this_month": 1200,
  "events_limit": 10000,
  "agents_active": 5,
  "agents_limit": 25,
  "plan": "free"
}
```

## Audit Log Format

### Entry Schema

```json
{
  "entryId": "entry_abc123",
  "timestamp": "2026-03-29T12:34:56.789Z",
  "agentId": "agent_def456",
  "delegationId": "del_xyz789",
  "tool": "github.push_files",
  "parameters": {
    "owner": "myorg",
    "repo": "myrepo",
    "branch": "main"
  },
  "decision": "allow",
  "matchedRule": 2,
  "constraintsEvaluated": ["rateLimit", "schedule"],
  "durationMs": 3,
  "prevEntryHash": "sha256:e3b0c44298fc1c149afb...",
  "entryHash": "sha256:a665a45920422f9d417e..."
}
```

### Hash Chain Integrity

The system uses SHA-256 cryptographic hashing to create a tamper-evident audit trail:

```javascript
entryHash = SHA-256(canonicalize(entry with entryHash=null))
// First entry uses prevEntryHash: "genesis"
```

**Verification Algorithm:**
```javascript
function verifyChain(entries: AuditEntry[]): boolean {
  for (let i = 1; i < entries.length; i++) {
    const prev = entries[i - 1]
    const expected = SHA-256(canonicalize(entries[i].with(prevEntryHash = prev.entryHash)))
    if (entries[i].entryHash !== expected) {
      return false
    }
  }
  return true
}
```

资料来源：[web/src/pages/spec.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/spec.tsx)

## Constraint Types

Constraints attach runtime conditions to rules beyond simple parameter validation.

| Constraint | Purpose |
|------------|---------|
| `schedule` | Restrict execution to specific days/hours |
| `rateLimit` | Limit requests within a time window |
| `budget` | Cap monetary spend |
| `sequence` | Require or forbid tool sequences |
| `sessionLimit` | Limit concurrent sessions |
| `riskScore` | Block high-risk operations |
| `ipAllowlist` | Restrict to specific IP ranges |
| `chainDepth` | Limit agent delegation depth |
| `cooldown` | Enforce minimum time between calls |
| `anomaly` | Detect unusual behavior patterns |

### Schedule Constraint

```json
{
  "type": "schedule",
  "daysOfWeek": [1, 2, 3, 4, 5],
  "hoursUTC": [8, 17],
  "timezone": "America/New_York"
}
```

### Rate Limit Constraint

```json
{
  "type": "rateLimit",
  "max": 100,
  "windowSeconds": 3600,
  "scope": "agent"
}
```

| Scope | Description |
|-------|-------------|
| `agent` | Counter is per agent instance |
| `principal` | Counter shared across all agents |

### Budget Constraint

```json
{
  "type": "budget",
  "currency": "usd",
  "max": 10.00,
  "windowSeconds": 86400
}
```

### Sequence Constraint

```json
{
  "type": "sequence",
  "requires": ["filesystem.read_file"],
  "forbids": ["github.push_files"]
}
```

### Session Limit Constraint

```json
{
  "type": "sessionLimit",
  "max": 5
}
```

### Risk Score Constraint

```json
{
  "type": "riskScore",
  "maxScore": 0.7
}
```

### IP Allowlist Constraint

```json
{
  "type": "ipAllowlist",
  "cidrs": ["10.0.0.0/8", "192.168.1.0/24"]
}
```

### Chain Depth Constraint

```json
{
  "type": "chainDepth",
  "max": 2
}
```

### Cooldown Constraint

```json
{
  "type": "cooldown",
  "seconds": 300
}
```

资料来源：[web/src/pages/spec.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/spec.tsx)

## SDK Reference

The AgentsID SDK provides programmatic access to the API in multiple languages.

### Available SDKs

| Package | Registry | Command |
|---------|----------|---------|
| JavaScript/TypeScript | npm | `npm install @agentsid/sdk` |
| Python | PyPI | `pip install agentsid` |
| Ruby | RubyGems | `gem install agentsid` |

### Agent Methods

| Method | Parameters | Returns | Description |
|--------|------------|---------|-------------|
| `registerAgent` | `name, onBehalfOf, permissions?, ttlHours?, metadata?` | `{ agent, token, tokenId, expiresAt }` | Create a new agent and issue its first token |
| `getAgent` | `agentId` | `Agent` | Get agent details by ID |
| `listAgents` | `status?, limit?` | `Agent[]` | List agents, optionally filtered by status |
| `updateAgent` | `agentId, name?, metadata?` | `Agent` | Update agent name or metadata |
| `refreshToken` | `agentId, ttlHours?` | `{ token, tokenId, expiresAt }` | Issue new token, revoke all previous |

### SDK Initialization

```javascript
import AgentsID from '@agentsid/sdk'

const client = new AgentsID({
  projectKey: 'aid_proj_xR7kM2pQ9...',
  agentToken: 'aid_tok_...'
})
```

资料来源：[web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)

## CLI Reference

### Initialization

```bash
npx agentsid init "My Production App"
```

Creates a new project and receives the API key.

**Output:**
```
Creating project "My Production App"...
Project created successfully!

  Project ID:  proj_a1b2c3d4e5f6
  API Key:     aid_proj_xR7kM2pQ9...
  Plan:        free

  Store your API key securely. It will not be shown again.
```

### Register Agent

```bash
npx agentsid register-agent \
  --name "research-assistant" \
  --on-behalf-of "user_abc" \
  --permissions "search_memories,save_memory" \
  --ttl 24
```

**Output:**
```
Agent registered!

  Agent ID:   agt_7x9k2mNpQ4rS1tUv
  Token:      aid_tok_...
  Expires:    2026-03-26 14:30:00+00:00
```

## Architecture Overview

```mermaid
graph TD
    A[AI Agent] -->|1. Request Tool Call| B[AgentsID SDK]
    B -->|2. Check Permission| C[AgentsID API]
    C -->|3. Evaluate Rules| D[Permission Engine]
    D -->|4. Query| E[(Database)]
    E -->|5. Rule Match| D
    D -->|6. Decision| C
    C -->|7. Allow/Deny| B
    B -->|8. Execute or Block| A
    C -->|9. Log Event| F[Audit Log]
    F -->|10. Hash Chain| G[Integrity Verification]
```

## Rate Limits and Quotas

| Plan | Events/Month | Agents | Features |
|------|--------------|--------|----------|
| Free | 10,000 | 25 | Core permissions, basic audit |
| Pro | 100,000 | 100 | Advanced constraints, SSO |
| Enterprise | Unlimited | Unlimited | Custom SLAs, dedicated support |

资料来源：[web/src/pages/privacy.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/privacy.tsx)

## Error Handling

| HTTP Code | Meaning | Common Causes |
|-----------|---------|---------------|
| `400 Bad Request` | Invalid request body | Missing required fields, malformed JSON |
| `401 Unauthorized` | Authentication failed | Invalid or expired API key |
| `403 Forbidden` | Permission denied | Agent lacks required permissions |
| `404 Not Found` | Resource not found | Invalid agent ID or project ID |
| `429 Too Many Requests` | Rate limit exceeded | Too many requests within time window |
| `500 Internal Server Error` | Server error | System maintenance or outage |

## Security Considerations

### API Key Storage

- API keys are hashed before storage; raw keys are never persisted
- Project keys should be stored in environment variables
- Agent tokens should be rotated periodically using `refreshToken`

### Data Handling

- Raw exports of project data, agent configurations, and audit logs are available in JSON format
- PostHog analytics is opt-in only, gated behind cookie consent
- The system does not sell user data

### Audit Log Immutability

The hash chain mechanism ensures:

1. Any tampering with historical entries breaks the chain
2. Verification can be performed at any time via `/api/v1/audit/verify`
3. Genesis entry uses a fixed seed value: `"genesis"`

资料来源：[web/src/pages/privacy.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/privacy.tsx)

## Related Documentation

- [Guides and Tutorials](https://agentsid.dev/guides)
- [Full API Documentation](https://agentsid.dev/docs#api-reference)
- [Privacy Policy](https://agentsid.dev/privacy)
- [Research Papers](https://agentsid.dev/research)

---

<a id='approval-workflows'></a>

## Approval Gates and Webhooks

### 相关页面

相关主题：[Deny-First Permission System](#permission-system), [Tamper-Evident Audit System](#audit-system)

<details>
<summary>Related Source Files</summary>

以下源码文件用于生成本页说明：

- [server/src/services/approval.py](https://github.com/AgentsID-dev/agentsid/blob/main/server/src/services/approval.py)
- [server/src/api/approvals.py](https://github.com/AgentsID-dev/agentsid/blob/main/server/src/api/approvals.py)
- [server/src/api/webhooks.py](https://github.com/AgentsID-dev/agentsid/blob/main/server/src/api/webhooks.py)
- [server/src/services/webhook.py](https://github.com/AgentsID-dev/agentsid/blob/main/server/src/services/webhook.py)
- [server/src/services/notifications.py](https://github.com/AgentsID-dev/agentsid/blob/main/server/src/services/notifications.py)
</details>

# Approval Gates and Webhooks

AgentsID provides two complementary mechanisms for controlling and monitoring AI agent behavior: **Approval Gates** and **Webhooks**. Together, they enable organizations to implement human-in-the-loop oversight for sensitive operations while maintaining real-time visibility into agent activities through event-driven notifications.

## Overview

Approval Gates pause agent tool executions and require explicit human authorization before proceeding. This creates a checkpoint system where certain actions cannot complete without human review.

Webhooks deliver real-time event notifications to your systems when significant events occur—including when approvals are requested, when decisions are made, and when policy violations or rate limits are encountered.

资料来源：[web/src/pages/docs.tsx:1-100]()

## Approval Gates

### Purpose and Scope

Approval Gates provide human-in-the-loop control over agent actions. When an agent attempts to execute a tool that matches a permission rule with `requires_approval: true`, the system halts execution and creates a pending approval record.

The approval mechanism supports:

- **Tool-specific gating**: Require approval only for specific dangerous operations (file writes, deletions, deployments)
- **Universal gating**: Require approval for all tool calls (maximum oversight)
- **Conditional gating**: Combine with other permission constraints (schedule, rate limits, risk scores)
- **Time-boxed decisions**: Approvers receive notifications and must decide within acceptable timeframes

资料来源：[web/src/pages/guides.tsx:1-50]()

### How Approval Gates Work

```mermaid
sequenceDiagram
    participant Agent
    participant AgentsID_API
    participant ApprovalService
    participant NotificationService
    participant Human
    participant Dashboard

    Agent->>AgentsID_API: Tool call (e.g., delete_file)
    AgentsID_API->>ApprovalService: Validate against permission rules
    ApprovalService-->>AgentsID_API: requires_approval: true
    AgentsID_API->>ApprovalService: Create pending approval
    ApprovalService-->>AgentsID_API: approval_id
    AgentsID_API-->>Agent: 202 Accepted (pending)
    NotificationService->>Human: Email/webhook notification
    Human->>Dashboard: Review approval request
    Human->>Dashboard: Approve or reject
    Dashboard->>ApprovalService: Process decision
    ApprovalService-->>Agent: Decision (allow/deny)
```

### Configuring Approval Gates

Approval gates are configured within permission rules using the `requires_approval` field:

```json
{
  "tool_pattern": "deploy_production",
  "action": "allow",
  "requires_approval": true
}
```

#### Cautious Agent Template

For maximum oversight, all tool calls can require approval:

```json
[
  { "tool_pattern": "*", "action": "allow", "requires_approval": true }
]
```

This configuration pauses every agent action and requires human authorization before execution proceeds. The system waits indefinitely for a decision.

资料来源：[web/src/pages/guides.tsx:1-50]()

#### Selective Approval Requirements

Configure approval requirements for specific high-risk operations while allowing routine operations to proceed automatically:

```json
[
  { "tool_pattern": "read_file", "action": "allow" },
  { "tool_pattern": "search_code", "action": "allow" },
  { "tool_pattern": "list_files", "action": "allow" },
  { "tool_pattern": "write_file", "action": "allow", "requires_approval": true },
  { "tool_pattern": "execute_*", "action": "deny" },
  { "tool_pattern": "deploy_*", "action": "deny" },
  { "tool_pattern": "delete_*", "action": "deny" }
]
```

资料来源：[web/src/pages/guides.tsx:50-100]()

### Approval API Endpoints

#### List Pending Approvals

Retrieves all pending approval requests for the authenticated project.

| Property | Value |
|----------|-------|
| Method | `GET` |
| Path | `/api/v1/approvals/` |

**Response:**

```json
[
  {
    "id": 1,
    "agent_id": "agt_7x9k2mNpQ4rS1tUv",
    "tool": "delete_user",
    "params": { "user_id": "usr_123" },
    "status": "pending",
    "requested_at": "2026-03-25 14:30:00+00:00"
  }
]
```

**curl Example:**

```bash
curl "https://api.agentsid.dev/api/v1/approvals/" \
  -H "Authorization: Bearer aid_proj_xR7kM2pQ9..."
```

资料来源：[web/src/pages/docs.tsx:1-100]()

#### Get Pending Approval Count

Returns the count of pending approvals, useful for dashboard badges and polling applications.

| Property | Value |
|----------|-------|
| Method | `GET` |
| Path | `/api/v1/approvals/count` |

**Response:**

```json
{
  "pending_count": 3
}
```

**curl Example:**

```bash
curl "https://api.agentsid.dev/api/v1/approvals/count" \
  -H "Authorization: Bearer aid_proj_xR7kM2pQ9..."
```

资料来源：[web/src/pages/docs.tsx:100-200]()

#### Approve a Pending Action

Grants authorization for a previously pending tool call.

| Property | Value |
|----------|-------|
| Method | `POST` |
| Path | `/api/v1/approvals/{id}/approve` |

**Request Body:**

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `decided_by` | string | Yes | Identifier of the human approver |
| `reason` | string | No | Optional reason for the decision |

**Example Request Body:**

```json
{
  "decided_by": "admin@example.com",
  "reason": "Verified with user"
}
```

**curl Example:**

```bash
curl -X POST "https://api.agentsid.dev/api/v1/approvals/1/approve" \
  -H "Authorization: Bearer aid_proj_xR7kM2pQ9..." \
  -H "Content-Type: application/json" \
  -d '{"decided_by": "admin@example.com"}'
```

资料来源：[web/src/pages/docs.tsx:200-300]()

#### Reject a Pending Action

Denies authorization for a pending tool call.

| Property | Value |
|----------|-------|
| Method | `POST` |
| Path | `/api/v1/approvals/{id}/reject` |

**Request Body:**

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `decided_by` | string | Yes | Identifier of the human rejecting |
| `reason` | string | No | Reason for rejection |

**curl Example:**

```bash
curl -X POST "https://api.agentsid.dev/api/v1/approvals/1/reject" \
  -H "Authorization: Bearer aid_proj_xR7kM2pQ9..." \
  -H "Content-Type: application/json" \
  -d '{"decided_by": "admin@example.com", "reason": "Not authorized"}'
```

资料来源：[web/src/pages/docs.tsx:300-400]()

### SDK Usage

The TypeScript/Python SDKs provide convenient methods for working with approvals:

```typescript
import { AgentsID } from "@agentsid/sdk"

const client = new AgentsID({ apiKey: process.env.AGENTSID_API_KEY })

// List pending approvals
const pending = await client.approvals.list();

// Approve an action
await client.approvals.approve(approvalId, { decidedBy: 'admin@example.com' });

// Reject an action
await client.approvals.reject(approvalId, { decidedBy: 'admin@example.com', reason: 'Security policy violation' });
```

资料来源：[README.md:1-100]()

## Webhooks

### Purpose and Scope

Webhooks enable real-time event notifications sent to your configured endpoints. When significant events occur within the AgentsID system, HTTP POST requests are delivered to your registered URLs with event payloads.

AgentsID supports **8 webhook event types**:

| Event Type | Trigger |
|------------|---------|
| `agent.created` | New agent registered |
| `agent.revoked` | Agent token revoked |
| `agent.denied` | Agent denied (permission violation) |
| `limit.approaching` | Usage approaching plan limits |
| `limit.reached` | Plan limits reached |
| `approval.requested` | New approval requested |
| `approval.decided` | Approval resolved (approved or rejected) |
| `chain.broken` | Audit chain integrity broken |

资料来源：[README.md:100-200]()

### Webhook Architecture

```mermaid
graph TD
    subgraph Events
        A[Agent Created] --> W[Webhook Service]
        B[Approval Requested] --> W
        C[Limit Reached] --> W
        D[Chain Broken] --> W
    end
    
    subgraph Delivery
        W --> S[Signature Verification]
        S --> R[Retry Queue]
        R --> E[Endpoint Delivery]
    end
    
    subgraph Consumer
        E --> P[Your Application]
    end
```

### Creating Webhook Subscriptions

| Property | Value |
|----------|-------|
| Method | `POST` |
| Path | `/api/v1/webhooks/` |

**Request Body:**

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | Yes | Webhook name (1-255 characters) |
| `url` | string | Yes | Destination URL (1-2000 characters) |
| `events` | string[] | Yes | Array of event types to subscribe to |
| `secret` | string | No | Shared secret for signature verification |

资料来源：[web/src/pages/docs.tsx:400-500]()

### Webhook Payload Structure

Each webhook delivery includes a JSON payload with event details:

```json
{
  "event": "approval.requested",
  "timestamp": "2026-03-25T14:30:00Z",
  "data": {
    "approval_id": 1,
    "agent_id": "agt_7x9k2mNpQ4rS1tUv",
    "tool": "deploy_production",
    "params": { "environment": "production" }
  }
}
```

### Webhook Security

Webhook requests include signature headers for verification:

| Header | Description |
|--------|-------------|
| `X-AgentsID-Signature` | HMAC-SHA256 signature of the payload |
| `X-AgentsID-Timestamp` | Unix timestamp of the request |

Verify signatures by computing the HMAC-SHA256 of the payload using your webhook secret and comparing it to the provided signature.

### Retry Policy

Failed webhook deliveries (non-2xx responses or timeouts) are retried with exponential backoff:

- First retry: 1 minute
- Second retry: 5 minutes
- Third retry: 30 minutes
- Final retry: 2 hours

After all retry attempts, the webhook delivery is marked as failed and no further retries occur.

## Dashboard Integration

The AgentsID dashboard provides a visual interface for managing approvals and viewing webhook configurations.

### Approvals Dashboard

From the dashboard at `agentsid.dev/dashboard`, administrators can:

- View all pending approval requests
- See tool parameters and context
- Approve or reject requests
- View approval history

资料来源：[web/src/pages/guides.tsx:1-50]()

### Permission Editor

The dashboard includes a visual permission editor that allows configuring `requires_approval` flags:

```typescript
interface PermissionRule {
  tool_pattern: string;
  action: "allow" | "deny";
  requires_approval?: boolean;
  priority?: number;
  schedule?: ScheduleConfig;
  rate_limit?: RateLimitConfig;
}
```

The editor displays active rules with their approval requirements and other constraint indicators.

资料来源：[web/src/components/dashboard/PoliciesTab.tsx:1-100]()

## Audit Trail Integration

All approval-related events are recorded in the audit trail:

| Audit Entry Field | Description |
|-------------------|-------------|
| `entryId` | Unique identifier |
| `timestamp` | ISO 8601 timestamp |
| `agentId` | Agent that triggered the event |
| `tool` | Tool that was called |
| `parameters` | Tool parameters |
| `decision` | allow, deny, or pending |
| `matchedRule` | Index of matched permission rule |
| `constraintsEvaluated` | List of constraints checked |

The audit trail maintains hash-chain integrity for compliance verification. Each entry's hash includes the previous entry's hash, creating an immutable chain.

资料来源：[web/src/pages/spec.tsx:1-100]()

## Use Cases

### Development Environment Approval

Configure automatic deployments to staging while requiring approval for production:

```json
[
  { "tool_pattern": "deploy_staging", "action": "allow" },
  { "tool_pattern": "deploy_production", "action": "allow", "requires_approval": true }
]
```

### Data Protection Workflow

Require approval for operations accessing confidential data:

```json
[
  { "tool_pattern": "read_data", "action": "allow", "data_level": ["internal"] },
  { "tool_pattern": "read_data", "action": "allow", "data_level": ["confidential", "restricted"], "requires_approval": true }
]
```

### Training Wheels Mode

For new agents or testing, require approval for everything:

```json
[
  { "tool_pattern": "*", "action": "allow", "requires_approval": true }
]
```

This allows observing agent behavior before granting full autonomy.

资料来源：[web/src/pages/guides.tsx:50-100]()

## Summary

| Feature | Description |
|---------|-------------|
| **Approval Gates** | Pause tool execution for human review before allowing or denying |
| **Webhooks** | Real-time event notifications to external systems |
| **Approval API** | Programmatic access to pending approvals and decision-making |
| **Dashboard** | Visual interface for managing approvals and viewing audit logs |
| **Integration** | SDK support for TypeScript, Python, Ruby, and Java |

---

<a id='web-dashboard'></a>

## Web Dashboard

### 相关页面

相关主题：[Backend API Reference](#backend-api)

<details>
<summary>Relevant Source Files</summary>

以下源码文件用于生成本页说明：

- [web/src/pages/dashboard.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/dashboard.tsx)
- [web/src/components/dashboard](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/components/dashboard)
- [web/src/components/dashboard/Skeletons.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/components/dashboard/Skeletons.tsx)
- [web/src/components/dashboard/AgentCards.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/components/dashboard/AgentCards.tsx)
- [web/src/components/dashboard/PermissionEditor.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/components/dashboard/PermissionEditor.tsx)
- [web/src/components/dashboard/AuditFeed.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/components/dashboard/AuditFeed.tsx)
- [web/src/pages/guides.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/guides.tsx)
- [web/src/pages/terms.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/terms.tsx)
- [web/src/pages/privacy.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/privacy.tsx)
</details>

# Web Dashboard

The Web Dashboard is the central management interface for AgentsID, providing real-time monitoring, agent configuration, and audit trail visualization for AI agent security controls.

## Overview

The dashboard serves as the command center where users:

- **Monitor agent activity** in real-time through the audit feed
- **Manage agent permissions** using pattern-based tool allow/deny rules
- **Register and configure new agents** with unique tokens
- **View security statistics** and compliance metrics
- **Access audit logs** for forensic analysis and compliance reporting

资料来源：[web/src/pages/dashboard.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/dashboard.tsx)

## Architecture

```mermaid
graph TD
    A[Browser Client] --> B[Dashboard App]
    B --> C[Supabase Backend]
    C --> D[AgentsID API]
    D --> E[Protected MCP Servers]
    
    B --> F[Sidebar Navigation]
    B --> G[Main Content Area]
    B --> H[Register Agent Modal]
    
    G --> I[Overview Tab]
    G --> J[Agents Tab]
    G --> K[Audit Feed Tab]
    
    I --> L[AuditStats]
    J --> M[AgentCards]
    J --> N[PermissionEditor]
    K --> O[AuditFeed]
```

## Dashboard Layout Structure

The dashboard uses a responsive sidebar layout with the following regions:

| Region | Description | File Reference |
|--------|-------------|----------------|
| **Sidebar** | Persistent navigation with tab switching | `web/src/pages/dashboard.tsx` |
| **Mobile Header** | Hamburger menu for mobile navigation | `web/src/pages/dashboard.tsx` |
| **Main Content** | Tab-based content area | `web/src/pages/dashboard.tsx` |
| **Error Banner** | Error display with retry capability | `web/src/pages/dashboard.tsx` |

### Responsive Behavior

- **Desktop (md+)**: Fixed 240px sidebar on the left, content area with `md:ml-60` offset
- **Mobile**: Collapsible sidebar with hamburger toggle, full-width content
- **Max Content Width**: 1400px centered with `max-w-[1400px] mx-auto`

资料来源：[web/src/pages/dashboard.tsx:1-50](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/dashboard.tsx)

## Tab Navigation

The dashboard supports the following navigation tabs:

```mermaid
stateDiagram-v2
    [*] --> Overview
    Overview --> Agents
    Agents --> AuditFeed
    AuditFeed --> Overview
    
    Overview: OverviewTab<br/>apiKey, agents, auditStats
    Agents: AgentCards + PermissionEditor
    AuditFeed: AuditFeed Component
```

### Tab States

| Tab | Component | Key Props |
|-----|-----------|-----------|
| `overview` | OverviewTab | apiKey, agents, auditStats, onTabChange, onRegisterAgent |
| `agents` | Agent management view | AgentCards, PermissionEditor |
| Audit Feed | Real-time event stream | AuditFeed with filtering |

资料来源：[web/src/pages/dashboard.tsx:100-150](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/dashboard.tsx)

## Core Components

### AgentCards

Displays registered agents with status indicators and activity metrics.

**Key Features:**
- Agent name and status display
- Activity counters (allow/deny events)
- Quick action buttons for agent management

资料来源：[web/src/components/dashboard/AgentCards.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/components/dashboard/AgentCards.tsx)

### PermissionEditor

Configures tool permission rules for each agent using pattern matching.

**Permission Rule Structure:**

```typescript
interface PermissionRule {
  tool_pattern: string;  // Glob pattern for tool names
  action: "allow" | "deny";
}
```

**Example Configuration:**

```json
[
  { "tool_pattern": "search_*",  "action": "allow" },
  { "tool_pattern": "read_*",    "action": "allow" },
  { "tool_pattern": "write_*",   "action": "deny" },
  { "tool_pattern": "delete_*",  "action": "deny" }
]
```

资料来源：[web/src/components/dashboard/PermissionEditor.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/components/dashboard/PermissionEditor.tsx)

### AuditFeed

Provides real-time visibility into agent tool calls with allow/deny decisions.

**Audit Event Properties:**
- Agent name and identifier
- Tool call name and parameters
- Decision status (allowed/denied)
- Timestamp
- Traces back to the rule commit that authorized the decision

资料来源：[web/src/components/dashboard/AuditFeed.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/components/dashboard/AuditFeed.tsx)
资料来源：[web/src/pages/landing.tsx:50-60](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/landing.tsx)

## Data Models

### AuditStats

Collected from the dashboard for real-time monitoring:

| Field | Type | Description |
|-------|------|-------------|
| totalEvents | number | Total audit events |
| allowedCount | number | Allowed tool calls |
| deniedCount | number | Denied tool calls |
| recentActivity | Event[] | Last N events for display |

资料来源：[web/src/pages/dashboard.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/dashboard.tsx)

### Agent Data

| Field | Description |
|-------|-------------|
| agentId | Unique identifier |
| name | Human-readable agent name |
| token | Agent authentication token |
| tokenId | Token reference ID |
| expiresAt | Token expiration timestamp |
| permissions | Array of PermissionRule objects |
| status | "active" \| "inactive" \| "expired" |
| metadata | Optional additional data |

资料来源：[web/src/pages/docs.tsx:SDK_INIT_TABS](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)

## Agent Registration Flow

```mermaid
sequenceDiagram
    participant User
    participant Dashboard
    participant Modal as RegisterAgentModal
    participant API as AgentsID API
    
    User->>Dashboard: Click "Register Agent"
    Dashboard->>Modal: Open registration modal
    User->>Modal: Enter agent details
    Modal->>API: registerAgent(name, permissions)
    API->>API: Generate token + tokenId
    API->>Modal: Return {agent, token, tokenId, expiresAt}
    Modal->>User: Display credentials
    User->>Dashboard: Configure MCP server with token
```

### Registration Modal

Accessible from both the Overview tab and Agents tab via the `onRegisterAgent` callback.

资料来源：[web/src/pages/dashboard.tsx:Footer](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/dashboard.tsx)

## Error Handling

### Error Banner Component

When dashboard data loading fails:

```tsx
{loadError && (
  <div className="mx-4 mt-4 md:mx-8 bg-red-500/5 border border-red-500/20 rounded-lg px-4 py-3 flex items-center justify-between">
    <span className="text-xs text-red-500">{loadError}</span>
    <button onClick={loadDashboardData} className="text-xs text-red-500 underline">
      Retry
    </button>
  </div>
)}
```

**Features:**
- Auto-dismiss on successful retry
- Manual retry button
- Responsive margin/padding

资料来源：[web/src/pages/dashboard.tsx:100-115](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/dashboard.tsx)

## Loading States

### DashboardSkeleton

Displayed during initial page load for better UX:

| Skeleton Region | Description |
|-----------------|-------------|
| Sidebar skeleton | 240px width, logo + navigation items |
| Main content skeleton | Header + tab content placeholders |
| Chart skeleton | 200px height area chart placeholder |

```tsx
function DashboardSkeleton() {
  return (
    <div className="flex min-h-screen bg-background">
      {/* Sidebar skeleton */}
      <div className="hidden md:flex flex-col w-60 border-r border-border p-4 gap-6">
        <Bone className="h-8 w-28 rounded-md" />
        <div className="flex flex-col gap-3 mt-4">
          <Bone className="h-8 w-full rounded-lg" />
          <Bone className="h-8 w-full rounded-lg" />
          <Bone className="h-8 w-full rounded-lg" />
          <Bone className="h-8 w-full rounded-lg" />
        </div>
      </div>
      {/* Main content skeleton */}
      <div className="flex-1 p-4 md:px-8 md:py-4">
        <Bone className="h-[200px] w-full rounded-lg" />
      </div>
    </div>
  );
}
```

资料来源：[web/src/components/dashboard/Skeletons.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/components/dashboard/Skeletons.tsx)

## Privacy and Data Practices

The dashboard handles the following user data:

| Data Type | Storage | Purpose |
|-----------|---------|---------|
| Email address | Supabase Auth | Account identification |
| Project names | Dashboard DB | Project organization |
| Agent names/permissions | Dashboard DB | Agent configuration |
| API key hashes | Dashboard DB | Credential verification (never raw) |
| Audit log entries | Dashboard DB | Compliance and monitoring |
| Token metadata | Dashboard DB | HMAC verification |

资料来源：[web/src/pages/privacy.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/privacy.tsx)
资料来源：[web/src/pages/terms.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/terms.tsx)

## Navigation Links

The dashboard footer provides links to related pages:

| Link | Path | Purpose |
|------|------|---------|
| Docs | `/docs` | SDK documentation |
| Guides | `/guides` | Setup tutorials |
| Dashboard | `/dashboard` | Current page |
| GitHub | External | Source code repository |
| Terms | `/terms` | Terms of service |
| Privacy | `/privacy` | Privacy policy |

资料来源：[web/src/pages/dashboard.tsx:Footer](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/dashboard.tsx)

## Usage with AI Coding Tools

The dashboard integrates with AI coding assistants through MCP (Model Context Protocol) servers:

| Platform | Setup Command | Configuration |
|----------|---------------|---------------|
| Claude Code | `claude mcp add` | Environment variables for project key and agent token |
| Codex CLI | `codex mcp add` | Similar MCP server registration |

### Testing Workflow

1. **Register agent** → Get project key and agent token
2. **Configure MCP server** → Set environment variables
3. **Test allowed calls** → Verify successful tool executions
4. **Test denied calls** → Verify blocked operations
5. **Check dashboard** → Review audit feed for all events

资料来源：[web/src/pages/guides.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/guides.tsx)

## Security Model

```mermaid
graph LR
    A[AI Agent] -->|tool_call| B[AgentsID Scanner]
    B -->|allow/deny| C[Dashboard Audit Feed]
    C -->|visualize| D[User Dashboard]
    
    B -->|block| A[AI Agent]
    B -->|allow| E[Protected MCP Server]
```

**Key Security Properties:**
- API keys are hashed before storage (never stored raw)
- Token-based authentication with configurable TTL
- Pattern-based permission rules
- Complete audit trail for all tool calls
- Compliance with data export and opt-out requirements

资料来源：[web/src/pages/privacy.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/privacy.tsx)

---

<a id='multi-language-sdks'></a>

## Multi-Language SDKs

### 相关页面

相关主题：[Quick Start Guide](#quick-start-guide), [Backend API Reference](#backend-api)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [sdk-typescript/src/client.ts](https://github.com/AgentsID-dev/agentsid/blob/main/sdk-typescript/src/client.ts)
- [sdk-typescript/src/middleware.ts](https://github.com/AgentsID-dev/agentsid/blob/main/sdk-typescript/src/middleware.ts)
- [sdk-python/agentsid/client.py](https://github.com/AgentsID-dev/agentsid/blob/main/sdk-python/agentsid/client.py)
- [sdk-python/agentsid/middleware.py](https://github.com/AgentsID-dev/agentsid/blob/main/sdk-python/agentsid/middleware.py)
- [sdk-ruby/lib/agentsid/client.rb](https://github.com/AgentsID-dev/agentsid/blob/main/sdk-ruby/lib/agentsid/client.rb)
- [sdk-java/src/main/java/dev/agentsid/AgentsID.java](https://github.com/AgentsID-dev/agentsid/blob/main/sdk-java/src/main/java/dev/agentsid/AgentsID.java)
- [sdk-java/src/main/java/dev/agentsid/MCPMiddleware.java](https://github.com/AgentsID-dev/agentsid/blob/main/sdk-java/src/main/java/dev/agentsid/MCPMiddleware.java)
</details>

# Multi-Language SDKs

AgentsID provides official Software Development Kits (SDKs) for multiple programming languages, enabling developers to integrate agent permission management, tool validation, and audit logging into their applications regardless of their preferred technology stack. Each SDK exposes a unified API surface while adapting to language-specific conventions and idioms.

## Overview

The AgentsID SDK ecosystem covers four primary languages:

| Language | Package/Registry | Primary Module |
|----------|------------------|----------------|
| TypeScript/JavaScript | `@agentsid/sdk` | `client.ts`, `middleware.ts` |
| Python | `agentsid` (PyPI) | `client.py`, `middleware.py` |
| Ruby | `agentsid` (RubyGems) | `client.rb` |
| Java | Maven Central | `AgentsID.java`, `MCPMiddleware.java` |

资料来源：[web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)

## SDK Architecture

All SDKs follow a consistent layered architecture consisting of:

1. **Client Layer** - Core API wrapper handling authentication, request serialization, and HTTP communication
2. **Middleware Layer** - Integration adapters for frameworks like MCP (Model Context Protocol) and HTTP servers
3. **Model Layer** - Typed data structures for requests, responses, and domain objects (agents, tokens, permissions)

```mermaid
graph TD
    A[Application Code] --> B[SDK Client]
    B --> C[HTTP/REST API]
    C --> D[AgentsID Backend]
    
    E[Framework Integration] --> B
    F[MCP Server] --> E
    G[HTTP Server] --> E
    
    B --> H[Response Models]
    H --> A
```

资料来源：[sdk-typescript/src/client.ts](https://github.com/AgentsID-dev/agentsid/blob/main/sdk-typescript/src/client.ts), [sdk-python/agentsid/client.py](https://github.com/AgentsID-dev/agentsid/blob/main/sdk-python/agentsid/client.py)

## Initialization

### TypeScript/JavaScript

```typescript
import { AgentsID } from '@agentsid/sdk';

const aid = new AgentsID({ 
  projectKey: 'aid_proj_YOUR_KEY' 
});
```

资料来源：[web/src/pages/guides.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/guides.tsx)

### Python

```python
from agentsid import AgentsID

aid = AgentsID(project_key="aid_proj_YOUR_KEY")
```

资料来源：[web/src/pages/guides.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/guides.tsx)

### Ruby

```ruby
require 'agentsid'

aid = AgentsID.new(project_key: 'aid_proj_YOUR_KEY')
```

资料来源：[sdk-ruby/lib/agentsid/client.rb](https://github.com/AgentsID-dev/agentsid/blob/main/sdk-ruby/lib/agentsid/client.rb)

### Java

```java
import dev.agentsid.AgentsID;

AgentsID aid = new AgentsID("aid_proj_YOUR_KEY");
```

资料来源：[sdk-java/src/main/java/dev/agentsid/AgentsID.java](https://github.com/AgentsID-dev/agentsid/blob/main/sdk-java/src/main/java/dev/agentsid/AgentsID.java)

## Agent Management

### Registering an Agent

The `registerAgent` method creates a new agent with scoped permissions and issues its first authentication token.

```mermaid
sequenceDiagram
    participant App as Application
    participant SDK as SDK Client
    participant API as AgentsID API
    
    App->>SDK: registerAgent(name, onBehalfOf, permissions)
    SDK->>API: POST /api/v1/agents
    API->>API: Create agent record
    API->>API: Generate token with JWT
    API-->>SDK: { agent, token, tokenId, expiresAt }
    SDK-->>App: Agent credentials
```

资料来源：[sdk-typescript/src/client.ts](https://github.com/AgentsID-dev/agentsid/blob/main/sdk-typescript/src/client.ts)

**Method Signature (TypeScript):**

```typescript
const { agent, token, tokenId, expiresAt } = await aid.registerAgent({
  name: 'research-bot',
  onBehalfOf: 'user_123',
  permissions: ['search_*', 'save_memory'],
});
```

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `name` | string | Yes | Human-readable agent identifier |
| `onBehalfOf` | string | Yes | Principal ID (user or system) the agent acts for |
| `permissions` | string[] | No | Permission patterns to grant (e.g., `save_memory`, `search_*`) |
| `ttlHours` | number | No | Token lifetime in hours (default varies by plan) |
| `metadata` | object | No | Arbitrary key-value pairs for organization |

资料来源：[web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)

### Agent Methods Reference

| Method | Description | Returns |
|--------|-------------|---------|
| `registerAgent()` | Create a new agent with initial token | `{ agent, token, tokenId, expiresAt }` |
| `getAgent(agentId)` | Retrieve agent details | `Agent` object |
| `listAgents(status?, limit?)` | List agents with optional filtering | `Agent[]` |
| `updateAgent(agentId, updates)` | Update agent name or metadata | `Agent` object |
| `refreshToken(agentId, ttlHours?)` | Revoke existing tokens and issue new one | `{ token, tokenId, expiresAt }` |
| `revokeAgent(agentId)` | Permanently deactivate an agent | `void` |

资料来源：[web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx), [sdk-python/agentsid/client.py](https://github.com/AgentsID-dev/agentsid/blob/main/sdk-python/agentsid/client.py)

## Permission Validation

### Checking Tool Access

The `validate` method checks whether an agent's token permits execution of a specific tool.

```typescript
const result = await aid.validate(token, 'save_memory');
console.log(result.permission.allowed); // → true
```

**Response Schema:**

```json
{
  "valid": true,
  "agent_id": "agt_7x9k2mNpQ4rS1tUv",
  "timestamp": "2026-03-25T14:30:00Z",
  "permission": {
    "allowed": true,
    "reason": "Allowed by rule: save_memory",
    "matched_rule": {
      "tool_pattern": "save_memory",
      "action": "allow"
    }
  }
}
```

资料来源：[web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)

### Deny-First Default Behavior

AgentsID employs a deny-first security model. If a tool is not explicitly listed in the agent's permission set, access is denied by default:

```json
{
  "allowed": false,
  "reason": "No matching rule -- default deny",
  "matched_rule": null
}
```

资料来源：[web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)

## Middleware Integration

### HTTP Middleware

The HTTP middleware adapter enables seamless integration with existing web frameworks.

```typescript
import { createHttpMiddleware } from '@agentsid/sdk';

const middleware = createHttpMiddleware({
  projectKey: 'aid_proj_YOUR_KEY',
  onUnauthorized: (req, res) => {
    res.status(401).json({ error: 'Invalid agent token' });
  }
});
```

资料来源：[sdk-typescript/src/middleware.ts](https://github.com/AgentsID-dev/agentsid/blob/main/sdk-typescript/src/middleware.ts)

### MCP Server Middleware

For Model Context Protocol servers, the SDK provides specialized middleware that intercepts tool calls before execution.

```mermaid
graph LR
    A[AI Tool] -->|Tool Call| B[MCP Middleware]
    B --> C{Validate with AgentsID}
    C -->|Allowed| D[Tool Handler]
    C -->|Denied| E[Error Response]
    D --> F[Execute Tool]
```

资料来源：[sdk-java/src/main/java/dev/agentsid/MCPMiddleware.java](https://github.com/AgentsID-dev/agentsid/blob/main/sdk-java/src/main/java/dev/agentsid/MCPMiddleware.java), [sdk-python/agentsid/middleware.py](https://github.com/AgentsID-dev/agentsid/blob/main/sdk-python/agentsid/middleware.py)

**Python MCP Middleware Pattern:**

```python
from agentsid.middleware import MCPMiddleware

class ProtectedNotesServer:
    def __init__(self, agentsid_client):
        self.middleware = MCPMiddleware(agentsid_client)
    
    async def handle_tool_call(self, tool_name: str, params: dict):
        # Validate before execution
        result = await self.middleware.validate(tool_name, params)
        if not result.allowed:
            raise PermissionError(f"Tool '{tool_name}' is not permitted")
        
        # Proceed with tool execution
        return await self.execute_tool(tool_name, params)
```

资料来源：[sdk-python/agentsid/middleware.py](https://github.com/AgentsID-dev/agentsid/blob/main/sdk-python/agentsid/middleware.py)

## Audit Logging

### Retrieving Audit Logs

The SDK provides access to the complete audit trail for agent activities:

```typescript
const log = await aid.getAuditLog();
console.log('Audit events:', log.entries.length);
```

**Response Schema:**

```json
{
  "entries": [
    {
      "id": 42,
      "agent_id": "agt_7x9k2mNpQ4rS1tUv",
      "action": "tool_call",
      "tool": "save_memory",
      "params": { "category": "note" },
      "decision": "allowed",
      "ip_address": "203.0.113.42",
      "user_agent": "MyApp/1.0",
      "created_at": "2026-03-25T14:30:00+00:00"
    }
  ],
  "pagination": {
    "cursor": "eyJpZCI6NDJ9",
    "has_more": true
  }
}
```

资料来源：[web/src/pages/guides.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/guides.tsx), [web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)

### Verifying Audit Integrity

The audit system supports cryptographic verification to detect tampering:

```typescript
const verification = await aid.verifyAuditLog();
if (!verification.verified) {
  console.error('Chain broken at entry:', verification.broken_at_id);
}
```

**Verification Response (intact chain):**

```json
{
  "verified": true,
  "entries_checked": 1523,
  "message": "Integrity chain verified -- all entries match their Merkle proofs"
}
```

**Verification Response (tampering detected):**

```json
{
  "verified": false,
  "entries_checked": 1523,
  "broken_at_id": 42,
  "message": "Integrity chain broken at entry 42 -- possible tampering"
}
```

资料来源：[web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)

## Delegation

AgentsID supports hierarchical agent delegation, where one agent can create sub-agents with constrained permissions:

```typescript
const delegate = await aid.delegate({
  parentAgentId: 'agt_parent',
  parentToken: 'aid_tok_...',
  childName: 'sub-researcher',
  childPermissions: ['search_memories'],
  ttlHours: 12
});
```

**Constraints:**

| Constraint Type | Parameters | Description |
|-----------------|------------|-------------|
| `rateLimit` | `max`, `windowSeconds`, `scope` | Maximum calls per time window |
| `schedule` | `daysOfWeek`, `hoursUTC`, `timezone` | Time-based access windows |

资料来源：[web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx), [web/src/pages/spec.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/spec.tsx)

## Usage Limits

The SDK exposes methods to monitor API usage against plan limits:

```typescript
const usage = await aid.getUsage();
console.log(`Events: ${usage.events_this_month}/${usage.events_limit}`);
console.log(`Agents: ${usage.agents_active}/${usage.agents_limit}`);
console.log(`Plan: ${usage.plan}`);
```

**Response Schema:**

```json
{
  "events_this_month": 1200,
  "events_limit": 10000,
  "agents_active": 5,
  "agents_limit": 25,
  "plan": "free"
}
```

资料来源：[web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)

## Error Handling

The SDK provides consistent error handling across all languages:

| HTTP Code | Condition |
|-----------|-----------|
| `401` | Invalid or missing API key |
| `403` | Permission scope violation or delegation constraint breach |
| `404` | Resource not found (agent, token, etc.) |
| `429` | Rate limit exceeded |

**Token Validation Errors:**

All token validation failures return intentionally generic messages to prevent information leakage:

```json
{
  "valid": false,
  "reason": "Token validation failed"
}
```

资料来源：[web/src/pages/docs.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/docs.tsx)

## Quick Reference

### Installation Commands

| Language | Command |
|----------|---------|
| TypeScript | `npm install @agentsid/sdk` |
| Python | `pip install agentsid` |
| Ruby | `gem install agentsid` |
| Java | Add to Maven or Gradle dependencies |

资料来源：[web/src/pages/landing.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/landing.tsx)

### Environment Variables

| Variable | Description |
|----------|-------------|
| `AGENTSID_PROJECT_KEY` | Your project API key (`aid_proj_...`) |
| `AGENTSID_AGENT_TOKEN` | Agent authentication token (`aid_tok_...`) |
| `AGENTSID_URL` | API endpoint (defaults to `https://agentsid.dev`) |

资料来源：[web/src/pages/guides.tsx](https://github.com/AgentsID-dev/agentsid/blob/main/web/src/pages/guides.tsx)

---

---

## Doramagic 踩坑日志

项目：AgentsID-dev/agentsid

摘要：发现 7 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：身份坑 - 仓库名和安装名不一致。

## 1. 身份坑 · 仓库名和安装名不一致

- 严重度：medium
- 证据强度：runtime_trace
- 发现：仓库名 `agentsid` 与安装入口 `@agentsid/sdk` 不完全一致。
- 对用户的影响：用户照着仓库名搜索包或照着包名找仓库时容易走错入口。
- 建议检查：在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。
- 复现命令：`npm install @agentsid/sdk`
- 防护动作：页面必须同时展示 repo 名和真实安装入口，避免用户搜索错包。
- 证据：identity.distribution | github_repo:1192733106 | https://github.com/AgentsID-dev/agentsid | repo=agentsid; install=@agentsid/sdk

## 2. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 建议检查：将假设转成下游验证清单。
- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。
- 证据：capability.assumptions | github_repo:1192733106 | https://github.com/AgentsID-dev/agentsid | README/documentation is current enough for a first validation pass.

## 3. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。
- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。
- 证据：evidence.maintainer_signals | github_repo:1192733106 | https://github.com/AgentsID-dev/agentsid | last_activity_observed missing

## 4. 安全/权限坑 · 下游验证发现风险项

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：下游已经要求复核，不能在页面中弱化。
- 建议检查：进入安全/权限治理复核队列。
- 防护动作：下游风险存在时必须保持 review/recommendation 降级。
- 证据：downstream_validation.risk_items | github_repo:1192733106 | https://github.com/AgentsID-dev/agentsid | no_demo; severity=medium

## 5. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 建议检查：把风险写入边界卡，并确认是否需要人工复核。
- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。
- 证据：risks.scoring_risks | github_repo:1192733106 | https://github.com/AgentsID-dev/agentsid | no_demo; severity=medium

## 6. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。
- 防护动作：issue/PR 响应未知时，必须提示维护风险。
- 证据：evidence.maintainer_signals | github_repo:1192733106 | https://github.com/AgentsID-dev/agentsid | issue_or_pr_quality=unknown

## 7. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。
- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。
- 证据：evidence.maintainer_signals | github_repo:1192733106 | https://github.com/AgentsID-dev/agentsid | release_recency=unknown

<!-- canonical_name: AgentsID-dev/agentsid; human_manual_source: deepwiki_human_wiki -->
