# Tool API

Source: https://docs.autessa.com/docs/api/tools

> Complete API reference for executing custom tools with synchronous and streaming execution modes.

# Tool API

The Tool API allows you to execute custom tools that you've built in the Autessa platform. Tools can be executed synchronously for immediate results or via WebSocket for real-time streaming output.
> All Tool API requests require the `resourceId` query parameter set to your tool ID and an `Authorization` header with your API key.

---

## Base URL

```
REST API:   https://api.autessa.com/clients/tool
WebSocket:  wss://api.autessa.com/ws/clients/tools/execute
```

---

## Authentication

### HTTP REST APIs
Pass your API key in the `Authorization` header (no "Bearer" prefix):

```
Authorization: your_api_key_here
```

### WebSocket APIs
Pass your API key as a query parameter:

```
authorization=your_api_key_here
```

**REST:**

```bash
curl https://api.autessa.com/clients/tool/execute?resourceId=V1StGXR8Z5 \
  -H "Authorization: your_api_key" \
  -H "Content-Type: application/json"
```

**WebSocket:**

```bash
websocat "wss://api.autessa.com/ws/clients/tools/execute?authorization=your_api_key&resourceId=V1StGXR8Z5"
```

---

## REST API Endpoints

## Execute Tool **POST** `/execute`

Executes a tool synchronously and returns the complete result. This endpoint waits for the tool execution to complete before returning.

