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

# Agent API: Trigger and Control Tavryn's Procurement Engine

> Trigger procurement scans, run per-contract analysis, start negotiations, and query Tavryn's command bar to get instant answers about your SaaS spend.

The Agent API gives you direct access to the autonomous engine that powers Tavryn. Use it to kick off full procurement scans on demand, deep-dive into a single contract's waste profile, drive negotiation rounds, and query Tavryn conversationally through the same command bar exposed by the Cmd+K interface. Every endpoint is idempotent-safe and rate-limited so you can integrate it safely into CI pipelines, internal tools, and webhook handlers.

***

## Run Procurement Scan

Trigger an immediate full procurement cycle — the same job the daily cron runs — for one or all businesses. Tavryn scans every active contract, scores each for savings potential, and opens negotiation rounds for any contract that clears the minimum-savings policy threshold.

```http theme={null}
POST /api/agent/run-now
```

> [!WARNING]
>
> This endpoint is rate-limited to **10 requests per minute** across all callers. Exceeding the limit returns HTTP `429` with a `resetMs` field (milliseconds until the window resets). Space your calls accordingly in automation scripts.

> [!TIP]
>
> Pass `"force": true` during development and testing to override the agent's idempotency window. Without `force`, Tavryn skips contracts it has already evaluated within the current cycle to avoid duplicate negotiations. Setting `force: true` re-evaluates every contract regardless of prior scan timestamps.

### Request Body

**businessId** `string`

UUID of a specific business to scan. When omitted, Tavryn runs the procurement cycle for all businesses registered in the system.

**force** `boolean` (default: false)

Set to `true` to bypass the idempotency guard and re-evaluate all contracts even if they were scanned recently. Useful for testing and for forcing a re-scan after you update contract data.

### Response

**message** `string`

Human-readable summary of what the agent did (e.g., `"Agent executed: 3 negotiations initiated, 3 notifications created."`).

**result** `object`

Structured outcome of the scan.

**result fields**

**totalNegotiationsStarted** `number`

Number of new negotiation rounds opened during this run.

**totalNotificationsCreated** `number`

Number of in-app notifications dispatched to business owners and approvers.

### Example Request

```bash theme={null}
curl -X POST https://your-tavryn-instance.com/api/agent/run-now \
  -H "Content-Type: application/json" \
  -d '{
    "businessId": "e3b0c442-98fc-1c14-b39f-92d1282048c0",
    "force": true
  }'
```

### Example Response

```json theme={null}
{
  "message": "Agent executed: 3 negotiations initiated, 3 notifications created.",
  "result": {
    "totalNegotiationsStarted": 3,
    "totalNotificationsCreated": 3
  }
}
```

### Status Codes

| Code | Meaning |
| - | - |
| `200` | Scan completed. Check `result` for counts. |
| `400` | Request body failed schema validation. |
| `429` | Rate limit exceeded. Retry after `resetMs` milliseconds. |
| `500` | Agent execution failed. |

***

## Analyze a Contract

Run Tavryn's full waste-detection analysis on a single contract. The agent evaluates seat utilization, usage telemetry, market benchmarks, and renewal proximity to produce a scored opportunity report — without opening a negotiation round.

```http theme={null}
POST /api/agent/analyze/{contractId}
```

> [!NOTE]
>
> Analysis is read-only and never mutates contract or negotiation records. Use it to preview savings potential before committing to a negotiation.

### Path Parameters

**contractId** `string` *required*

UUID of the contract to analyze.

### Rate Limit

20 requests per minute per `contractId`. Returns HTTP `429` with `resetMs` on breach.

### Response

**analysis** `object`

The full analysis report for the contract.

**analysis fields**

**contractId** `string`

UUID of the analyzed contract.

**saving** `number`

Estimated annual savings in USD based on the winning heuristic.

**heuristicType** `string`

The waste pattern detected. One of:

| Value | Description |
| - | - |
| `seat_optimization` | Idle licensed seats found — price proportional to unused ratio. |
| `usage_decline` | Telemetry reports a measurable drop in workload volume. |
| `none` | No immediate heuristic pattern detected at this time. |

**explanation** `string`

Plain-English description of the finding (e.g., `"19 of 50 seats inactive (38% idle)"`).

**targetPrice** `number`

Suggested opening offer for a negotiation derived from the analysis.

### Example Request

```bash theme={null}
curl -X POST https://your-tavryn-instance.com/api/agent/analyze/a1b2c3d4-e5f6-7890-abcd-ef1234567890
```

### Example Response

```json theme={null}
{
  "analysis": {
    "contractId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "saving": 4560,
    "heuristicType": "seat_optimization",
    "explanation": "19 of 50 seats inactive (38% idle)",
    "targetPrice": 7440
  }
}
```

***

## Run a Negotiation Loop

