> ## Documentation Index
> Fetch the complete documentation index at: https://docs.promptguard.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Agent Security API

> Validate tool calls and monitor AI agent behavior

# Agent Security API

The Agent Security API protects AI agents by validating tool calls before execution and detecting anomalous behavior patterns.

**Project Scoping**: Agent profiles are scoped by project. For the Developer API, `project_id` is automatically extracted from your API key. For the Consumer API, `project_id` must be provided in the request body.

## Why Agent Security?

AI agents with tool access can be exploited to:

* **Execute dangerous commands**: Shell injection, file system manipulation
* **Escalate privileges**: Accessing restricted resources
* **Exfiltrate data**: Sending data to external endpoints
* **Behave erratically**: Unusual patterns indicating compromise

## Endpoints

### Validate Tool Call

Validate a tool call before allowing execution.

```http theme={"system"}
POST /api/v1/agent/validate-tool
```

**Request Body**

```json theme={"system"}
{
  "agent_id": "agent-123",
  "tool_name": "write_file",
  "arguments": {
    "path": "/tmp/output.txt",
    "content": "Hello world"
  },
  "session_id": "session-456"
}
```

**Note**: For Developer API, `project_id` is automatically extracted from your API key. For Consumer API, include `project_id` in the request body.

**Response (Allowed)**

```json theme={"system"}
{
  "allowed": true,
  "risk_score": 0.2,
  "risk_level": "low",
  "reason": "Tool call approved",
  "warnings": [],
  "blocked_reasons": []
}
```

**Response (Blocked)**

```json theme={"system"}
{
  "allowed": false,
  "risk_score": 0.95,
  "risk_level": "critical",
  "reason": "Dangerous command detected",
  "warnings": ["Shell injection pattern detected"],
  "blocked_reasons": [
    "Attempt to execute shell command",
    "Path traversal detected"
  ]
}
```

### Get Agent Stats

Get statistics for a specific agent.

```http theme={"system"}
GET /api/v1/agent/{agent_id}/stats
```

**Response**

```json theme={"system"}
{
  "agent_id": "agent-123",
  "total_tool_calls": 1523,
  "blocked_calls": 12,
  "avg_risk_score": 0.15,
  "active_sessions": 3,
  "anomalies_detected": 2
}
```

### Register Agent

Register a new agent identity and receive a one-time-visible credential.

```http theme={"system"}
POST /api/v1/agent/register
```

**Request Body**

```json theme={"system"}
{
  "agent_name": "billing-assistant",
  "allowed_tools": ["read_invoice", "send_summary"]
}
```

**Response**

```json theme={"system"}
{
  "agent_id": "agent-123",
  "agent_name": "billing-assistant",
  "agent_secret": "agsec_xxxxxxxx",
  "credential_prefix": "agsec_xxxx"
}
```

<Warning>
  `agent_secret` is shown only once. Store it securely — it cannot be retrieved again, only rotated.
</Warning>

### Rotate Agent Credential

Revoke the agent's current credential and issue a new one.

```http theme={"system"}
POST /api/v1/agent/{agent_id}/rotate-credential
```

**Response**

```json theme={"system"}
{
  "agent_id": "agent-123",
  "new_secret": "agsec_yyyyyyyy",
  "credential_prefix": "agsec_yyyy",
  "old_credential_revoked": true
}
```

### End Agent Session

End an agent session and clear its tracking data.

```http theme={"system"}
DELETE /api/v1/agent/{agent_id}/session/{session_id}
```

### Agent Security Health

Health check for the agent security service. Useful for readiness probes before routing validation traffic.

```http theme={"system"}
GET /api/v1/agent/health
```

### Get Managed Policy

Get the org-managed update policy for an enrolled device (used by the desktop agent to apply fleet-managed update settings).

```http theme={"system"}
GET /api/v1/agent/managed-policy
```

**Response**

```json theme={"system"}
{
  "fleet": true,
  "force_update_mode": "auto",
  "pinned_channel": "stable",
  "min_version_override": null
}
```

## SDK Usage

<Tabs>
  <Tab title="Python">
    ```python theme={"system"}
    from promptguard import PromptGuard

    pg = PromptGuard(api_key="pg_live_xxxxxxxx")

    # Validate before executing a tool
    result = pg.agent.validate_tool(
        agent_id="my-agent",
        tool_name="execute_code",
        arguments={"code": "print('hello')"}
    )

    if result["allowed"]:
        # Safe to execute
        execute_tool(tool_name, arguments)
    else:
        print(f"Blocked: {result['blocked_reasons']}")
    ```
  </Tab>

  <Tab title="Node.js">
    ```typescript theme={"system"}
    import { PromptGuard } from 'promptguard-sdk';

    const pg = new PromptGuard({ apiKey: 'pg_live_xxxxxxxx' });

    // Validate before executing a tool
    const result = await pg.agent.validateTool(
      'my-agent',
      'execute_code',
      { code: "print('hello')" }
    );

    if (result.allowed) {
      // Safe to execute
      await executeTool(toolName, args);
    } else {
      console.log(`Blocked: ${result.blocked_reasons.join(', ')}`);
    }
    ```
  </Tab>
</Tabs>

## Risk Levels

| Level      | Score Range | Action                    |
| ---------- | ----------- | ------------------------- |
| `safe`     | 0.0 - 0.2   | Allow                     |
| `low`      | 0.2 - 0.4   | Allow with logging        |
| `medium`   | 0.4 - 0.6   | May require review        |
| `high`     | 0.6 - 0.8   | Block or require approval |
| `critical` | 0.8 - 1.0   | Always block              |

## Blocked Tools (Default)

These tools are blocked by default:

* `execute_shell`, `run_command`, `bash`, `system`
* `delete_file`, `rm`, `rmdir`
* `kill_process`, `terminate`
* `send_email`, `http_post` (without approval)

## Project Isolation

Agent profiles are isolated by project. This means:

* The same `agent_id` in different projects will have separate behavioral profiles
* Profiles persist across restarts (stored in database)
* Each project maintains its own baseline for anomaly detection

**Developer API**: `project_id` is automatically extracted from your API key. Ensure your API key is associated with a project.

**Consumer API**: Include `project_id` in your request body. You must have access to the specified project.

## Best Practices

1. **Validate every tool call**: Don't skip validation for "safe" tools
2. **Use sessions**: Group related calls for better behavior analysis
3. **Review anomalies**: Investigate when `anomaly_score` is high
4. **Set up alerts**: Monitor for patterns indicating compromise
5. **Use project-scoped API keys**: Ensure your API keys are associated with projects for proper isolation