A tool with [sensitive output](/docs/guide/agentic/tools.md#sensitive-output) turned on can't be run with an API key: the call returns `403` with `SENSITIVE_TOOL_REQUIRES_USER`.

### Query Parameters

- `resourceId` (string, required) — The ID of the tool to execute.

### Request Body

- `toolId` (string, required) — The ID of the tool to execute.
- `variables` (object) — Public variables (input parameters) for the tool. Key-value pairs where both keys and values are strings.
- `privateVariables` (object) — Private variables that won't be exposed in the output or logs. String key-value pairs.
- `environmentVariables` (object) — Environment variables that won't be stored on the server. Useful for secrets. String key-value pairs.
- `version` (CustomVersion) — Optional version override. If not specified, uses the PUBLISHED version.

### Response

- `responseType` (string) — Always `"EXECUTE_TOOL"` for tool responses.
- `toolName` (string) — Name of the tool that was executed.
- `result` (any) — The result data from the tool execution. Can be any JSON structure.
- `publicVars` (object) — Public variables returned by the tool.
- `debuggingInfo` (object) — Debugging information including success status, logs, and final response.
- `invocationId` (string) — Unique UUID identifying this execution.
- `errors` — "> Array of error messages if any occurred.
  
  
  
  

**cURL:**

```bash
  curl --request POST \
    --url 'https://api.autessa.com/clients/tool/execute?resourceId=V1StGXR8Z5' \
    --header 'Content-Type: application/json' \
    --header 'Authorization: your_api_key' \
    --data '{
      "toolId": "V1StGXR8Z5",
      "variables": {
        "city": "Seattle",
        "state": "WA"
      },
      "environmentVariables": {
        "API_KEY": "secret_key"
      }
    }'
```

**JavaScript:**

```javascript
const response = await fetch(
'https://api.autessa.com/clients/tool/execute?resourceId=V1StGXR8Z5',
{
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'your_api_key'
  },
  body: JSON.stringify({
    toolId: 'V1StGXR8Z5',
    variables: {
      city: 'Seattle',
      state: 'WA'
    }
  })
}
);

const data = await response.json();
console.log(data.result);
```

**Python:**

```python
import requests

response = requests.post(
  'https://api.autessa.com/clients/tool/execute?resourceId=V1StGXR8Z5',
  headers={
      'Content-Type': 'application/json',
      'Authorization': 'your_api_key'
  },
  json={
      'toolId': 'V1StGXR8Z5',
      'variables': {
          'city': 'Seattle',
          'state': 'WA'
      }
  }
)

data = response.json()
print(data['result'])
```

  

**Success:**

```json
  {
    "responseType": "EXECUTE_TOOL",
    "toolName": "GetWeather",
    "invocationId": "8f14e45f-ceea-4e07-8c65-9d2f9a1b3c4d",
    "result": "It is 65 degrees Fahrenheit with partly cloudy skies",
    "publicVars": {
      "city": "Seattle",
      "state": "WA"
    },
    "debuggingInfo": {
      "success": true,
      "finalResponse": "It is 65 degrees Fahrenheit with partly cloudy skies",
      "logs": [
        "[2025-01-29 15:23:41.123] [LOG] Fetching weather data...",
        "[2025-01-29 15:23:42.456] [LOG] Weather data retrieved successfully"
      ]
    },
    "errors": []
  }
```

**Error:**

```json
{
"responseType": "EXECUTE_TOOL",
"toolName": "GetWeather",
"result": null,
"debuggingInfo": {
  "success": false,
  "logs": [
    "[2025-01-29 15:23:41.123] [ERROR] Failed to fetch weather data"
  ]
},
"errors": ["Tool execution failed"]
}
```

  

---

## WebSocket API

## Stream Tool Execution **WSS** `/ws/clients/tools/execute`

Real-time tool execution with streaming output. Allows you to receive intermediate results and debugging messages as the tool executes.

### Connection URL

```
wss://api.autessa.com/ws/clients/tools/execute?authorization={key}&resourceId={toolId}
```

### Query Parameters

- `authorization` (string, required) — Your API key.
- `resourceId` (string, required) — The ID of the tool to execute. This determines which tool runs — any `toolId` in the message body is ignored.

### Connection Lifecycle

1. **Connect** - WebSocket connection established
2. **Send Message** - Client sends tool execution request
3. **Receive Streams** - Server streams execution messages in real-time
4. **Final Result** - Server sends final execution result
5. **Disconnect** - Connection closes after execution completes

**websocat:**

```bash
websocat "wss://api.autessa.com/ws/clients/tools/execute?authorization=your_api_key&resourceId=V1StGXR8Z5"
```

**JavaScript:**

```javascript
const ws = new WebSocket(
  'wss://api.autessa.com/ws/clients/tools/execute?authorization=your_api_key&resourceId=V1StGXR8Z5'
);

ws.onopen = () => {
  console.log('Connected to tool');

  // Send execution request
  ws.send(JSON.stringify({
variables: {
  city: 'Seattle',
  state: 'WA'
}
  }));
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('Received:', data);
};
```

**Python:**

```python
import websocket
import json

ws = websocket.WebSocket()
ws.connect(
  "wss://api.autessa.com/ws/clients/tools/execute?authorization=your_api_key&resourceId=V1StGXR8Z5"
)

# Send execution request
ws.send(json.dumps({
'variables': {
    'city': 'Seattle',
    'state': 'WA'
}
}))

# Receive messages
while True:
message = ws.recv()
data = json.loads(message)
print(data)
if data.get('result'):
    break  # Final result received
```

### Client-to-Server Message

Send a JSON message to execute the tool:

- `variables` (object) — Public variables (input parameters). String key-value pairs.
- `privateVariables` (object) — Private variables. String key-value pairs.
- `environmentVariables` (object) — Environment variables. String key-value pairs.

> The executed tool is always the one identified by the `resourceId` connection parameter — a `toolId` field in the message body is ignored. Version overrides are not supported over WebSocket; the PUBLISHED version always runs.

```json title="JSON"
{
  "variables": {
    "city": "Seattle",
    "state": "WA"
  },
  "privateVariables": {},
  "environmentVariables": {
    "API_KEY": "secret_key"
  }
}
```

### Server-to-Client Messages

The server sends multiple messages during tool execution:

#### 1. Execution Start

Sent when the tool begins executing:

```json title="JSON"
{
  "responseType": "EXECUTE_TOOL",
  "toolName": "GetWeather",
  "invocationId": "8f14e45f-ceea-4e07-8c65-9d2f9a1b3c4d",
  "publicVars": {
    "city": "Seattle",
    "state": "WA"
  },
  "streamMessage": "EXECUTION START: GetWeather"
}
```

#### 2. Variables Preview

Shows the public variables being used:

```json title="JSON"
{
  "responseType": "EXECUTE_TOOL",
  "toolName": "GetWeather",
  "invocationId": "8f14e45f-ceea-4e07-8c65-9d2f9a1b3c4d",
  "streamMessage": "EXECUTION VARIABLES: {\"city\":\"Seattle\",\"state\":\"WA\"}"
}
```

#### 3. Custom Stream Messages

Any custom messages your tool sends via console.log or stream APIs:

```json title="JSON"
{
  "responseType": "EXECUTE_TOOL",
  "toolName": "GetWeather",
  "invocationId": "8f14e45f-ceea-4e07-8c65-9d2f9a1b3c4d",
  "streamMessage": "Fetching weather data from API..."
}
```

#### 4. Execution End

Sent when the tool finishes executing:

```json title="JSON"
{
  "responseType": "EXECUTE_TOOL",
  "toolName": "GetWeather",
  "invocationId": "8f14e45f-ceea-4e07-8c65-9d2f9a1b3c4d",
  "streamMessage": "EXECUTION END: GetWeather"
}
```

#### 5. Execution Result Preview

Preview of the tool's return value:

```json title="JSON"
{
  "responseType": "EXECUTE_TOOL",
  "toolName": "GetWeather",
  "invocationId": "8f14e45f-ceea-4e07-8c65-9d2f9a1b3c4d",
  "streamMessage": "EXECUTION RESULT: \"It is 65 degrees Fahrenheit with partly cloudy skies\""
}
```

#### 6. Final Result

The complete execution result with debugging info:

```json title="JSON"
{
  "responseType": "EXECUTE_TOOL",
  "toolName": "GetWeather",
  "invocationId": "8f14e45f-ceea-4e07-8c65-9d2f9a1b3c4d",
  "result": "It is 65 degrees Fahrenheit with partly cloudy skies",
  "publicVars": {
    "city": "Seattle",
    "state": "WA"
  },
  "debuggingInfo": {
    "success": true,
    "finalResponse": "It is 65 degrees Fahrenheit with partly cloudy skies",
    "logs": [
      "[2025-01-29 15:23:41.123] [LOG] Fetching weather data...",
      "[2025-01-29 15:23:42.456] [LOG] Weather data retrieved successfully"
    ]
  }
}
```

---

## Built-in Stream Message Prefixes

The Tool API uses built-in prefixes for system messages. Avoid using these prefixes in your custom stream messages:

- `EXECUTION START` — Sent when tool execution begins
- `EXECUTION VARIABLES` — Shows the public variables being used
- `EXECUTION END` — Sent when tool execution completes
- `EXECUTION RESULT` — Preview of the tool's return value

---

## Custom Version

Override the default PUBLISHED version of a tool. Version overrides apply to the REST endpoint only — WebSocket executions always run the PUBLISHED version.

- `versionState` (string) — Version state: `"PUBLISHED"`, `"DRAFT"`, or `"ARCHIVED"`. Defaults to `"PUBLISHED"`.
- `versionNumber` (integer) — Specific version number to use (optional).

```json title="REST API"
{
  "toolId": "V1StGXR8Z5",
  "version": {
    "versionState": "DRAFT",
    "versionNumber": 3
  },
  "variables": {...}
}
```

---

## Variables Guide

### Public Variables

Public variables are the main input parameters for your tool. They are:

- Visible in debugging output
- Logged for monitoring and evaluation
- Returned in the `publicVars` field

Use these for normal input parameters like IDs, search queries, etc.

### Private Variables

Private variables are not exposed in outputs or logs. Use these for:

- Intermediate values you want to pass
- Data that should not be logged
- Internal processing parameters

**Note:** Private variables are still visible during execution, just not in logs.

### Environment Variables

Environment variables are not stored on the server. Use these for:

- API keys and secrets
- Credentials
- Temporary configuration values

**Important:** Environment variables are passed with each request and never persisted.

---

## Rate Limiting

Tool execution is rate limited at two levels: per API key (the per-minute and per-day limits configured on the key) and per company. Both the REST and WebSocket endpoints enforce these limits.

When rate limited, you'll receive a 429 status code with the reason in the `errors` array of the response body.

---

## Complete Examples

### Simple Tool Execution

**JavaScript:**

```javascript
async function executeTool(toolId, variables) {
  const response = await fetch(
    `https://api.autessa.com/clients/tool/execute?resourceId=${toolId}`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'your_api_key'
      },
      body: JSON.stringify({
        toolId,
        variables
      })
    }
  );

  const data = await response.json();

  if (data.errors && data.errors.length > 0) {
    throw new Error(data.errors.join(', '));
  }

  return data.result;
}