Execute one or more offer-counter-offer rounds against the vendor for a specific contract. See the [Negotiations API](https://tavryn.mintlify.site/api-reference/negotiations.md) for the full reference — this is a summary of the endpoint signature.

```http theme={null}
POST /api/agent/negotiate/{contractId}
```

```http theme={null}
GET  /api/agent/negotiate/{contractId}
```

| Method | Purpose |
| - | - |
| `POST` | Advance the negotiation — submit a new round with optional parameter overrides. |
| `GET` | Read the current negotiation status, contract details, and vendor memory without triggering a new round. |

### Path Parameters

**contractId** `string` *required*

UUID of the contract to negotiate.

### POST Request Body (all optional)

**maxRounds** `number`

Maximum rounds before Tavryn walks away. Integer `1`–`20`.

**walkAwayCeiling** `number`

Hard upper price limit in USD. Tavryn cancels the negotiation if it cannot get the vendor below this number.

**targetPrice** `number`

Explicit target price in USD. Overrides the heuristic-derived target.

### Rate Limit

20 requests per minute per `contractId` on `POST`. No rate limit on `GET`.

***

## Ask Tavryn (Command Bar)

Send a natural-language question or instruction to Tavryn and receive a structured answer — the same engine that powers the Cmd+K command bar in the dashboard. Supports both streaming (Server-Sent Events) and standard JSON responses.

```http theme={null}
POST /api/agent/command
```

### Request Body

**message** `string` *required*

The question or instruction for Tavryn. Maximum 2,000 characters. Examples: `"Which contracts renew in the next 30 days?"`, `"Start a negotiation for Notion"`, `"How much have we saved this quarter?"`.

**businessId** `string`

UUID of the business context to query. When omitted, Tavryn resolves the first available business automatically.

**stream** `boolean` (default: true)

Set to `false` to receive a single JSON response instead of a Server-Sent Events stream. Streaming is recommended for UI integrations to display typewriter-style output.

**history** `array`

Up to 10 prior conversation turns to maintain context across multi-turn queries. Each turn is an object with `role` (`"user"` or `"assistant"`) and `content` (string, max 2,000 chars).

### Rate Limit

30 requests per minute per business. Returns HTTP `429` with `resetMs` on breach.

### Streaming Response (SSE)

When `stream` is `true` and the `Accept` header includes `text/event-stream` or `*/*`, the response is a `text/event-stream` with three event types:

**chunk** `SSE event`

Incremental text fragment. Contains `chunk` (the new words), and `fullText` (the full response so far).

```
data: {"type":"chunk","chunk":"Which contracts","fullText":"Which contracts"}
```

**card** `SSE event`

A structured data card for rendering rich UI components (tables, charts, action buttons). Present only when the query returns actionable structured data.

```
data: {"type":"card","card":{"type":"contracts_table","rows":[...]}}
```

**done** `SSE event`

Terminal event signalling the response is complete.

```
data: {"type":"done","success":true,"toolCalls":["list_contracts","get_renewal_schedule"]}
```

### JSON Response (non-streaming)

**text** `string`

The full natural-language response from Tavryn.

**card** `object | null`

Structured data card, if applicable.

**toolCalls** `array`

List of internal tool names Tavryn invoked to answer the question (for debugging and audit purposes).

**businessId** `string`

The business UUID the response was scoped to.

### Example Request (streaming)

```bash theme={null}
curl -X POST https://your-tavryn-instance.com/api/agent/command \
  -H "Content-Type: application/json" \
  -H "Accept: text/event-stream" \
  -d '{
    "message": "Which contracts renew in the next 30 days?",
    "businessId": "e3b0c442-98fc-1c14-b39f-92d1282048c0",
    "stream": true
  }'
```

### Example Request (JSON)

```bash theme={null}
curl -X POST https://your-tavryn-instance.com/api/agent/command \
  -H "Content-Type: application/json" \
  -d '{
    "message": "How much have we saved this quarter?",
    "businessId": "e3b0c442-98fc-1c14-b39f-92d1282048c0",
    "stream": false
  }'
```

### Example JSON Response

```json theme={null}
{
  "text": "You have saved $18,400 this quarter across 6 completed negotiations. The largest single saving was $4,800 on your Salesforce Sales Cloud renewal.",
  "card": null,
  "toolCalls": ["get_savings_summary"],
  "businessId": "e3b0c442-98fc-1c14-b39f-92d1282048c0"
}
```

***

## Confirm a Command Action

When a command bar query results in a suggested action (e.g., "Start a negotiation for Notion"), Tavryn returns a confirmation prompt before executing. Use this endpoint to confirm and execute that action.

```http theme={null}
POST /api/agent/command/confirm
```

### Request Body

**action** `string` *required*

The action to execute. Must be one of:

| Value | Description |
| - | - |
| `start_negotiation` | Open a negotiation for the contract identified in `params`. |
| `request_approval` | Escalate a pending deal to a human approver. |
| `create_receipt` | Generate a payment receipt for a completed negotiation. |

**businessId** `string`

UUID of the business context. Resolved automatically if omitted.

**params** `object`

Key-value parameters required by the action (e.g., `{ "contractId": "..." }` for `start_negotiation`). Defaults to `{}`.

### Response

**action** `string`

The action that was executed.

**success** `boolean`

`true` if the action completed without error.

**message** `string`

Human-readable description of what was done.

**data** `object`

Action-specific result data (e.g., the new negotiation record for `start_negotiation`).

### Example Request

```bash theme={null}
curl -X POST https://your-tavryn-instance.com/api/agent/command/confirm \
  -H "Content-Type: application/json" \
  -d '{
    "action": "start_negotiation",
    "businessId": "e3b0c442-98fc-1c14-b39f-92d1282048c0",
    "params": {
      "contractId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
    }
  }'
```

### Example Response

```json theme={null}
{
  "action": "start_negotiation",
  "success": true,
  "message": "Negotiation started for Notion Team Plan.",
  "data": {
    "negotiation_id": "d4e5f6a7-b8c9-0123-defa-456789012345",
    "status": "active",
    "current_offer": 9800,
    "target_price": 9000
  }
}
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.