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

# Invoke Tool

> Execute a specific tool from your stack

## Overview

Executes a specific tool from your stack with the provided input parameters. This endpoint allows you to programmatically invoke any enabled tool in your stack.

## Endpoint

```
POST https://api.toolrouter.ai/v1/stacks/{stack_id}/tools/{tool_id}/invoke
```

## Authentication

This endpoint requires an API key. Include it in the Authorization header:

```bash theme={null}
Authorization: Bearer YOUR_API_KEY
```

## Path Parameters

<ParamField path="stack_id" type="string" required>
  The unique identifier of the stack containing the tool
</ParamField>

<ParamField path="tool_id" type="string" required>
  The unique identifier of the tool to invoke
</ParamField>

## Request Body

<ParamField body="tool_input" type="object" required>
  Input parameters for the tool execution. The structure depends on the specific tool being invoked.

  <Note>
    Use the [List Stack Tools](/api-reference/endpoint/account/list_stack_tools) endpoint to see the required input schema for each tool.
  </Note>
</ParamField>

## Response

The response format varies depending on the tool being invoked. Each tool returns its results in a JSON object.

<ResponseField name="result" type="object">
  The output from the tool execution. Structure varies by tool.
</ResponseField>

## Example Requests

### Send Email via Gmail

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://api.toolrouter.ai/v1/stacks/stack_123e4567-e89b-12d3-a456-426614174000/tools/gmail_send_email/invoke" \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "tool_input": {
        "to": ["john@example.com", "jane@example.com"],
        "subject": "Meeting Reminder",
        "body": "This is a reminder about our meeting tomorrow at 2 PM."
      }
    }'
  ```

  ```python Python theme={null}
  import requests

  headers = {
      "Authorization": "Bearer YOUR_API_KEY",
      "Content-Type": "application/json"
  }

  data = {
      "tool_input": {
          "to": ["john@example.com", "jane@example.com"],
          "subject": "Meeting Reminder",
          "body": "This is a reminder about our meeting tomorrow at 2 PM."
      }
  }

  response = requests.post(
      "https://api.toolrouter.ai/v1/stacks/stack_123e4567-e89b-12d3-a456-426614174000/tools/gmail_send_email/invoke",
      headers=headers,
      json=data
  )

  result = response.json()
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://api.toolrouter.ai/v1/stacks/stack_123e4567-e89b-12d3-a456-426614174000/tools/gmail_send_email/invoke', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      tool_input: {
        to: ["john@example.com", "jane@example.com"],
        subject: "Meeting Reminder",
        body: "This is a reminder about our meeting tomorrow at 2 PM."
      }
    })
  });

  const result = await response.json();
  ```
</CodeGroup>

### Create Linear Issue

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://api.toolrouter.ai/v1/stacks/stack_123e4567-e89b-12d3-a456-426614174000/tools/linear_create_issue/invoke" \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "tool_input": {
        "title": "Fix login bug",
        "description": "Users are unable to log in with their email addresses",
        "teamId": "team_abc123"
      }
    }'
  ```

  ```python Python theme={null}
  import requests

  headers = {
      "Authorization": "Bearer YOUR_API_KEY",
      "Content-Type": "application/json"
  }

  data = {
      "tool_input": {
          "title": "Fix login bug",
          "description": "Users are unable to log in with their email addresses",
          "teamId": "team_abc123"
      }
  }

  response = requests.post(
      "https://api.toolrouter.ai/v1/stacks/stack_123e4567-e89b-12d3-a456-426614174000/tools/linear_create_issue/invoke",
      headers=headers,
      json=data
  )

  result = response.json()
  ```
</CodeGroup>