// Usage
const weather = await executeTool('V1StGXR8Z5', {
  city: 'Seattle',
  state: 'WA'
});

console.log(weather);
// Output: "It is 65 degrees Fahrenheit with partly cloudy skies"
```

**Python:**

```python
import requests

def execute_tool(tool_id, variables):
    response = requests.post(
        f'https://api.autessa.com/clients/tool/execute?resourceId={tool_id}',
        headers={
            'Content-Type': 'application/json',
            'Authorization': 'your_api_key'
        },
        json={
            'toolId': tool_id,
            'variables': variables
        }
    )

    data = response.json()

    if data.get('errors'):
        raise Exception(', '.join(data['errors']))

    return data['result']

# Usage
weather = execute_tool('V1StGXR8Z5', {
    'city': 'Seattle',
    'state': 'WA'
})

print(weather)
# Output: "It is 65 degrees Fahrenheit with partly cloudy skies"
```

### Streaming Tool Execution

**JavaScript:**

```javascript
function executeToolStreaming(toolId, variables) {
  return new Promise((resolve, reject) => {
    const ws = new WebSocket(
      `wss://api.autessa.com/ws/clients/tools/execute?authorization=your_api_key&resourceId=${toolId}`
    );

    const streamMessages = [];
    let finalResult = null;

    ws.onopen = () => {
      ws.send(JSON.stringify({
        variables
      }));
    };

    ws.onmessage = (event) => {
      const data = JSON.parse(event.data);

      // Collect stream messages
      if (data.streamMessage) {
        console.log('Stream:', data.streamMessage);
        streamMessages.push(data.streamMessage);
      }

      // Final result
      if (data.result !== undefined) {
        finalResult = data.result;
        ws.close();
      }
    };

    ws.onclose = () => {
      resolve({
        result: finalResult,
        streamMessages
      });
    };

    ws.onerror = (error) => {
      reject(error);
    };
  });
}

