# API Reference

This document provides comprehensive documentation for the Symbiont runtime APIs. The Symbiont project exposes two distinct API systems designed for different use cases and development stages.

## Overview

Symbiont offers two API interfaces:

1. **Runtime HTTP API** - A complete API for direct runtime interaction, agent management, and workflow execution
2. **Tool Review API (Production)** - A comprehensive, production-ready API for AI-driven tool review and signing workflows

---

## Runtime HTTP API

The Runtime HTTP API provides direct access to the Symbiont runtime for workflow execution, agent management, and system monitoring. All endpoints are fully implemented and production-ready when the `http-api` feature is enabled.

### Base URL
```
http://127.0.0.1:8080/api/v1
```

### Authentication

Agent management endpoints require Bearer token authentication. Set the `API_AUTH_TOKEN` environment variable and include the token in the Authorization header:

```
Authorization: Bearer <your-token>
```

**Protected Endpoints:**
- All `/api/v1/agents/*` endpoints require authentication
- `/api/v1/health`, `/api/v1/workflows/execute`, and `/api/v1/metrics` endpoints do not require authentication

### Available Endpoints

#### Health Check
```http
GET /api/v1/health
```

Returns the current system health status and basic runtime information.

**Response (200 OK):**
```json
{
  "status": "healthy",
  "uptime_seconds": 3600,
  "timestamp": "2024-01-15T10:30:00Z",
  "version": "1.0.0"
}
```

**Response (500 Internal Server Error):**
```json
{
  "status": "unhealthy",
  "error": "Database connection failed",
  "timestamp": "2024-01-15T10:30:00Z"
}
```

### Available Endpoints

#### Workflow Execution
```http
POST /api/v1/workflows/execute
```

Execute a workflow with specified parameters.

**Request Body:**
```json
{
  "workflow_id": "string",
  "parameters": {},
  "agent_id": "optional-agent-id"
}
```

**Response (200 OK):**
```json
{
  "result": "workflow execution result"
}
```

#### Agent Management

All agent management endpoints require authentication via the `Authorization: Bearer <token>` header.

##### List Agents
```http
GET /api/v1/agents
Authorization: Bearer <your-token>
```

Retrieve a list of all active agents in the runtime.

**Response (200 OK):**
```json
[
  "agent-id-1",
  "agent-id-2",
  "agent-id-3"
]
```

##### Get Agent Status
```http
GET /api/v1/agents/{id}/status
Authorization: Bearer <your-token>
```

Get detailed status information for a specific agent including real-time execution metrics.

**Response (200 OK):**
```json
{
  "agent_id": "uuid",
  "state": "running|ready|waiting|failed|completed|terminated",
  "last_activity": "2024-01-15T10:30:00Z",
  "scheduled_at": "2024-01-15T10:00:00Z",
  "resource_usage": {
    "memory_usage": 268435456,
    "cpu_usage": 15.5,
    "active_tasks": 1
  },
  "execution_context": {
    "execution_mode": "ephemeral|persistent|scheduled|event_driven",
    "process_id": 12345,
    "uptime": "00:15:30",
    "health_status": "healthy|unhealthy"
  }
}
```

**New Agent States:**
- `running`: Agent is actively executing with a running process
- `ready`: Agent is initialized and ready for execution
- `waiting`: Agent is queued for execution
- `failed`: Agent execution failed or health check failed
- `completed`: Agent task completed successfully
- `terminated`: Agent was gracefully or forcibly terminated

##### Create Agent
```http
POST /api/v1/agents
Authorization: Bearer <your-token>
```

Create a new agent with the provided configuration.

**Request Body:**
```json
{
  "name": "my-agent",
  "dsl": "agent definition in DSL format"
}
```

**Response (200 OK):**
```json
{
  "id": "uuid",
  "status": "created"
}
```

##### Update Agent
```http
PUT /api/v1/agents/{id}
Authorization: Bearer <your-token>
```

Update an existing agent's configuration. At least one field must be provided.