### Search Emails

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://api.toolrouter.ai/v1/stacks/stack_123e4567-e89b-12d3-a456-426614174000/tools/gmail_search_emails/invoke" \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "tool_input": {
        "query": "from:john@example.com subject:meeting",
        "maxResults": 10
      }
    }'
  ```

  ```python Python theme={null}
  import requests

  headers = {
      "Authorization": "Bearer YOUR_API_KEY",
      "Content-Type": "application/json"
  }

  data = {
      "tool_input": {
          "query": "from:john@example.com subject:meeting",
          "maxResults": 10
      }
  }

  response = requests.post(
      "https://api.toolrouter.ai/v1/stacks/stack_123e4567-e89b-12d3-a456-426614174000/tools/gmail_search_emails/invoke",
      headers=headers,
      json=data
  )

  result = response.json()
  ```
</CodeGroup>

## Example Responses

### Gmail Send Email Response

```json theme={null}
{
  "result": {
    "message_id": "18c2e1b2f3a4d5e6",
    "status": "sent",
    "recipients": ["john@example.com", "jane@example.com"],
    "timestamp": "2024-01-25T15:30:00Z"
  }
}
```

### Linear Create Issue Response

```json theme={null}
{
  "result": {
    "id": "issue_123abc456def",
    "number": 42,
    "title": "Fix login bug",
    "url": "https://linear.app/company/issue/TEAM-42",
    "state": "Backlog",
    "team": {
      "id": "team_abc123",
      "name": "Engineering"
    },
    "created_at": "2024-01-25T15:30:00Z"
  }
}
```

### Gmail Search Emails Response

```json theme={null}
{
  "result": {
    "emails": [
      {
        "id": "email_123",
        "subject": "Weekly team meeting",
        "from": "john@example.com",
        "snippet": "Let's discuss the project updates...",
        "date": "2024-01-24T10:00:00Z"
      },
      {
        "id": "email_456", 
        "subject": "Meeting notes",
        "from": "john@example.com",
        "snippet": "Here are the notes from yesterday's meeting...",
        "date": "2024-01-23T14:30:00Z"
      }
    ],
    "total_count": 2
  }
}
```

## Error Handling

### Tool Execution Errors

When a tool fails to execute properly, the response will include error details:

```json theme={null}
{
  "detail": "Invalid email address format"
}
```

### Common Tool Errors

* **Invalid parameters**: Tool input doesn't match the required schema
* **Authentication failure**: Tool credentials are missing or invalid
* **Service unavailable**: The external service (Gmail, Linear, etc.) is temporarily unavailable
* **Rate limiting**: Too many requests to the external service
* **Permission denied**: Credentials don't have necessary permissions

## Best Practices

### Input Validation

Always validate your input parameters before making the request:

```python theme={null}
def validate_email_input(tool_input):
    required_fields = ["to", "subject", "body"]
    for field in required_fields:
        if field not in tool_input:
            raise ValueError(f"Missing required field: {field}")
    
    if not isinstance(tool_input["to"], list):
        raise ValueError("'to' field must be a list of email addresses")
    
    return True

# Validate before invoking
try:
    validate_email_input(email_data["tool_input"])
    response = requests.post(endpoint, headers=headers, json=email_data)
except ValueError as e:
    print(f"Invalid input: {e}")
```

### Error Handling

Implement proper error handling for tool invocations:

```python theme={null}
import requests
from requests.exceptions import RequestException

def invoke_tool_safely(stack_id, tool_id, tool_input, headers):
    try:
        response = requests.post(
            f"https://api.toolrouter.ai/v1/stacks/{stack_id}/tools/{tool_id}/invoke",
            headers=headers,
            json={"tool_input": tool_input},
            timeout=30
        )
        
        if response.status_code == 200:
            return response.json()
        elif response.status_code == 500:
            error_detail = response.json().get("detail", "Unknown error")
            print(f"Tool execution failed: {error_detail}")
            return None
        else:
            print(f"API error: {response.status_code} - {response.text}")
            return None
            
    except RequestException as e:
        print(f"Request failed: {e}")
        return None
```

### Retry Logic

Implement retry logic for temporary failures:

```python theme={null}
import time
import random

def invoke_tool_with_retry(stack_id, tool_id, tool_input, headers, max_retries=3):
    for attempt in range(max_retries):
        result = invoke_tool_safely(stack_id, tool_id, tool_input, headers)
        
        if result is not None:
            return result
            
        if attempt < max_retries - 1:
            # Exponential backoff with jitter
            delay = (2 ** attempt) + random.uniform(0, 1)
            time.sleep(delay)
            
    return None
```

## Error Responses

<ResponseField name="400 Bad Request">
  Invalid tool input parameters

  ```json theme={null}
  {
    "detail": "Invalid input parameters for tool gmail_send_email"
  }
  ```
</ResponseField>

<ResponseField name="401 Unauthorized">
  Invalid or missing API key

  ```json theme={null}
  {
    "detail": "Unauthorized"
  }
  ```
</ResponseField>

<ResponseField name="404 Not Found">
  Stack or tool not found

  ```json theme={null}
  {
    "detail": "Stack not found"
  }
  ```

  ```json theme={null}
  {
    "detail": "Tool gmail_send_email not found in stack"
  }
  ```
</ResponseField>

<ResponseField name="429 Too Many Requests">
  Rate limit exceeded

  ```json theme={null}
  {
    "detail": "Too many requests"
  }
  ```
</ResponseField>

<ResponseField name="500 Internal Server Error">
  Tool execution failed

  ```json theme={null}
  {
    "detail": "Gmail API authentication failed"
  }
  ```
</ResponseField>