// Usage
const { result, streamMessages } = await executeToolStreaming('V1StGXR8Z5', {
  city: 'Seattle',
  state: 'WA'
});

console.log('Final result:', result);
console.log('Stream messages:', streamMessages);
```

**Python:**

```python
import websocket
import json

def execute_tool_streaming(tool_id, variables):
    ws = websocket.WebSocket()
    ws.connect(
        f"wss://api.autessa.com/ws/clients/tools/execute?authorization=your_api_key&resourceId={tool_id}"
    )

    # Send execution request
    ws.send(json.dumps({
        'variables': variables
    }))

    stream_messages = []
    final_result = None

    # Receive messages
    while True:
        message = ws.recv()
        data = json.loads(message)

        # Stream messages
        if 'streamMessage' in data:
            print(f"Stream: {data['streamMessage']}")
            stream_messages.append(data['streamMessage'])

        # Final result
        if 'result' in data and data['result'] is not None:
            final_result = data['result']
            break

    ws.close()

    return {
        'result': final_result,
        'stream_messages': stream_messages
    }

# Usage
response = execute_tool_streaming('V1StGXR8Z5', {
    'city': 'Seattle',
    'state': 'WA'
})

print(f"Final result: {response['result']}")
print(f"Stream messages: {response['stream_messages']}")
```

### Tool with Environment Variables

```javascript title="JavaScript"
async function executeToolWithSecrets(toolId, variables, secrets) {
  const response = await fetch(
    `https://api.autessa.com/clients/tool/execute?resourceId=${toolId}`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'your_api_key'
      },
      body: JSON.stringify({
        toolId,
        variables,
        environmentVariables: secrets
      })
    }
  );

  const data = await response.json();
  return data.result;
}

// Usage - secrets are never logged
const result = await executeToolWithSecrets(
  'V1StGXR8Z5',
  { city: 'Seattle', state: 'WA' },
  { WEATHER_API_KEY: 'secret_key_123' }
);
```

---

## Error Handling

Always check for errors in the response:

```javascript title="JavaScript"
const response = await fetch(
  'https://api.autessa.com/clients/tool/execute?resourceId=V1StGXR8Z5',
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'your_api_key'
    },
    body: JSON.stringify({
      toolId: 'V1StGXR8Z5',
      variables: { city: 'Seattle' }
    })
  }
);

const data = await response.json();

if (data.errors && data.errors.length > 0) {
  console.error('Tool execution failed:', data.errors);
  // Handle error
} else {
  console.log('Result:', data.result);
  // Handle success
}
```

---

## Best Practices

### Security

- Use `environmentVariables` for API keys and secrets
- Never log sensitive data in stream messages
- Rotate API keys regularly

### Performance

- Use WebSocket for long-running tools that benefit from streaming
- Use REST API for quick, simple tool executions
- Implement exponential backoff for retries

### Debugging

- Check `debuggingInfo` for detailed execution logs
- Use stream messages to provide progress updates
- Back off when you receive 429 responses to avoid throttling

### Error Handling

- Always check the `errors` array
- Check `debuggingInfo.success` for execution status
- Implement proper error handling for network failures

---

## Related

- [API Overview](/docs/api.md)
- [Agent API](/docs/api/agents.md)
- [Scheduled Events API](/docs/api/scheduled-events.md)
- [Authentication](/docs/guide/authentication.md)
- [Building Tools](/docs/guide/agentic/tools.md)
- [Tool Types](/docs/tools.md)