**Request Body:**
```json
{
  "name": "updated-agent-name",
  "dsl": "updated agent definition in DSL format"
}
```

**Response (200 OK):**
```json
{
  "id": "uuid",
  "status": "updated"
}
```

##### Delete Agent
```http
DELETE /api/v1/agents/{id}
Authorization: Bearer <your-token>
```

Delete an existing agent from the runtime.

**Response (200 OK):**
```json
{
  "id": "uuid",
  "status": "deleted"
}
```

##### Execute Agent
```http
POST /api/v1/agents/{id}/execute
Authorization: Bearer <your-token>
```

Trigger execution of a specific agent.

**Request Body:**
```json
{}
```

**Response (200 OK):**
```json
{
  "execution_id": "uuid",
  "status": "execution_started"
}
```

##### Get Agent Execution History
```http
GET /api/v1/agents/{id}/history
Authorization: Bearer <your-token>
```

Retrieve the execution history for a specific agent.

**Response (200 OK):**
```json
{
  "history": [
    {
      "execution_id": "uuid",
      "status": "completed",
      "timestamp": "2024-01-15T10:30:00Z"
    }
  ]
}
```

##### Agent Heartbeat
```http
POST /api/v1/agents/{id}/heartbeat
Authorization: Bearer <your-token>
```

Send a heartbeat from a running agent to update its health status.

##### Push Event to Agent
```http
POST /api/v1/agents/{id}/events
Authorization: Bearer <your-token>
```

Push an external event to a running agent for event-driven execution.

#### System Metrics
```http
GET /api/v1/metrics
```

Retrieve a comprehensive metrics snapshot covering scheduler, task manager, load balancer, and system resources.

**Response (200 OK):**
```json
{
  "timestamp": "2026-02-16T12:00:00Z",
  "scheduler": {
    "total_jobs": 12,
    "active_jobs": 8,
    "paused_jobs": 2,
    "failed_jobs": 1,
    "total_runs": 450,
    "successful_runs": 445,
    "dead_letter_count": 2
  },
  "task_manager": {
    "queued_tasks": 3,
    "running_tasks": 5,
    "completed_tasks": 1200,
    "failed_tasks": 15
  },
  "load_balancer": {
    "total_workers": 4,
    "active_workers": 3,
    "requests_per_second": 12.5
  },
  "system": {
    "cpu_usage_percent": 45.2,
    "memory_usage_bytes": 536870912,
    "memory_total_bytes": 17179869184,
    "uptime_seconds": 3600
  }
}
```

The metrics snapshot can also be exported to files (atomic JSON write) or OTLP endpoints using the runtime's `MetricsExporter` system. See the [Metrics & Telemetry](#metrics--telemetry) section below.

---

### Metrics & Telemetry

Symbiont supports exporting runtime metrics to multiple backends:

#### File Exporter

Writes metric snapshots as atomic JSON files (tempfile + rename):

```rust
use symbi_runtime::metrics::{FileMetricsExporter, MetricsExporterConfig};

let exporter = FileMetricsExporter::new("/var/lib/symbi/metrics.json");
exporter.export(&snapshot)?;
```

#### OTLP Exporter

Sends metrics to any OpenTelemetry-compatible endpoint (requires the `metrics` feature):

```rust
use symbi_runtime::metrics::{OtlpExporter, OtlpExporterConfig, OtlpProtocol};

let config = OtlpExporterConfig {
    endpoint: "http://localhost:4317".to_string(),
    protocol: OtlpProtocol::Grpc,
    ..Default::default()
};
```

#### Composite Exporter

Fan-out to multiple backends simultaneously — individual export failures are logged but don't block other exporters:

```rust
use symbi_runtime::metrics::CompositeExporter;

let composite = CompositeExporter::new(vec![
    Box::new(file_exporter),
    Box::new(otlp_exporter),
]);
```

#### Background Collection

The `MetricsCollector` runs as a background thread, periodically gathering snapshots and exporting them:

```rust
use symbi_runtime::metrics::MetricsCollector;

let collector = MetricsCollector::new(exporter, interval);
collector.start();
// ... later ...
collector.stop();
```

---

### Skill Scanning (ClawHavoc)

The `SkillScanner` inspects agent skill content for malicious patterns before loading. It ships with **40 built-in ClawHavoc defense rules** across 10 attack categories:

| Category | Count | Severity | Examples |
|----------|-------|----------|----------|
| Original defense rules | 10 | Critical/Warning | `pipe-to-shell`, `eval-with-fetch`, `rm-rf-pattern` |
| Reverse shells | 7 | Critical | bash, nc, ncat, mkfifo, python, perl, ruby |
| Credential harvesting | 6 | High | SSH keys, AWS creds, cloud config, browser cookies, keychain |
| Network exfiltration | 3 | High | DNS tunnel, `/dev/tcp`, netcat outbound |
| Process injection | 4 | Critical | ptrace, LD_PRELOAD, `/proc/mem`, gdb attach |
| Privilege escalation | 5 | High | sudo, setuid, setcap, chown root, nsenter |
| Symlink / path traversal | 2 | Medium | symlink escape, deep path traversal |
| Downloader chains | 3 | Medium | curl save, wget save, chmod exec |

See the [Security Model](/security-model#clawhavoc-skill-scanner) for the full rule list and severity model.

#### Usage

```rust
use symbi_runtime::skills::SkillScanner;

let scanner = SkillScanner::new(); // includes all 40 default rules
let result = scanner.scan_skill("/path/to/skill/");

if !result.passed {
    for finding in &result.findings {
        eprintln!("[{}] {}: {} (line {})",
            finding.severity, finding.rule, finding.message, finding.line);
    }
}
```

Custom deny patterns can be added alongside the defaults:

```rust
let scanner = SkillScanner::with_custom_rules(vec![
    ("custom-pattern".into(), r"my_dangerous_pattern".into(),
     ScanSeverity::Warning, "Custom rule description".into()),
]);
```

### Server Configuration

The Runtime HTTP API server can be configured with the following options:

- **Default bind address**: `127.0.0.1:8080`
- **CORS support**: Configurable for development
- **Request tracing**: Enabled via Tower middleware
- **Feature gate**: Available behind `http-api` Cargo feature

---

### Feature Configuration Reference

#### Cloud LLM Inference (`cloud-llm`)

Connect to cloud LLM providers via OpenRouter for agent reasoning:

```bash
cargo build --features cloud-llm
```

**Environment Variables:**
- `OPENROUTER_API_KEY` — Your OpenRouter API key (required)
- `OPENROUTER_MODEL` — Model to use (default: `google/gemini-2.0-flash-001`)
- `OPENROUTER_REFERER` — Optional. Sets the `HTTP-Referer` header on OpenRouter requests (app attribution). Leave unset for unattributed traffic.
- `OPENROUTER_TITLE` — Optional. Sets the `X-Title` header. See [OpenRouter app attribution](https://openrouter.ai/docs/app-attribution).

The cloud LLM provider integrates with the reasoning loop's `execute_actions()` pipeline. It supports streaming responses, automatic retries with exponential backoff, and token usage tracking.

#### Standalone Agent Mode (`standalone-agent`)

Meta-feature that enables cloud LLM inference for cloud-native agents:

```bash
cargo build --features standalone-agent
# Enables: cloud-llm
```

**Environment Variables:**
- `OPENROUTER_API_KEY` — OpenRouter API key

> **Note:** Composio MCP and SymbiBot integration were removed in this version due to security concerns — see SECURITY_AUDIT.md C3 for context.

#### Cedar Policy Engine (`cedar`)

Formal authorization using the [Cedar policy language](https://www.cedarpolicy.com/):

```bash
cargo build --features cedar
```

Cedar policies integrate with the reasoning loop's Gate phase, providing fine-grained authorization decisions. See the [Security Model](/security-model#cedar-policy-engine) for policy examples.

#### Vector Database Configuration

Symbiont ships with **LanceDB** as the default embedded vector backend — no external service required. For scaled deployments, Qdrant is available as an optional backend.

**LanceDB (default):**
```toml
[vector_db]
enabled = true
backend = "lancedb"
collection_name = "symbi_knowledge"
```

No additional configuration needed. Data stored locally alongside the runtime.

**Qdrant (optional):**
```bash
cargo build --features vector-qdrant
```

```toml
[vector_db]
enabled = true
backend = "qdrant"
collection_name = "symbi_knowledge"
url = "http://localhost:6333"
```

**Environment Variables:**
- `SYMBIONT_VECTOR_BACKEND` — `lancedb` (default) or `qdrant`
- `QDRANT_URL` — Qdrant server URL (only when using Qdrant)

#### Advanced Reasoning Primitives (`orga-adaptive`)

Enable tool curation, stuck-loop detection, context pre-fetch, and scoped conventions:

```bash
cargo build --features orga-adaptive
```

See the [orga-adaptive guide](/orga-adaptive) for full configuration reference.

---

### Data Structures

#### Core Types
```rust
// Workflow execution request
WorkflowExecutionRequest {
    workflow_id: String,
    parameters: serde_json::Value,
    agent_id: Option<AgentId>
}

// Agent status response
AgentStatusResponse {
    agent_id: AgentId,
    state: AgentState,
    last_activity: DateTime<Utc>,
    resource_usage: ResourceUsage
}

// Health check response
HealthResponse {
    status: String,
    uptime_seconds: u64,
    timestamp: DateTime<Utc>,
    version: String
}

// Agent creation request
CreateAgentRequest {
    name: String,
    dsl: String
}

// Agent creation response
CreateAgentResponse {
    id: String,
    status: String
}

// Agent update request
UpdateAgentRequest {
    name: Option<String>,
    dsl: Option<String>
}

// Agent update response
UpdateAgentResponse {
    id: String,
    status: String
}

// Agent deletion response
DeleteAgentResponse {
    id: String,
    status: String
}

// Agent execution request
ExecuteAgentRequest {
    // Empty struct for now
}

// Agent execution response
ExecuteAgentResponse {
    execution_id: String,
    status: String
}

// Agent execution record
AgentExecutionRecord {
    execution_id: String,
    status: String,
    timestamp: String
}

// Agent execution history response
GetAgentHistoryResponse {
    history: Vec<AgentExecutionRecord>
}
```

### Runtime Provider Interface

The API implements a `RuntimeApiProvider` trait with the following enhanced methods:

- `execute_workflow()` - Execute a workflow with given parameters
- `get_agent_status()` - Retrieve detailed status with real-time execution metrics
- `get_system_health()` - Get overall system health with scheduler statistics
- `list_agents()` - List all agents (running, queued, and completed)
- `shutdown_agent()` - Gracefully shutdown with resource cleanup and timeout handling
- `get_metrics()` - Retrieve comprehensive system metrics including task statistics
- `create_agent()` - Create agents with execution mode specification
- `update_agent()` - Update agent configuration with persistence
- `delete_agent()` - Delete agent with proper cleanup of running processes
- `execute_agent()` - Trigger execution with monitoring and health checks
- `get_agent_history()` - Retrieve detailed execution history with performance metrics

#### Scheduling API

All scheduling endpoints require authentication. Requires the `cron` feature.

##### List Schedules
```http
GET /api/v1/schedules
Authorization: Bearer <your-token>
```

**Response (200 OK):**
```json
[
  {
    "job_id": "uuid",
    "name": "daily-report",
    "cron_expression": "0 0 9 * * *",
    "timezone": "America/New_York",
    "status": "active",
    "enabled": true,
    "next_run": "2026-03-04T09:00:00Z",
    "run_count": 42
  }
]
```

##### Create Schedule
```http
POST /api/v1/schedules
Authorization: Bearer <your-token>
```

**Request Body:**
```json
{
  "name": "daily-report",
  "cron_expression": "0 0 9 * * *",
  "timezone": "America/New_York",
  "agent_name": "report-agent",
  "policy_ids": ["policy-1"],
  "one_shot": false
}
```

The `cron_expression` uses six fields: `sec min hour day month weekday` (optional seventh field for year).

**Response (200 OK):**
```json
{
  "job_id": "uuid",
  "next_run": "2026-03-04T09:00:00Z",
  "status": "created"
}
```

##### Update Schedule
```http
PUT /api/v1/schedules/{id}
Authorization: Bearer <your-token>
```

**Request Body (all fields optional):**
```json
{
  "cron_expression": "0 */10 * * * *",
  "timezone": "UTC",
  "policy_ids": ["policy-2"],
  "one_shot": true
}
```

##### Pause / Resume / Trigger Schedule
```http
POST /api/v1/schedules/{id}/pause
POST /api/v1/schedules/{id}/resume
POST /api/v1/schedules/{id}/trigger
Authorization: Bearer <your-token>
```

**Response (200 OK):**
```json
{
  "job_id": "uuid",
  "action": "paused",
  "status": "ok"
}
```

##### Delete Schedule
```http
DELETE /api/v1/schedules/{id}
Authorization: Bearer <your-token>
```

**Response (200 OK):**
```json
{
  "job_id": "uuid",
  "deleted": true
}
```

##### Get Schedule History
```http
GET /api/v1/schedules/{id}/history
Authorization: Bearer <your-token>
```

**Response (200 OK):**
```json
{
  "job_id": "uuid",
  "history": [
    {
      "run_id": "uuid",
      "started_at": "2026-03-03T09:00:00Z",
      "completed_at": "2026-03-03T09:01:23Z",
      "status": "completed",
      "error": null,
      "execution_time_ms": 83000
    }
  ]
}
```

##### Get Next Runs
```http
GET /api/v1/schedules/{id}/next?count=5
Authorization: Bearer <your-token>
```

**Response (200 OK):**
```json
{
  "job_id": "uuid",
  "next_runs": [
    "2026-03-04T09:00:00Z",
    "2026-03-05T09:00:00Z"
  ]
}
```

##### Scheduler Health
```http
GET /api/v1/health/scheduler
```

Returns scheduler-specific health and statistics.

---

#### Channel Adapter API

All channel endpoints require authentication. Connects agents to Slack, Microsoft Teams, and Mattermost.

##### List Channels
```http
GET /api/v1/channels
Authorization: Bearer <your-token>
```

**Response (200 OK):**
```json
[
  {
    "id": "uuid",
    "name": "slack-general",
    "platform": "slack",
    "status": "running"
  }
]
```

##### Register Channel
```http
POST /api/v1/channels
Authorization: Bearer <your-token>
```

**Request Body:**
```json
{
  "name": "slack-general",
  "platform": "slack",
  "config": {
    "webhook_url": "https://hooks.slack.com/...",
    "channel": "#general"
  }
}
```

Supported platforms: `slack`, `teams`, `mattermost`.

**Response (200 OK):**
```json
{
  "id": "uuid",
  "name": "slack-general",
  "platform": "slack",
  "status": "registered"
}
```

##### Get / Update / Delete Channel
```http
GET    /api/v1/channels/{id}
PUT    /api/v1/channels/{id}
DELETE /api/v1/channels/{id}
Authorization: Bearer <your-token>
```

##### Start / Stop Channel
```http
POST /api/v1/channels/{id}/start
POST /api/v1/channels/{id}/stop
Authorization: Bearer <your-token>
```

**Response (200 OK):**
```json
{
  "id": "uuid",
  "action": "started",
  "status": "ok"
}
```

##### Channel Health
```http
GET /api/v1/channels/{id}/health
Authorization: Bearer <your-token>
```

**Response (200 OK):**
```json
{
  "id": "uuid",
  "connected": true,
  "platform": "slack",
  "workspace_name": "my-team",
  "channels_active": 3,
  "last_message_at": "2026-03-03T15:42:00Z",
  "uptime_secs": 86400
}
```

##### Identity Mappings
```http
GET  /api/v1/channels/{id}/mappings
POST /api/v1/channels/{id}/mappings
Authorization: Bearer <your-token>
```

Maps platform users to Symbiont identities for agent interactions.

##### Channel Audit Log
```http
GET /api/v1/channels/{id}/audit
Authorization: Bearer <your-token>
```

---

### Scheduler Features

**Real Task Execution:**
- Process spawning with secure execution environments
- Resource monitoring (memory, CPU) with 5-second intervals
- Health checks and automatic failure detection
- Support for ephemeral, persistent, scheduled, and event-driven execution modes

**Graceful Shutdown:**
- 30-second graceful termination period
- Force termination for unresponsive processes
- Resource cleanup and metrics persistence
- Queue cleanup and state synchronization

### Enhanced Context Management

**Advanced Search Capabilities:**
```json
{
  "query_type": "keyword|temporal|similarity|hybrid",
  "search_terms": ["term1", "term2"],
  "time_range": {
    "start": "2024-01-01T00:00:00Z",
    "end": "2024-01-31T23:59:59Z"
  },
  "memory_types": ["factual", "procedural", "episodic"],
  "relevance_threshold": 0.7,
  "max_results": 10
}
```

**Importance Calculation:**
- Multi-factor scoring with access frequency, recency, and user feedback
- Memory type weighting and age decay factors
- Trust score calculation for shared knowledge

**Access Control Integration:**
- Policy engine connected to context operations
- Agent-scoped access with secure boundaries
- Knowledge sharing with granular permissions

---

## Tool Review API (Production)

The Tool Review API provides a complete workflow for securely reviewing, analyzing, and signing MCP (Model Context Protocol) tools using AI-driven security analysis with human oversight capabilities.

### Base URL
```
https://your-symbiont-instance.com/api/v1
```

### Authentication
All endpoints require Bearer JWT authentication:
```
Authorization: Bearer <your-jwt-token>
```

### Core Workflow

The Tool Review API follows this request/response flow:

```mermaid
graph TD
    A[Submit Tool] --> B[Security Analysis]
    B --> C{Risk Assessment}
    C -->|Low Risk| D[Auto-Approve]
    C -->|High Risk| E[Human Review Queue]
    E --> F[Human Decision]
    F --> D
    D --> G[Code Signing]
    G --> H[Signed Tool Ready]
```

### Endpoints

#### Review Sessions

##### Submit Tool for Review
```http
POST /sessions
```

Submits an MCP tool for security review and analysis.

**Request Body:**
```json
{
  "tool_name": "string",
  "tool_version": "string",
  "source_code": "string",
  "metadata": {
    "description": "string",
    "author": "string",
    "permissions": ["array", "of", "permissions"]
  }
}
```

**Response:**
```json
{
  "review_id": "uuid",
  "status": "submitted",
  "created_at": "2024-01-15T10:30:00Z"
}
```

##### List Review Sessions
```http
GET /sessions
```

Retrieves a paginated list of review sessions with optional filtering.

**Query Parameters:**
- `page` (integer): Page number for pagination
- `limit` (integer): Number of items per page
- `status` (string): Filter by review status
- `author` (string): Filter by tool author

**Response:**
```json
{
  "sessions": [
    {
      "review_id": "uuid",
      "tool_name": "string",
      "status": "string",
      "created_at": "2024-01-15T10:30:00Z",
      "updated_at": "2024-01-15T11:00:00Z"
    }
  ],
  "pagination": {
    "page": 1,
    "limit": 20,
    "total": 100,
    "has_next": true
  }
}
```

##### Get Review Session Details
```http
GET /sessions/{reviewId}
```

Retrieves detailed information about a specific review session.

**Response:**
```json
{
  "review_id": "uuid",
  "tool_name": "string",
  "tool_version": "string",
  "status": "string",
  "analysis_results": {
    "risk_score": 85,
    "findings": ["array", "of", "security", "findings"],
    "recommendations": ["array", "of", "recommendations"]
  },
  "created_at": "2024-01-15T10:30:00Z",
  "updated_at": "2024-01-15T11:00:00Z"
}
```

#### Security Analysis

##### Get Analysis Results
```http
GET /analysis/{analysisId}
```

Retrieves detailed security analysis results for a specific analysis.

**Response:**
```json
{
  "analysis_id": "uuid",
  "review_id": "uuid",
  "risk_score": 85,
  "analysis_type": "automated",
  "findings": [
    {
      "severity": "high",
      "category": "code_injection",
      "description": "Potential code injection vulnerability detected",
      "location": "line 42",
      "recommendation": "Sanitize user input before execution"
    }
  ],
  "rag_insights": [
    {
      "knowledge_source": "security_kb",
      "relevance_score": 0.95,
      "insight": "Similar patterns found in known vulnerabilities"
    }
  ],
  "completed_at": "2024-01-15T10:45:00Z"
}
```

#### Human Review Workflow

##### Get Review Queue
```http
GET /review/queue
```

Retrieves items pending human review, typically high-risk tools requiring manual inspection.

**Response:**
```json
{
  "pending_reviews": [
    {
      "review_id": "uuid",
      "tool_name": "string",
      "risk_score": 92,
      "priority": "high",
      "assigned_to": "reviewer@example.com",
      "escalated_at": "2024-01-15T11:00:00Z"
    }
  ],
  "queue_stats": {
    "total_pending": 5,
    "high_priority": 2,
    "average_wait_time": "2h 30m"
  }
}
```

##### Submit Review Decision
```http
POST /review/{reviewId}/decision
```

Submits a human reviewer's decision on a tool review.

**Request Body:**
```json
{
  "decision": "approve|reject|request_changes",
  "comments": "Detailed review comments",
  "conditions": ["array", "of", "approval", "conditions"],
  "reviewer_id": "reviewer@example.com"
}
```

**Response:**
```json
{
  "review_id": "uuid",
  "decision": "approve",
  "processed_at": "2024-01-15T12:00:00Z",
  "next_status": "approved_for_signing"
}
```

#### Tool Signing

##### Get Signing Status
```http
GET /signing/{reviewId}
```

Retrieves the signing status and signature information for a reviewed tool.

**Response:**
```json
{
  "review_id": "uuid",
  "signing_status": "completed",
  "signature_info": {
    "algorithm": "RSA-SHA256",
    "key_id": "signing-key-001",
    "signature": "base64-encoded-signature",
    "signed_at": "2024-01-15T12:30:00Z"
  },
  "certificate_chain": ["array", "of", "certificates"]
}
```

##### Download Signed Tool
```http
GET /signing/{reviewId}/download
```

Downloads the signed tool package with embedded signature and verification metadata.

**Response:**
Binary download of the signed tool package.

#### Statistics & Monitoring

##### Get Workflow Statistics
```http
GET /stats
```

Retrieves comprehensive statistics and metrics about the review workflow.

**Response:**
```json
{
  "workflow_stats": {
    "total_reviews": 1250,
    "approved": 1100,
    "rejected": 125,
    "pending": 25
  },
  "performance_metrics": {
    "average_review_time": "45m",
    "auto_approval_rate": 0.78,
    "human_review_rate": 0.22
  },
  "security_insights": {
    "common_vulnerabilities": ["sql_injection", "xss", "code_injection"],
    "risk_score_distribution": {
      "low": 45,
      "medium": 35,
      "high": 20
    }
  }
}
```

### Rate Limiting

The Tool Review API implements rate limiting per endpoint type:

- **Submission endpoints**: 10 requests per minute
- **Query endpoints**: 100 requests per minute
- **Download endpoints**: 20 requests per minute

Rate limit headers are included in all responses:
```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1642248000
```

### Error Handling

The API uses standard HTTP status codes and returns detailed error information:

```json
{
  "error": {
    "code": "INVALID_REQUEST",
    "message": "Tool source code is required",
    "details": {
      "field": "source_code",
      "reason": "missing_required_field"
    }
  }
}
```


---

## CLI subcommands

Beyond the long-lived HTTP surface, `symbi` exposes several CLI-only subcommands for one-shot operations. The full catalogue is in `symbi --help`; the ones most relevant to integration and policy enforcement are:

### `symbi schemapin`

TOFU (Trust-On-First-Use) integrity pinning for MCP server configurations. Designed to be called from SessionStart hooks so that an MCP server's configuration hash can't silently change between sessions without the operator approving it.

```bash
# Verify the pinned hash for one or all MCP servers in .mcp.json
symbi schemapin verify [--mcp-server <NAME>] [--config <PATH>]

# Pin the current config hash for a server
symbi schemapin pin --mcp-server <NAME> [--config <PATH>] [--force]

# List every pinned server under ~/.symbiont/schemapin/mcp/
symbi schemapin list

# Remove a pin record
symbi schemapin unpin --mcp-server <NAME>
```

Pins are stored under `~/.symbiont/schemapin/mcp/` as JSON records. `verify` exits 0 on match, non-zero on mismatch or missing pin — suitable for use in pre-session scripts.

### `symbi policy`

Cedar policy evaluation against tool-call events. Reads a single event as JSON, decides `allow` / `deny` against a policy directory, and exits with a status code suitable for scripting.

```bash
# Evaluate an event read from stdin
echo '{"principal":"Agent::\"dev\"", "action":"write", "resource":{...}}' \
  | symbi policy evaluate --stdin --policies ./policies

# Evaluate an event read from a file
symbi policy evaluate --input event.json --policies ./policies

# Emit structured JSON only (suitable for programmatic use)
symbi policy evaluate --stdin --policies ./policies --json
```

Default output is the bare verdict on stdout with structured detail on stderr; pass `--json` to collapse everything to stdout JSON. This is the same Cedar decision logic the runtime uses inline — useful for shift-left policy testing in CI and for debugging denials outside a running runtime.

### `symbi agents-md`

Regenerate `AGENTS.md` from the current `agents/*.symbi` files (legacy `.dsl` is also picked up). Runs automatically during `symbi init`; call it manually after adding or editing agent definitions.

```bash
symbi agents-md generate --dir . --output AGENTS.md
```

### `symbi fmt`

Canonical-format `.symbi` files. Reuses the tree-sitter parse tree from `symbi-dsl` to emit a stable layout suitable for pre-commit hooks, CI gates, and editor save actions.

```bash
# Rewrite files in place
symbi fmt agents/*.symbi

# CI gate — exit 2 if anything would change, no writes
symbi fmt --check agents/*.symbi

# Stdio mode for editor integration
cat broken.symbi | symbi fmt --stdin
```

Exit codes: `0` no changes (or wrote successfully), `1` an I/O or syntax error occurred and no file was rewritten, `2` `--check` saw drift or invalid argument combination. The formatter refuses to format files containing syntax errors.

## Getting Started

### Runtime HTTP API

1. Build the `symbi` binary (the `http-api` feature is on by default in the binary crate):
   ```bash
   cargo build --release
   ```

2. Start the runtime — the API listens on `:8080` and HTTP Input on `:8081`:
   ```bash
   ./target/release/symbi up --http-bind 0.0.0.0
   ```

   For a scaffolded project and the recommended Docker flow, see [Getting Started](/getting-started).

3. Verify the server is running:
   ```bash
   curl http://127.0.0.1:8080/api/v1/health
   ```

4. Test an authenticated endpoint — `symbi up` prints the generated bearer token at startup (or set one explicitly with `--http.token`):
   ```bash
   curl -H "Authorization: Bearer $SYMBI_HTTP_TOKEN" \
        http://127.0.0.1:8080/api/v1/agents
   ```

### Tool Review API

1. Obtain API credentials from your Symbiont administrator
2. Submit a tool for review using the `/sessions` endpoint
3. Monitor the review progress via `/sessions/{reviewId}`
4. Download signed tools from `/signing/{reviewId}/download`

## Support

For API support and questions:
- Review the [Runtime Architecture documentation](runtime-architecture.md)
- Check the [Security Model documentation](security-model.md)
- File issues on the project's GitHub repository