# Analytics API Source: https://docs.augmentcode.com/analytics/analytics-api Access usage metrics and analytics for your organization. **Preview Feature** The Analytics API is currently in preview and is available exclusively to Enterprise customers. The Analytics API provides access to usage metrics for your organization, including how Augment Code is being used across your team. It allows you to build your own AI integration dashboards with tools like Jellyfish. Track daily active users, usage patterns, and detailed activity metrics to understand and optimize your team's use of Augment Code. ## Base URL | Environment | URL | | ----------- | ----------------------------- | | Production | `https://api.augmentcode.com` | ## Getting started To use the Analytics API, you need to create a service account and generate an API token. 1. Navigate to your organization's **Service Accounts** page in the Augment web app: [app.augmentcode.com/settings/service-accounts](https://app.augmentcode.com/settings/service-accounts) 2. Click **Add Service Account** 3. Enter a **Service Name** (1-100 characters, alphanumeric, hyphens, and underscores only) 4. Optionally add a **Description** for the service account 5. Click **Create** Service account names must be unique within your organization. 1. In the **Service Accounts** list, find your newly created service account 2. Click **Create Token** 3. Enter a **Token Description** (e.g., "Analytics API integration") 4. Click **Create** 5. **Copy and securely store the token** — it will only be shown once Treat API tokens like passwords. Do not share them or commit them to version control. Include the token in the `Authorization` header of your API requests: ```bash theme={null} curl -X GET "https://api.augmentcode.com/analytics/v0/dau-count" \ -H "Authorization: Bearer " ``` For more details on service accounts, see the [Service Accounts documentation](/cli/automation/service-accounts). ## Available Endpoints The Analytics API provides several endpoints to access different types of usage data: Get daily active user counts over a date range Get the list of active users for a specific date with pagination Get aggregated usage metrics by day over a date range Get per-user usage metrics over a date range with pagination Get user activity broken down by programming language and editor ## Important Considerations **Timezone and Data Availability** All dates in requests and responses are interpreted and returned in **UTC timezone**. The most recent queryable date is "yesterday" (UTC), and data for the previous day becomes available at approximately **02:00 UTC** each day. Make sure to account for this when querying data or processing results. **Data Freshness** Analytics data is updated once daily. Data for a given day becomes available the following day at approximately 02:00 UTC. ### Common Constraints Most endpoints share these constraints: | Constraint | Value | | --------------------------- | ---------------------------------------------------- | | Maximum date range | 90 days | | Maximum historical lookback | 2 years | | Today and future dates | Not allowed (data available at \~02:00 UTC next day) | | Timezone | All dates interpreted as UTC | ## Next Steps View detailed API endpoint documentation Learn more about service accounts and authentication # Analytics API Reference Source: https://docs.augmentcode.com/analytics/api-reference Detailed API endpoint documentation. **Preview Feature** The Analytics API is currently in preview and is available exclusively to Enterprise customers. **Important: Timezone and Data Availability** All dates in requests and responses are interpreted and returned in **UTC timezone**. The most recent queryable date is "yesterday" (UTC), and data for the previous day becomes available at approximately **02:00 UTC** each day. **Data Freshness** Analytics data is updated once daily. Data for a given day becomes available the following day at approximately 02:00 UTC. ## GET /analytics/v0/dau-count Returns daily active user counts over a date range. ### Query Parameters | Parameter | Type | Required | Description | | ----------- | ------ | -------- | --------------------------------------- | | start\_date | string | No | Start date in `YYYY-MM-DD` format (UTC) | | end\_date | string | No | End date in `YYYY-MM-DD` format (UTC) | ### Date Range Behavior | Scenario | Behavior | | -------------------------- | -------------------------------------------------------------- | | Neither date provided | Returns last 7 days ending at yesterday (UTC) | | Only `start_date` provided | Returns 7 days starting from `start_date`, capped at yesterday | | Only `end_date` provided | Returns 7 days ending at `end_date` | | Both dates provided | Returns the specified inclusive range | ### Constraints | Constraint | Value | | --------------------------- | ---------------------------------------------------- | | Maximum date range | 90 days | | Maximum historical lookback | 2 years | | Today and future dates | Not allowed (data available at \~02:00 UTC next day) | | Timezone | All dates interpreted as UTC | ### Example Request ```bash theme={null} curl -X GET "https://api.augmentcode.com/analytics/v0/dau-count?start_date=2025-10-15&end_date=2025-10-20" \ -H "Authorization: Bearer " ``` ### Example Response ```json theme={null} { "daily_active_user_counts": [ {"date": "2025-10-15", "user_count": 100}, {"date": "2025-10-16", "user_count": 120}, {"date": "2025-10-17", "user_count": 95}, {"date": "2025-10-18", "user_count": 140}, {"date": "2025-10-19", "user_count": 88}, {"date": "2025-10-20", "user_count": 110} ], "metadata": { "effective_start_date": "2025-10-15", "effective_end_date": "2025-10-20", "generated_at": "2025-10-21T10:30:00Z", "total_days": 6 } } ``` ### Response Fields | Field | Type | Description | | ------------------------------------------ | ------- | ----------------------------------------------------- | | daily\_active\_user\_counts | array | Array of daily user counts, one per day | | daily\_active\_user\_counts\[].date | string | Calendar date (`YYYY-MM-DD`) | | daily\_active\_user\_counts\[].user\_count | integer | Number of unique active users | | metadata.effective\_start\_date | string | Actual start date used (UTC, after defaults/clamping) | | metadata.effective\_end\_date | string | Actual end date used (UTC, after defaults/clamping) | | metadata.generated\_at | string | Response generation timestamp (ISO 8601) | | metadata.total\_days | integer | Number of days in the range | *** ## GET /analytics/v0/dau Returns the list of active users for a specific date. Supports pagination. ### Query Parameters | Parameter | Type | Required | Description | | ---------- | ------- | -------- | ------------------------------------------ | | date | string | No | Date to query in `YYYY-MM-DD` format (UTC) | | cursor | string | No | Pagination cursor from previous response | | page\_size | integer | No | Number of results per page | ### Date Behavior | Scenario | Behavior | | ----------------- | ---------------------------------------------------------------- | | Date not provided | Defaults to yesterday (UTC) | | Date provided | Returns users active on that date (must be yesterday or earlier) | ### Pagination | Parameter | Default | Maximum | | ---------- | ------- | ------- | | page\_size | 100 | 250 | To paginate through results: 1. Make initial request (optionally with `page_size`) 2. If `pagination.has_more` is `true`, use `pagination.next_cursor` as the `cursor` parameter 3. Repeat until `has_more` is `false` ### Constraints | Constraint | Value | | --------------------------- | ---------------------------------------------------- | | Maximum historical lookback | 2 years | | Today and future dates | Not allowed (data available at \~02:00 UTC next day) | | Timezone | All dates interpreted as UTC | ### Example Request (First Page) ```bash theme={null} curl -X GET "https://api.augmentcode.com/analytics/v0/dau?date=2025-10-15&page_size=50" \ -H "Authorization: Bearer " ``` ### Example Response ```json theme={null} { "users": [ {"user_email": "alice@example.com"}, {"user_email": "bob@example.com"}, {"service_account_name": "ci-bot"} ], "pagination": { "next_cursor": "eyJsYXN0X2lkIjoidXNlcjUwIn0=", "has_more": true }, "metadata": { "effective_date": "2025-10-15", "generated_at": "2025-10-16T10:30:00Z", "returned_user_count": 3 } } ``` ### Example Request (Next Page) ```bash theme={null} curl -X GET "https://api.augmentcode.com/analytics/v0/dau?date=2025-10-15&page_size=50&cursor=eyJsYXN0X2lkIjoidXNlcjUwIn0=" \ -H "Authorization: Bearer " ``` ### Response Fields | Field | Type | Description | | ------------------------------- | ------- | -------------------------------------------------------- | | users | array | Array of active users | | users\[].user\_email | string | User's email address (for regular users) | | users\[].service\_account\_name | string | Service account name (for service accounts) | | pagination.next\_cursor | string | Cursor for fetching next page (empty if no more results) | | pagination.has\_more | boolean | `true` if more results are available | | metadata.effective\_date | string | Actual date used (UTC, after defaults) | | metadata.generated\_at | string | Response generation timestamp (ISO 8601) | | metadata.returned\_user\_count | integer | Number of users returned in this page | Each user has either `user_email` or `service_account_name`, never both. *** ## GET /analytics/v0/daily-usage Returns daily usage metrics for your organization over a date range. Days with no activity are omitted from the response. ### Query Parameters | Parameter | Type | Required | Description | | ----------- | ------ | -------- | --------------------------------------- | | start\_date | string | No | Start date in `YYYY-MM-DD` format (UTC) | | end\_date | string | No | End date in `YYYY-MM-DD` format (UTC) | ### Date Range Behavior | Scenario | Behavior | | -------------------------- | -------------------------------------------------------------- | | Neither date provided | Returns last 7 days ending at yesterday (UTC) | | Only `start_date` provided | Returns 7 days starting from `start_date`, capped at yesterday | | Only `end_date` provided | Returns 7 days ending at `end_date` | | Both dates provided | Returns the specified inclusive range | ### Constraints | Constraint | Value | | --------------------------- | ---------------------------------------------------- | | Maximum date range | 90 days | | Maximum historical lookback | 2 years | | Today and future dates | Not allowed (data available at \~02:00 UTC next day) | | Timezone | All dates interpreted as UTC | ### Example Request ```bash theme={null} curl -s -X GET "https://api.augmentcode.com/analytics/v0/daily-usage?start_date=2025-10-15&end_date=2025-10-20" \ -H "Authorization: Bearer " | jq . ``` ### Example Response ```json theme={null} { "daily_usage": [ { "date": "2025-10-15", "metrics": { "total_modified_lines_of_code": 1250, "total_messages": 340, "total_tool_calls": 890, "completions_count": 1500, "completions_accepted": 1120, "completions_lines_of_code": 980, "chat_messages": 85, "remote_agent_messages": 45, "remote_agent_lines_of_code": 120, "ide_agent_messages": 150, "ide_agent_lines_of_code": 95, "cli_agent_interactive_messages": 40, "cli_agent_interactive_lines_of_code": 35, "cli_agent_non_interactive_messages": 20, "cli_agent_non_interactive_lines_of_code": 20 } } ], "metadata": { "effective_start_date": "2025-10-15", "effective_end_date": "2025-10-20", "generated_at": "2025-10-21T10:30:00Z", "total_days": 1 } } ``` ### Response Fields | Field | Type | Description | | --------------------------------------------------------------------- | ------- | ---------------------------------------------------------------- | | daily\_usage | array | Array of daily usage data points (days with no activity omitted) | | daily\_usage\[].date | string | Calendar date (`YYYY-MM-DD`) | | daily\_usage\[].metrics | object | Usage metrics for this date | | daily\_usage\[].metrics.total\_modified\_lines\_of\_code | integer | Total lines of code modified across all interactions | | daily\_usage\[].metrics.total\_messages | integer | Total messages across all interaction types | | daily\_usage\[].metrics.total\_tool\_calls | integer | Total tool calls across all agent types | | daily\_usage\[].metrics.completions\_count | integer | Number of completion requests | | daily\_usage\[].metrics.completions\_accepted | integer | Number of completions accepted by users | | daily\_usage\[].metrics.completions\_lines\_of\_code | integer | Lines of code from completions | | daily\_usage\[].metrics.completions\_suggested\_lines\_of\_code | integer | Lines of code suggested by completions (before acceptance) | | daily\_usage\[].metrics.chat\_messages | integer | Number of chat messages | | daily\_usage\[].metrics.remote\_agent\_messages | integer | Number of Remote Agent messages | | daily\_usage\[].metrics.remote\_agent\_lines\_of\_code | integer | Lines of code from Remote Agent | | daily\_usage\[].metrics.ide\_agent\_messages | integer | Number of IDE Agent messages | | daily\_usage\[].metrics.ide\_agent\_lines\_of\_code | integer | Lines of code from IDE Agent | | daily\_usage\[].metrics.cli\_agent\_interactive\_messages | integer | Number of CLI Agent interactive messages | | daily\_usage\[].metrics.cli\_agent\_interactive\_lines\_of\_code | integer | Lines of code from CLI Agent interactive mode | | daily\_usage\[].metrics.cli\_agent\_non\_interactive\_messages | integer | Number of CLI Agent non-interactive messages | | daily\_usage\[].metrics.cli\_agent\_non\_interactive\_lines\_of\_code | integer | Lines of code from CLI Agent non-interactive mode | | metadata.effective\_start\_date | string | Actual start date used (UTC, after defaults/clamping) | | metadata.effective\_end\_date | string | Actual end date used (UTC, after defaults/clamping) | | metadata.generated\_at | string | Response generation timestamp (ISO 8601) | | metadata.total\_days | integer | Number of days with data in the response | *** ## GET /analytics/v0/user-activity Returns aggregated usage metrics per user over a date range. Users with no activity are omitted. Supports pagination. ### Query Parameters | Parameter | Type | Required | Description | | ----------- | ------- | -------- | ---------------------------------------- | | start\_date | string | No | Start date in `YYYY-MM-DD` format (UTC) | | end\_date | string | No | End date in `YYYY-MM-DD` format (UTC) | | cursor | string | No | Pagination cursor from previous response | | page\_size | integer | No | Number of results per page | ### Date Range Behavior | Scenario | Behavior | | -------------------------- | -------------------------------------------------------------- | | Neither date provided | Returns last 7 days ending at yesterday (UTC) | | Only `start_date` provided | Returns 7 days starting from `start_date`, capped at yesterday | | Only `end_date` provided | Returns 7 days ending at `end_date` | | Both dates provided | Returns the specified inclusive range | ### Pagination | Parameter | Default | Maximum | | ---------- | ------- | ------- | | page\_size | 50 | 100 | To paginate through results: 1. Make initial request (optionally with `page_size`) 2. If `pagination.has_more` is `true`, use `pagination.next_cursor` as the `cursor` parameter 3. Repeat until `has_more` is `false` ### Constraints | Constraint | Value | | --------------------------- | ---------------------------------------------------- | | Maximum date range | 90 days | | Maximum historical lookback | 2 years | | Today and future dates | Not allowed (data available at \~02:00 UTC next day) | | Timezone | All dates interpreted as UTC | ### Example Request ```bash theme={null} curl -s -X GET "https://api.augmentcode.com/analytics/v0/user-activity?start_date=2025-10-15&end_date=2025-10-20&page_size=3" \ -H "Authorization: Bearer " | jq . ``` ### Example Response ```json theme={null} { "users": [ { "user_email": "alice@example.com", "active_days": 5, "metrics": { "total_modified_lines_of_code": 450, "total_messages": 65, "total_tool_calls": 120, "completions_count": 320, "completions_accepted": 280, "completions_lines_of_code": 350, "chat_messages": 25, "remote_agent_messages": 10, "remote_agent_lines_of_code": 45, "ide_agent_messages": 30, "ide_agent_lines_of_code": 40, "cli_agent_interactive_messages": 8, "cli_agent_interactive_lines_of_code": 10, "cli_agent_non_interactive_messages": 5, "cli_agent_non_interactive_lines_of_code": 5 } }, { "user_email": "bob@example.com", "active_days": 3, "metrics": { "total_modified_lines_of_code": 280, "total_messages": 70, "total_tool_calls": 75, "completions_count": 150, "completions_accepted": 120, "completions_lines_of_code": 180, "chat_messages": 40, "remote_agent_messages": 5, "remote_agent_lines_of_code": 25, "ide_agent_messages": 20, "ide_agent_lines_of_code": 55, "cli_agent_interactive_messages": 3, "cli_agent_interactive_lines_of_code": 15, "cli_agent_non_interactive_messages": 2, "cli_agent_non_interactive_lines_of_code": 5 } }, { "service_account_name": "ci-bot", "active_days": 6, "metrics": { "total_modified_lines_of_code": 200, "total_messages": 50, "total_tool_calls": 85, "completions_count": 0, "completions_accepted": 0, "completions_lines_of_code": 0, "chat_messages": 0, "remote_agent_messages": 0, "remote_agent_lines_of_code": 0, "ide_agent_messages": 0, "ide_agent_lines_of_code": 0, "cli_agent_interactive_messages": 0, "cli_agent_interactive_lines_of_code": 0, "cli_agent_non_interactive_messages": 50, "cli_agent_non_interactive_lines_of_code": 200 } } ], "pagination": { "next_cursor": "eyJsYXN0X2lkIjoidXNlcjMifQ==", "has_more": true }, "metadata": { "effective_start_date": "2025-10-15", "effective_end_date": "2025-10-20", "generated_at": "2025-10-21T10:30:00Z", "total_days": 6, "returned_user_count": 3 } } ``` ### Response Fields | Field | Type | Description | | -------------------------------------------------------------- | ------- | --------------------------------------------------------------- | | users | array | Array of user activity records (users with no activity omitted) | | users\[].user\_email | string | User's email address (for regular users) | | users\[].service\_account\_name | string | Service account name (for service accounts) | | users\[].active\_days | integer | Number of distinct days with activity in the date range | | users\[].metrics | object | Usage metrics for this user (summed over date range) | | users\[].metrics.total\_modified\_lines\_of\_code | integer | Total lines of code modified across all interactions | | users\[].metrics.total\_messages | integer | Total messages across all interaction types | | users\[].metrics.total\_tool\_calls | integer | Total tool calls across all agent types | | users\[].metrics.completions\_count | integer | Number of completion requests | | users\[].metrics.completions\_accepted | integer | Number of completions accepted | | users\[].metrics.completions\_lines\_of\_code | integer | Lines of code from completions | | users\[].metrics.completions\_suggested\_lines\_of\_code | integer | Lines of code suggested by completions (before acceptance) | | users\[].metrics.chat\_messages | integer | Number of chat messages | | users\[].metrics.remote\_agent\_messages | integer | Number of Remote Agent messages | | users\[].metrics.remote\_agent\_lines\_of\_code | integer | Lines of code from Remote Agent | | users\[].metrics.ide\_agent\_messages | integer | Number of IDE Agent messages | | users\[].metrics.ide\_agent\_lines\_of\_code | integer | Lines of code from IDE Agent | | users\[].metrics.cli\_agent\_interactive\_messages | integer | Number of CLI Agent interactive messages | | users\[].metrics.cli\_agent\_interactive\_lines\_of\_code | integer | Lines of code from CLI Agent interactive mode | | users\[].metrics.cli\_agent\_non\_interactive\_messages | integer | Number of CLI Agent non-interactive messages | | users\[].metrics.cli\_agent\_non\_interactive\_lines\_of\_code | integer | Lines of code from CLI Agent non-interactive mode | | pagination.next\_cursor | string | Cursor for fetching next page (empty if no more results) | | pagination.has\_more | boolean | `true` if more results are available | | metadata.effective\_start\_date | string | Actual start date used (UTC, after defaults/clamping) | | metadata.effective\_end\_date | string | Actual end date used (UTC, after defaults/clamping) | | metadata.generated\_at | string | Response generation timestamp (ISO 8601) | | metadata.total\_days | integer | Total number of days in the queried date range | | metadata.returned\_user\_count | integer | Number of users returned in this page | Each user has either `user_email` or `service_account_name`, never both. *** ## GET /analytics/v0/daily-user-activity-by-editor-language Returns user activity metrics broken down by language and editor for a specific date. Supports pagination. ### Query Parameters | Parameter | Type | Required | Description | | ---------- | ------- | -------- | ------------------------------------------ | | date | string | No | Date to query in `YYYY-MM-DD` format (UTC) | | cursor | string | No | Pagination cursor from previous response | | page\_size | integer | No | Number of results per page | ### Date Behavior | Scenario | Behavior | | ----------------- | ------------------------------------------------------------- | | Date not provided | Defaults to yesterday (UTC) | | Date provided | Returns activity for that date (must be yesterday or earlier) | ### Pagination | Parameter | Default | Maximum | | ---------- | ------- | ------- | | page\_size | 50 | 100 | To paginate through results: 1. Make initial request (optionally with `page_size`) 2. If `pagination.has_more` is `true`, use `pagination.next_cursor` as the `cursor` parameter 3. Repeat until `has_more` is `false` ### Constraints | Constraint | Value | | --------------------------- | ---------------------------------------------------- | | Maximum historical lookback | 2 years | | Today and future dates | Not allowed (data available at \~02:00 UTC next day) | | Timezone | All dates interpreted as UTC | ### Example Request (First Page) ```bash theme={null} curl -X GET "https://api.augmentcode.com/analytics/v0/daily-user-activity-by-editor-language?date=2025-10-15&page_size=50" \ -H "Authorization: Bearer " ``` ### Example Response ```json theme={null} { "records": [ { "user_email": "alice@example.com", "language": "Python", "editor": "VSCode", "metrics": { "total_modified_lines_of_code": 150, "total_messages": 25, "total_tool_calls": 40, "completions_count": 80, "completions_accepted": 65, "completions_lines_of_code": 120, "chat_messages": 10, "remote_agent_messages": 5, "remote_agent_lines_of_code": 15, "ide_agent_messages": 8, "ide_agent_lines_of_code": 12, "cli_agent_interactive_messages": 2, "cli_agent_interactive_lines_of_code": 3, "cli_agent_non_interactive_messages": 0, "cli_agent_non_interactive_lines_of_code": 0 } }, { "user_email": "alice@example.com", "language": "TypeScript", "editor": "VSCode", "metrics": { "total_modified_lines_of_code": 80, "total_messages": 12, "total_tool_calls": 18, "completions_count": 45, "completions_accepted": 38, "completions_lines_of_code": 60, "chat_messages": 5, "remote_agent_messages": 2, "remote_agent_lines_of_code": 8, "ide_agent_messages": 4, "ide_agent_lines_of_code": 10, "cli_agent_interactive_messages": 1, "cli_agent_interactive_lines_of_code": 2, "cli_agent_non_interactive_messages": 0, "cli_agent_non_interactive_lines_of_code": 0 } } ], "pagination": { "next_cursor": "eyJsYXN0X2lkIjoidXNlcjMifQ==", "has_more": true }, "metadata": { "effective_date": "2025-10-15", "generated_at": "2025-10-16T10:30:00Z", "returned_record_count": 2 } } ``` ### Example Request (Next Page) ```bash theme={null} curl -X GET "https://api.augmentcode.com/analytics/v0/daily-user-activity-by-editor-language?date=2025-10-15&page_size=50&cursor=eyJsYXN0X2lkIjoidXNlcjMifQ==" \ -H "Authorization: Bearer " ``` ### Response Fields | Field | Type | Description | | ---------------------------------------------------------------- | ------- | --------------------------------------------------------------- | | records | array | Array of user/language/editor activity records | | records\[].user\_email | string | User's email address (for regular users) | | records\[].service\_account\_name | string | Service account name (for service accounts) | | records\[].language | string | Programming language (e.g., "Python", "TypeScript", "Unknown") | | records\[].editor | string | Editor/IDE name (e.g., "VSCode", "JetBrains", "CLI", "Unknown") | | records\[].metrics | object | Usage metrics for this user/language/editor combination | | records\[].metrics.total\_modified\_lines\_of\_code | integer | Total lines of code modified across all interactions | | records\[].metrics.total\_messages | integer | Total messages across all interaction types | | records\[].metrics.total\_tool\_calls | integer | Total tool calls across all agent types | | records\[].metrics.completions\_count | integer | Number of completion requests | | records\[].metrics.completions\_accepted | integer | Number of completions accepted | | records\[].metrics.completions\_lines\_of\_code | integer | Lines of code from completions | | records\[].metrics.completions\_suggested\_lines\_of\_code | integer | Lines of code suggested by completions (before acceptance) | | records\[].metrics.chat\_messages | integer | Number of chat messages | | records\[].metrics.remote\_agent\_messages | integer | Number of Remote Agent messages | | records\[].metrics.remote\_agent\_lines\_of\_code | integer | Lines of code from Remote Agent | | records\[].metrics.ide\_agent\_messages | integer | Number of IDE Agent messages | | records\[].metrics.ide\_agent\_lines\_of\_code | integer | Lines of code from IDE Agent | | records\[].metrics.cli\_agent\_interactive\_messages | integer | Number of CLI Agent interactive messages | | records\[].metrics.cli\_agent\_interactive\_lines\_of\_code | integer | Lines of code from CLI Agent interactive mode | | records\[].metrics.cli\_agent\_non\_interactive\_messages | integer | Number of CLI Agent non-interactive messages | | records\[].metrics.cli\_agent\_non\_interactive\_lines\_of\_code | integer | Lines of code from CLI Agent non-interactive mode | | pagination.next\_cursor | string | Cursor for fetching next page (empty if no more results) | | pagination.has\_more | boolean | `true` if more results are available | | metadata.effective\_date | string | Actual date used (UTC, after defaults) | | metadata.generated\_at | string | Response generation timestamp (ISO 8601) | | metadata.returned\_record\_count | integer | Number of records returned in this page | Each record has either `user_email` or `service_account_name`, never both. A single user may have multiple records if they used different language/editor combinations on the queried date. *** ## Rate Limiting The Analytics API enforces rate limits to ensure fair usage and system stability. | Limit Type | Value | | ------------------- | ------------------ | | Requests per minute | 10 requests/minute | | Burst allowance | 20 requests | When you exceed the rate limit, the API returns HTTP status code `429 Too Many Requests`. Your requests will be blocked for the duration specified above before you can make new requests. ### Best Practices 1. **Batch your requests**: Instead of making many small requests, use larger date ranges (up to 90 days) to retrieve more data per request. 2. **Implement exponential backoff**: If you receive a `429` response, wait before retrying. Start with a short delay and increase it with each consecutive failure. 3. **Cache responses**: Analytics data is updated only once daily, so cache responses and avoid re-fetching the same data within a 24-hour period. 4. **Use pagination efficiently**: When paginating through large result sets, process each page before requesting the next one rather than fetching all pages as fast as possible. 5. **Spread requests over time**: If you need to make multiple API calls, distribute them evenly rather than sending them all at once. *** ## Error Responses The API returns standard HTTP status codes: | Status Code | Description | | ----------- | ------------------------------------------------------------------ | | 400 | Invalid request (e.g., invalid date format, range exceeds 90 days) | | 401 | Missing or invalid authentication token | | 403 | Insufficient permissions | | 429 | Too many requests (rate limit exceeded) | | 500 | Internal server error | ### Example Error Response ```json theme={null} { "error": { "code": "InvalidArgument", "message": "end_date cannot be later than yesterday (UTC)" } } ``` # Overview of Analytics Source: https://docs.augmentcode.com/analytics/overview Monitor team usage patterns and analyze Augment Code adoption across your organization. **Enterprise-Only Feature** Exclusive to Enterprise customers, access the Team Usage under Analytics at [app.augmentcode.com/dashboard](https://app.augmentcode.com/dashboard). ## Feature Metrics at a Glance Number of unique users in the current calendar month Total lines of code generated from all sources during the selected period Total number of user messages and tool calls during the selected period ## Understand adoption inside of your organization Review detailed per-user metrics to understand power-user usage patterns or inactivity inside your organization. ### Available Columns | Column | Description | | -------------------------------------- | -------------------------------------------------------------------------- | | **User** | Email or service account name (with visual indicator for service accounts) | | **First Seen** | Date user first appeared in the system | | **Last Seen** | Date of user's most recent activity | | **Active Days** | Number of days user was active in the selected period | | **Completions** | Total code completions generated | | **Accepted Completions** | Number of completions accepted by user | | **Accept Rate** | Percentage of completions accepted | | **Chat Messages** | Total chat messages sent | | **Agent Messages** | Messages from agent interactions | | **Remote Agent Messages** | Messages from remote agent sessions | | **Interactive CLI Agent Messages** | Interactive CLI agent interactions | | **Non-Interactive CLI Agent Messages** | Non-interactive CLI agent interactions | | **Tool Uses** | Total number of tool invocations | | **Total Modified Lines of Code** | All lines of code modified | | **Completion Lines of Code** | Lines from completions | | **Instruction Lines of Code** | Lines from instructions | | **Agent Lines of Code** | Lines from agent edits | | **Remote Agent Lines of Code** | Lines from remote agent | | **CLI Agent Lines of Code** | Lines from CLI agent | ## Data Export Export your usage data for custom analysis, reporting, or integration with other tools: * **CSV Download** - Export all user statistics to a CSV file * **Filename Format** - `user-feature-stats-YYYY-MM-DD-to-YYYY-MM-DD.csv` * **Complete Data** - Includes all columns from the user statistics table ## Mobile Experience The dashboard is fully optimized for mobile devices with: * Card-based layout for easy viewing on smaller screens * Mobile sort selector dropdown for choosing sort column and direction * Responsive pagination controls adapted for touch interfaces * All key metrics and data accessible on any device ## Getting Help If you have questions about the Enterprise Dashboard or need assistance interpreting your usage data: Reach out to your sales representative for strategic guidance Get technical support at support.augmentcode.com ## Related Resources Programmatic access to usage metrics via REST API Detailed API endpoint documentation # ACP Mode Source: https://docs.augmentcode.com/cli/acp/agent Auggie is a fully compatible Agent Client Protocol (ACP) agent enabling you to bring the power of Augment to any compatible client. ## About ACP Mode [Agent Client Protocol](https://agentclientprotocol.com/overview/introduction) (ACP) is an open protocol that provides a standardized way to connect AI agents to different text editors, IDEs, and other tools. ACP mode uses JSON-RPC over standard input and output to communicate between the agent and the client. You can see a [overview of the protocol](https://agentclientprotocol.com/protocol/overview) to learn more. ## Using ACP Mode To use Auggie in ACP mode, you need to pass the `--acp` flag when starting Auggie. You can pass additional [command-line arguments](/cli/reference) to set the model, authentication, and other options. ```sh theme={null} auggie --acp ``` To use Auggie in a ACP-compatible client, you need to configure the client to launch Auggie with the `--acp` flag and follow the client-specific instructions. See the [ACP Clients](/cli/acp/clients) page for more details. ## Compatibility ACP is an emerging protocol and is in active development. Not all features available in interactive mode are supported in ACP mode. We are looking forward to working with the community to add support for more features in the future. # ACP Clients Source: https://docs.augmentcode.com/cli/acp/clients Configure Auggie to run in any Agent Client Protocol (ACP) compatible client like Zed, Neovim, or Emacs. ## About ACP Clients [Agent Client Protocol](https://agentclientprotocol.com/overview/introduction) (ACP) is an open protocol that provides a standardized way to connect AI agents to different text editors, IDEs, and other tools. Auggie is a fully ACP compatible agent enabling you to bring the power of Augment to editors like Zed, Neovim, or Emacs. See a [full list of supported clients](https://agentclientprotocol.com/overview/clients) in the ACP docs. ## Prerequisites * Auggie CLI [installed and configured](/cli/setup-auggie/install-auggie-cli) * Login to Augment with `auggie login` * A compatible ACP client ## Client configuration If you have an ACP client that you would like to have listed here, please [open an issue](https://github.com/augmentcode/auggie/issues/new) and we'll be happy to add it. ### Zed We recommend installing and configuring Auggie in [Zed](https://zed.dev/) using the [Auggie extension](https://zed.dev/extensions/auggie). If you want to configure Auggie manually through Zed's settings, you can use the following configuration. You can pass additional [command-line arguments](/cli/reference) to Auggie by adding them to the `args` array or use alternative [authentication methods](/cli/setup-auggie/authentication) by passing environment variables in the `env` object. ``` { "agent_servers": { "Auggie CLI": { "command": "auggie", "args": ["--acp"], "env": {} } } } ``` ### JetBrains We recommend installing and configuring Augment in [JetBrains IDEs](/jetbrains/setup-augment/install-jetbrains-ides) using the [Augment extension](https://plugins.jetbrains.com/plugin/24072-augment-ai-coding-assistant-for-professionals). To use Auggie with JetBrains IDEs, you can configure it in your IDE settings. You can pass additional [command-line arguments](/cli/reference) to Auggie by adding them to the `args` array or use alternative [authentication methods](/cli/setup-auggie/authentication) by passing environment variables in the `env` object. ```json theme={null} { "agent_servers": { "Auggie CLI": { "command": "auggie", "args": [ "--acp" ], "env": {} } } } ``` ### Neovim To use Auggie with Neovim, you can use one of the following plugins: #### [**Avante.nvim**](https://github.com/yetone/avante.nvim) Add the following to your lazy.nvim configuration: ```lua theme={null} { "yetone/avante.nvim", event = "VeryLazy", build = "make", dependencies = { "nvim-lua/plenary.nvim", "MunifTanjim/nui.nvim", }, opts = { provider = "auggie-acp", acp_providers = { ["auggie-acp"] = { command = "auggie", args = { "--acp" }, }, }, behaviour = { auto_suggestions = false, auto_set_highlight_group = true, auto_set_keymaps = true, auto_apply_diff_after_generation = false, support_paste_from_clipboard = false, }, }, }, ``` #### [**Agentic.nvim**](https://github.com/carlos-algms/agentic.nvim) Add the following to your lazy.nvim configuration: ```lua theme={null} { "carlos-algms/agentic.nvim", opts = { provider = "auggie-acp", acp_providers = { ["auggie-acp"] = { command = "auggie", args = { "--acp" }, }, }, }, } ``` #### [**CodeCompanion.nvim**](https://github.com/olimorris/codecompanion.nvim) Add the following to your lazy.nvim configuration: ```lua theme={null} { "olimorris/codecompanion.nvim", opts = { strategies = { chat = { adapter = "auggie_cli", }, inline = { adapter = "auggie_cli", }, }, }, } ``` ### Emacs To use Auggie with emacs, you can use one of the following plugins: * [agent-shell.el](https://github.com/xenodium/agent-shell) # Using Auggie with Automation Source: https://docs.augmentcode.com/cli/automation/overview Auggie was designed to not just be a powerful agent to write code, but to automate all the tasks that are needed to build software at scale. Non-interactive mode is an additional feature that may be disabled if it is not included in your agreement (enterprise). ## About automation Auggie was purpose built to integrate into your software development stack. From using Auggie in your local development workflows to automatically running Auggie in your CI/CD pipelines, Auggie can help you build better software faster. ### Example use cases * **Code reviews**: Review code changes and provide feedback. * **Issue triage**: Triage incoming issues and route them to the appropriate team or individual. * **Automate on-call**: Respond to incoming alerts and create an assessment plan. * **Exception management**: Analyze incoming exceptions and create tickets. ## Integrating with your workflows In order to use Auggie in your systems, like a CI/CD pipeline, you'll need to install Auggie CLI, provide a session token, and write an instruction that will be used alongside any data from your system you want to include. ### Installation Auggie can be [installed](/cli/setup-auggie/install-auggie-cli) directly from npm anywhere you can run Node 22 or later including VMs, serverless functions, and containers. You will also need to install any dependencies for defined MCP servers in those environments. ```sh theme={null} npm install -g @augmentcode/auggie ``` ### Authentication Session tokens are associated with the user that created it, and Auggie will run with integration configurations from that user. See [Authentication](/cli/setup-auggie/authentication) for full details. You can override the user's GitHub configuration by passing `--github-api-token `. ```sh theme={null} # First, login to Augment with the CLI auggie login # Next, output your token auggie tokens print # Then, pass your token to auggie AUGMENT_SESSION_AUTH='' auggie --print "Summarize the build failure" ``` ### Scripts and pipes Auggie runs as a subprocess, so it can be used in any shell script. It can be used just like any command-line tool that follows the Unix philosophy. You can pipe data into Auggie and then pipe the response to another command. Data passed into Auggie through stdin will be used as context in addition to the instruction. ```sh theme={null} # Pipe data through stdin cat build.log | auggie --print "Summarize the failure and open a Linear ticket" # Provide input from a file auggie --compact --instruction /path/to/instruction.md < build.log ``` ## GitHub Actions GitHub Actions makes it easy to connect Auggie to other parts of your software development pipeline, from linting, testing, build, and deploy. We've built a [simple wrapper for Auggie](https://github.com/augmentcode/augment-agent) that enables you to integrate with GitHub Action workflows and build custom tooling around Auggie. Follow the instructions to [configure Augment Agent](https://github.com/augmentcode/augment-agent/blob/main/README.md) in GitHub Actions and explore the [example-workflows](https://github.com/augmentcode/augment-agent/tree/main/example-workflows) directory to get started. ### Ready to use workflows Get started using Auggie in GitHub Actions immediately by following the instructions for setup and deploy in one of the following workflows, or use the `/github-workflow` wizard in Auggie to have the workflows generated for you. * [PR Description](https://github.com/augmentcode/describe-pr): This action automatically analyzes your PR changes and generates comprehensive, informative descriptions. * [PR Review](https://github.com/augmentcode/review-pr): This action automatically analyzes your PR changes and generates comprehensive, informative reviews Need even more help building GitHub Actions? May we suggest asking Auggie. ```sh theme={null} auggie "Help me build a GitHub Action to..." ``` # Service Accounts Source: https://docs.augmentcode.com/cli/automation/service-accounts ## About Service Accounts provide non-human identities for automation use cases to make API requests to the Augment backend through Auggie CLI. They decouple automation tasks from using individual user accounts and enable per-automation task token lifecycle management. ## Managing Service Accounts Service Accounts can be managed by navigating to [app.augmentcode.com/settings/service-accounts](https://app.augmentcode.com/settings/service-accounts) and logging in. Service accounts are only available to [Enterprise plan](https://augmentcode.com/pricing) customers. Service accounts can only be managed by the Administrator of the Enterprise Plan. ### Creating a Service Account To create a new service account, click the "New Service Account" button. You will be prompted to enter a name and an optional description for the service account. The account name must be unique within your organization. ### Creating API tokens Once you've created a service account, you can create API tokens for it by clicking the "Add API token" button next to the service account name in the list of service accounts. You will be prompted to enter a name for the API token which must be unique amongst the tokens for this service account. Once you've created a token, you will be given a one time opportunity to retrieve the token value by either: * Copying the token value directly or using the "Copy token" button **OR** * Downloading a `session.json` file that is ready to use with Auggie CLI. API tokens for service accounts don't have an expiration date and need to be manually revoked if they are no longer needed. ### Deleting Service Accounts and API tokens API tokens can be revoked by selecting "Revoke" from the triple dot menu next to the token name in the service account list. Note that revoking a token is a permanent action and cannot be undone. Any existing Auggie CLI automation sessions using the token will be disrupted. Service accounts can be deleted by clicking "Manage" next to the service account name in the service account list, and then clicking "Delete Account" from the dialog that appears. Note that deleting a service account will also delete all the associated API tokens. ## Using API tokens with Auggie CLI In order to use a service account API token with Auggie CLI, you need to edit the `session.json` file stored under `~/.augment`. If you've downloaded a `session.json` file after creating the API token, you can simply replace the existing `session.json` file with the new one. If you've only copied the token value, you need to edit the `session.json` file with the following content and replace the `accessToken` value with the new token value. ``` { "accessToken": "", "tenantURL": "", "scopes": [ "read", "write" ] } ``` The correct `tenantURL` value for your organization is displayed on top of the service account list in the management UI. ## Best Practices * Use a separate service account per automation task. This will allow you to manage token lifecycle and monitor credit usage per automation task. * Use the ability to create multiple tokens under a service account to rotate tokens when needed. Create a new API token, update the automation tasks to use the new token, and revoke the old token once all automation tasks have been updated. # Automatic Updates Source: https://docs.augmentcode.com/cli/autoupgrade Learn how to manage and troubleshoot Auggie CLI's automatic update feature. ## How Automatic Updates Work Auggie CLI automatically updates itself when running in interactive mode to ensure you always have the latest features and bug fixes. ### Interactive Mode (TUI) * Automatically checks npm for newer versions when you start Auggie * Performs upgrades without prompting to minimize interruption * Shows a brief notification when an update is applied * Best-effort approach - continues running even if update fails ### Non-interactive Mode (Print/Text Mode) * Auto-update is completely disabled * Respects version pinning in automation scripts ## Disabling Automatic Updates Set the `AUGMENT_DISABLE_AUTO_UPDATE` environment variable to `1` to disable automatic updates. ### Environment Variable (Recommended for Scripts) ```bash theme={null} # Disable for current session export AUGMENT_DISABLE_AUTO_UPDATE=1 # Disable for single command AUGMENT_DISABLE_AUTO_UPDATE=1 auggie --print "Your instruction here" ``` ## Manual Updates You can manually update Auggie CLI by running the following command. ```bash theme={null} auggie upgrade ``` # Custom Slash Commands Source: https://docs.augmentcode.com/cli/custom-commands Create and manage custom slash commands for frequently-used prompts and workflows. ## About Custom Slash Commands Custom slash commands let you create reusable prompts stored as Markdown files that Auggie can run. You can organize commands by scope (workspace or user) and use directory structures for namespacing. ### Syntax ``` / [arguments] ``` ### Parameters | Parameter | Description | | :--------------- | :--------------------------------------- | | `` | Name derived from the Markdown filename | | `[arguments]` | Optional arguments passed to the command | ## Command Types and Locations Custom commands are stored in markdown files and can be placed in multiple locations with a specific order of precedence: ### Command Locations (in order of precedence) 1. **User Commands**: `~/.augment/commands/.md` (user) 2. **Workspace Commands**: `./.augment/commands/.md` (workspace) 3. **Claude Code Commands**: `./.claude/commands/.md` (.claude) ### User Commands Commands available across all your projects. These are user-wide and persist across different workspaces. **Location**: `~/.augment/commands/` ```sh theme={null} # Create a global command mkdir -p ~/.augment/commands echo "Review this code for security vulnerabilities:" > ~/.augment/commands/security-review.md ``` ### Workspace Commands Commands stored in your repository and shared with your team. These are workspace-specific and can be committed to version control. **Location**: `./.augment/commands/` ```sh theme={null} # Create a workspace command mkdir -p .augment/commands echo "Analyze this code for performance issues and suggest optimizations:" > .augment/commands/optimize.md ``` ### Claude Code Compatibility Auggie automatically detects and supports commands from `./.claude/commands/` for compatibility with existing Claude Code setups. This allows teams already using Claude Code to continue using their existing command libraries without modification. **Location**: `./.claude/commands/` and `~/.claude/commands/` **Migration**: While `./.claude/commands/` is supported for compatibility, we recommend migrating to `./.augment/commands/` for new projects to maintain consistency with Auggie's naming conventions. ## Features ### Namespacing Organize commands in subdirectories. Commands from nested directories can be accessed using the `namespace:command` syntax, where the namespace corresponds to the subdirectory name. For example, a file at `.augment/commands/frontend/component.md` creates the command `/frontend:component`. Conflicts between user and workspace level commands are not supported and will be defined in order of precedence above. ### Arguments Pass dynamic values to commands. ```markdown theme={null} # Command definition echo 'Fix issue following our coding standards' > .augment/commands/fix-issue.md # Usage > /fix-issue 123 ``` ### Frontmatter Command files support frontmatter for metadata: | Frontmatter | Purpose | Default | | :-------------- | :------------------------------------------------------------------------- | :---------------------------------- | | `description` | Brief description of the command | Uses the first line from the prompt | | `argument-hint` | Expected arguments format that will be displayed after typing in a command | None | | `model` | Specify the model to run this command with (overrides the CLI default) | Uses the CLI default model | **File**: `~/.augment/commands/deploy-staging.md` ```markdown theme={null} --- description: Deploy the application to staging with health checks argument-hint: [branch-name] model: gpt-4o --- Deploy the application to the staging environment: 1. Run all tests to ensure code quality 2. Build the application for production 3. Deploy to staging server 4. Run health checks to verify deployment 5. Send notification to team channel ``` ## Command Line Execution We also provide the ability to execute custom commands from the command line using the `auggie command ` or list them with `auggie command list`. For complete command-line reference, see [CLI Reference for Custom Commands](/cli/reference#custom-commands). ```sh theme={null} # Execute a custom command auggie command deploy-staging # List all available commands (including custom ones) auggie command list ``` Custom commands appear in the help output with their descriptions: ``` Available custom commands: auggie command deploy-staging # Deploy the application to staging auggie command security-review # Review code for security vulnerabilities ``` ## Example Commands For ready-to-use examples of custom slash commands, including code review templates, bug fix guides, and feature implementation plans, see: **[Custom Commands Examples](/cli/custom-commands-examples)** ## Best Practices 1. **Use kebab-case naming** for command names (e.g., `deploy-staging`, `run-tests`) 2. **Keep names descriptive** but concise, avoiding spaces and special characters 3. **Use meaningful prefixes** for related commands (e.g., `deploy-staging`, `deploy-production`) 4. **Include clear descriptions** in frontmatter for better discoverability 5. **Break complex workflows** into numbered steps for clarity 6. **Use user commands** (`~/.augment/commands/`) for personal workflows across all projects 7. **Use workspace commands** (`./.augment/commands/`) for team-shared, project-specific tasks 8. **Organize with subdirectories** for related command groups using namespacing 9. **Document command purpose** and expected outcomes clearly 10. **Version your commands** when making significant changes ## See Also * [Custom Commands Examples](/cli/custom-commands-examples) - Ready-to-use command templates and examples * [Interactive Mode Slash Commands](/cli/interactive#slash-commands) - Learn about Auggie's interactive terminal features * [CLI Reference for Custom Commands](/cli/reference#custom-commands) - Complete reference for command-line flags # Custom Slash Commands Examples Source: https://docs.augmentcode.com/cli/custom-commands-examples Ready-to-use examples of custom slash commands for common development workflows. ## Example Commands Here are some practical examples of custom slash commands you can use in your projects: ```markdown theme={null} --- description: Perform a comprehensive code review argument-hint: [file-path] --- Please perform a comprehensive code review of the specified file or current changes, focusing on: 1. **Code Quality**: Check for readability, maintainability, and adherence to best practices 2. **Security**: Look for potential security vulnerabilities 3. **Performance**: Identify potential performance issues 4. **Testing**: Suggest areas that need test coverage 5. **Documentation**: Check if code is properly documented $ARGUMENTS ``` ```markdown theme={null} --- description: Generate a structured bug fix approach argument-hint: [bug-description] --- Help me fix this bug: $ARGUMENTS Please provide: 1. Root cause analysis 2. Step-by-step fix approach 3. Testing strategy 4. Prevention measures for similar issues ``` ```markdown theme={null} --- description: Create implementation plan for new features argument-hint: [feature-description] --- Create a detailed implementation plan for: $ARGUMENTS Include: - Technical requirements - Architecture considerations - Implementation steps - Testing approach - Documentation needs ``` ```markdown theme={null} --- description: Perform security analysis on code argument-hint: [file-path] --- Perform a security review of: $ARGUMENTS Focus on: 1. **Input validation** and sanitization 2. **Authentication** and authorization checks 3. **Data exposure** and privacy concerns 4. **Injection vulnerabilities** (SQL, XSS, etc.) 5. **Cryptographic** implementations 6. **Dependencies** with known vulnerabilities Provide specific recommendations for any issues found. ``` ```markdown theme={null} --- description: Analyze and optimize code performance argument-hint: [file-path] --- Analyze the performance of: $ARGUMENTS Please examine: 1. **Algorithm complexity** and efficiency 2. **Memory usage** patterns 3. **Database queries** and optimization opportunities 4. **Caching** strategies 5. **Network requests** and bundling 6. **Rendering performance** (for frontend code) Suggest specific optimizations with expected impact. ``` ```markdown theme={null} --- description: Generate comprehensive documentation argument-hint: [file-path] --- Generate documentation for: $ARGUMENTS Include: 1. **Overview** and purpose 2. **API reference** with parameters and return values 3. **Usage examples** with code snippets 4. **Configuration options** if applicable 5. **Error handling** and troubleshooting 6. **Dependencies** and requirements Format as clear, structured markdown. ``` ```markdown theme={null} --- description: Generate comprehensive test cases argument-hint: [file-path] --- Generate test cases for: $ARGUMENTS Create tests covering: 1. **Happy path** scenarios 2. **Edge cases** and boundary conditions 3. **Error handling** and exceptions 4. **Integration points** with other components 5. **Performance** considerations 6. **Security** edge cases Use appropriate testing framework conventions and include setup/teardown as needed. ``` ## How to Add Commands to Your Project To use these custom slash commands in your project, you need to save them in the `.augment/commands/` directory: ### Step 1: Create the Commands Directory First, create the `.augment/commands/` directory in your project root if it doesn't exist: ```bash theme={null} mkdir -p .augment/commands ``` ### Step 2: Save Command Files Save each command as a separate `.md` file in the `.augment/commands/` directory. For example: ```bash theme={null} # Save the code review command cat > .augment/commands/code-review.md << 'EOF' --- description: Perform a comprehensive code review argument-hint: [file-path] --- Please perform a comprehensive code review of the specified file or current changes, focusing on: 1. **Code Quality**: Check for readability, maintainability, and adherence to best practices 2. **Security**: Look for potential security vulnerabilities 3. **Performance**: Identify potential performance issues 4. **Testing**: Suggest areas that need test coverage 5. **Documentation**: Check if code is properly documented $ARGUMENTS EOF ``` ### Step 3: Use Your Commands Once saved, your custom commands become available as slash commands in Augment: ``` /code-review src/components/Button.tsx /bug-fix "Login form validation not working" /security-review auth/middleware.js ``` ### Directory Structure Your project structure should look like this: ``` your-project/ ├── .augment/ │ └── commands/ │ ├── code-review.md │ ├── bug-fix.md │ ├── security-review.md │ └── performance-optimization.md ├── src/ └── package.json ``` ## Usage Tips * **Save these templates** in your `.augment/commands/` directory * **Customize the prompts** to match your team's coding standards and practices * **Add project-specific context** to make the commands more effective * **Combine commands** by referencing outputs from one command in another * **Use meaningful filenames** like `code-review.md`, `bug-fix.md`, etc. * **Version control your commands** by committing the `.augment/commands/` directory to your repository ## Creating Your Own Examples When creating custom commands, consider these patterns: 1. **Start with a clear description** in the frontmatter 2. **Use argument hints** to guide users on expected inputs 3. **Structure your prompts** with numbered lists or bullet points 4. **Include specific instructions** for the type of analysis or output you want 5. **Reference the `$ARGUMENTS` variable** where user input should be inserted ## See Also * [Custom Slash Commands](/cli/custom-commands) - Learn how to create and manage custom commands * [CLI Reference for Custom Commands](/cli/reference#custom-commands) - Complete command-line reference for custom commands # Hooks Source: https://docs.augmentcode.com/cli/hooks Intercept and control tool execution with custom scripts ## Overview Hooks allow you to intercept tool execution at specific lifecycle events and run custom scripts. This enables powerful workflows like: * **Security auditing** - Block dangerous commands or log sensitive file access * **Policy enforcement** - Enforce coding standards or restrict production access * **Logging** - Track tool usage for compliance and analytics * **Integration** - Connect with external systems and workflows Hooks execute automatically when specific events occur during agent operation, giving you fine-grained control over tool execution and session lifecycle. ## Configuration Hooks are configured in `settings.json` files: ### Settings File Locations | Location | Platform | Supported By | Description | | :------------------------------------- | :---------- | :-------------------- | :------------------------------------------------- | | `/etc/augment/settings.json` | Linux/macOS | CLI, VSCode, IntelliJ | System-wide settings for enterprise/admin policies | | `C:\ProgramData\Augment\settings.json` | Windows | CLI, VSCode, IntelliJ | System-wide settings for enterprise/admin policies | | `~/.augment/settings.json` | All | CLI, VSCode, IntelliJ | User-level settings | System-level settings (`/etc/augment/settings.json`) take precedence and cannot be overridden by user settings. `PreToolUse`, `PostToolUse`, and `Stop` hooks run **synchronously** - the agent waits for them to complete before proceeding. Use appropriate timeouts to prevent long delays. Note that only `PreToolUse` can block tool execution; `Stop` can block the agent from finishing (via `decision: "block"`), but `PostToolUse` cannot block anything. ### Structure Hooks are organized by event type with optional matchers: ```json theme={null} { "hooks": { "PreToolUse": [ { "matcher": "launch-process", "hooks": [ { "type": "command", "command": "/etc/augment/hooks/validate-command.sh", "timeout": 5000 } ] } ] } } ``` **Configuration fields:** | Field | Description | | :--------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `matcher` | Pattern to match tool names (case-sensitive). Supports regex patterns. Optional for `PreToolUse` and `PostToolUse` (defaults to `".*"` to match all tools). Not used for session events (`SessionStart`, `SessionEnd`, `Stop`). | | `hooks` | Array of hook handlers to execute when the pattern matches. | | `type` | Hook execution type - currently only `"command"` is supported. | | `command` | Path to the shell script to execute (must be a `.sh` file). | | `timeout` | *(Optional)* Timeout in milliseconds (default: 60000ms). | | `metadata` | *(Optional)* Configuration for additional context fields - see [Hook Metadata](#hook-metadata-configuration). | **Matcher pattern examples:** | Pattern | Description | | :-------------------------------- | :---------------------------------------- | | `"launch-process"` | Match a specific tool | | `"str-replace-editor\|save-file"` | Match multiple tools using regex OR | | `".*"` | Match all tools | | `"mcp:*"` | Match all MCP tools (special case) | | `"mcp:.*_my-server$"` | Match any tool from a specific MCP server | For session events (`SessionStart`, `SessionEnd`, `Stop`) that don't require matchers: ```json theme={null} { "hooks": { "SessionStart": [ { "hooks": [ { "type": "command", "command": "/path/to/setup-script.sh" } ] } ] } } ``` ### Script Requirements Hook scripts must: 1. **Use `.sh` file extension** - Only shell scripts are supported 2. **Be executable** - Run `chmod +x your-hook.sh` 3. **Have a valid shebang** - First line must specify the interpreter You can use any interpreter (Python, Node.js, Ruby, etc.) by specifying it in the shebang line. The file extension must still be `.sh`. ```bash theme={null} #!/usr/bin/env python3 # Python script with .sh extension - uses Python interpreter via shebang import sys, json event_data = json.load(sys.stdin) # ... your Python code ``` ## Hook Events ### PreToolUse Runs **before** a tool executes. Can block tool execution. **Common tool names:** | Tool | Description | | :------------------- | :----------------- | | `launch-process` | Shell commands | | `view` | File reading | | `str-replace-editor` | File editing | | `save-file` | File writing | | `remove-files` | File deletion | | `web-fetch` | Fetch web content | | `web-search` | Web search | | `codebase-retrieval` | Codebase search | | `github-api` | GitHub integration | | `linear` | Linear integration | Use [PreToolUse output control](#pretooluse-output) to block tools or modify inputs. ### PostToolUse Runs immediately **after** a tool completes. Can provide feedback to the agent but cannot block execution. Recognizes the same tool names as PreToolUse. Includes `tool_output` and `tool_error` in the event data. ### Stop Runs when the agent stops responding, whether from normal completion or user interrupt. The `agent_stop_cause` field indicates why the agent stopped (e.g., `"end_turn"` or `"interrupted"`). Can block the agent from stopping (useful for requiring tests before completion). ### SessionStart Runs when Auggie starts a new session. Useful for: * Loading development context (git status, open issues) * Installing dependencies * Setting up environment variables ### SessionEnd Runs when an Auggie session ends. Useful for: * Cleanup tasks * Logging session statistics * Saving session state ## Hook Input Hooks receive event data via **stdin** as a JSON object. The structure varies by event type, but all events share common base fields. ### Common Fields (All Events) These fields are present in **every** hook event: | Field | Type | Description | | :---------------- | :-------- | :--------------------------------------------------------------------------------------------- | | `hook_event_name` | string | The type of event: `"PreToolUse"`, `"PostToolUse"`, `"Stop"`, `"SessionStart"`, `"SessionEnd"` | | `conversation_id` | string | Unique identifier for the current conversation | | `workspace_roots` | string\[] | List of workspace root directories (usually contains one path) | ### Event-Specific Fields #### PreToolUse / PostToolUse Events Tool events include information about the tool being executed: | Field | Type | Availability | Description | | :------------- | :--------- | :--------------- | :------------------------------------------------------------------------------------------------------------------------------ | | `tool_name` | string | Always | Name of the tool (e.g., `"launch-process"`, `"str-replace-editor"`). Use to filter which tools your hook applies to. | | `tool_input` | object | Always | Input parameters passed to the tool. **Critical for security hooks** - extract and validate specific parameters. | | `tool_output` | string? | PostToolUse only | Output returned by the tool (if successful). Use for auditing or providing context to the agent. | | `tool_error` | string? | PostToolUse only | Error message if tool execution failed. Use to detect failures and inject troubleshooting tips. | | `file_changes` | object\[]? | PostToolUse only | File changes for `save-file`, `str-replace-editor`, `remove-files`. Includes `path`, `changeType`, `content`, and `oldContent`. | **Example: Extracting tool-specific parameters** ```bash Bash - Extract Bash command theme={null} #!/usr/bin/env bash EVENT_DATA=$(cat) TOOL_NAME=$(echo "$EVENT_DATA" | jq -r '.tool_name') if [[ "$TOOL_NAME" == "launch-process" ]]; then # Extract the command being executed COMMAND=$(echo "$EVENT_DATA" | jq -r '.tool_input.command') echo "Command: $COMMAND" >&2 # Check for dangerous patterns if echo "$COMMAND" | grep -qE "rm -rf|sudo|curl.*sh"; then echo "Blocked dangerous command" >&2 exit 2 fi fi exit 0 ``` ```python Python - Extract file path theme={null} #!/usr/bin/env python3 import sys, json event_data = json.load(sys.stdin) if event_data.get('tool_name') == 'str-replace-editor': path = event_data.get('tool_input', {}).get('path', '') if any(p in path for p in ['.env', 'secrets', 'credentials']): print(f"[AUDIT] Sensitive file: {path}", file=sys.stderr) sys.exit(0) ``` **Example: Using `tool_output` for context (PostToolUse)** ```bash Bash theme={null} #!/usr/bin/env bash EVENT_DATA=$(cat) TOOL_NAME=$(echo "$EVENT_DATA" | jq -r '.tool_name') TOOL_OUTPUT=$(echo "$EVENT_DATA" | jq -r '.tool_output // ""') if [[ "$TOOL_NAME" == "launch-process" ]] && echo "$TOOL_OUTPUT" | grep -q "test.*passed"; then # Tests passed - inject success context cat << EOF { "hookSpecificOutput": { "hookEventName": "PostToolUse", "additionalContext": "All tests passed successfully!" } } EOF fi exit 0 ``` ```python Python theme={null} #!/usr/bin/env python3 import sys import json event_data = json.load(sys.stdin) tool_name = event_data.get('tool_name', '') tool_output = event_data.get('tool_output', '') if tool_name == 'launch-process' and 'test' in tool_output and 'passed' in tool_output: # Tests passed - inject success context output = { "hookSpecificOutput": { "hookEventName": "PostToolUse", "additionalContext": "All tests passed successfully!" } } print(json.dumps(output)) sys.exit(0) ``` **Example: Using `tool_error` for troubleshooting (PostToolUse)** ```bash Bash theme={null} #!/usr/bin/env bash EVENT_DATA=$(cat) TOOL_ERROR=$(echo "$EVENT_DATA" | jq -r '.tool_error // ""') if [[ -n "$TOOL_ERROR" ]] && echo "$TOOL_ERROR" | grep -q "permission denied"; then # Inject troubleshooting tip cat << EOF { "hookSpecificOutput": { "hookEventName": "PostToolUse", "additionalContext": "Permission denied error detected. Try running with appropriate permissions or check file ownership." } } EOF fi exit 0 ``` ```python Python theme={null} #!/usr/bin/env python3 import sys import json event_data = json.load(sys.stdin) tool_error = event_data.get('tool_error', '') if tool_error and 'permission denied' in tool_error.lower(): output = { "hookSpecificOutput": { "hookEventName": "PostToolUse", "additionalContext": "Permission denied error detected. Try with appropriate permissions." } } print(json.dumps(output)) sys.exit(0) ``` **Example: Using `file_changes` for audit logging (PostToolUse)** The `file_changes` field is populated for file-modifying tools and includes the old content for edits: ```json theme={null} { "hook_event_name": "PostToolUse", "conversation_id": "conv-xyz789", "tool_name": "str-replace-editor", "tool_input": { "path": "src/auth.ts", "old_str_1": "...", "new_str_1": "..." }, "file_changes": [ { "path": "src/auth.ts", "changeType": "edit", "content": "// New code content here...", "oldContent": "// Old code that was replaced..." } ] } ``` ```bash theme={null} #!/usr/bin/env bash EVENT_DATA=$(cat) echo "$EVENT_DATA" | jq -c '.file_changes[]?' | while read -r change; do echo "[AUDIT] $(echo $change | jq -r '.changeType'): $(echo $change | jq -r '.path')" >&2 done exit 0 ``` #### SessionStart / SessionEnd Events Session events have no additional fields beyond the common base fields. **Example SessionStart event:** ```json theme={null} { "hook_event_name": "SessionStart", "conversation_id": "conv-xyz789", "workspace_roots": ["/Users/username/project"] } ``` #### Stop Event Stop events include information about why the agent stopped: | Field | Type | Description | | :----------------: | :----: | :---------------------------------------------------------: | | `agent_stop_cause` | string | Why the agent stopped (e.g., `"end_turn"`, `"interrupted"`) | **Example Stop event:** ```json theme={null} { "hook_event_name": "Stop", "conversation_id": "conv-xyz789", "workspace_roots": ["/Users/username/project"], "agent_stop_cause": "end_turn" } ``` ### Metadata-Based Fields When hooks declare metadata options in their configuration, additional fields are included in the event data: #### `context` field (when `includeUserContext: true`) Available for: **All event types** ```json theme={null} { "context": { "userEmail": "user@example.com", "modelName": "Claude Opus 4.5", "toolVersion": "0.6.0", "timestamp": "2025-01-15T10:30:00-08:00" } } ``` **How to use:** * **`userEmail`**: Identify which user triggered the hook. Use for user-specific policies or analytics. * **`modelName`**: AI model display name (e.g., "Claude Opus 4.5", "Sonnet-3.7"). Use for model-specific behavior. * **`toolVersion`**: CLI or VSCode extension version (e.g., "0.6.0"). Use for debugging or version-specific behavior. * **`timestamp`**: ISO 8601 timestamp. Use for auditing and analytics. **Example: User-specific permissions** ```bash Bash theme={null} #!/usr/bin/env bash EVENT_DATA=$(cat) USER_EMAIL=$(echo "$EVENT_DATA" | jq -r '.context.userEmail // ""') TOOL_NAME=$(echo "$EVENT_DATA" | jq -r '.tool_name') COMMAND=$(echo "$EVENT_DATA" | jq -r '.tool_input.command // ""') # Only allow deployments for specific users if [[ "$TOOL_NAME" == "launch-process" ]] && echo "$COMMAND" | grep -q "deploy"; then if [[ "$USER_EMAIL" != "admin@example.com" ]]; then echo "Only admins can deploy" >&2 exit 2 fi fi exit 0 ``` ```python Python theme={null} #!/usr/bin/env python3 import sys import json event_data = json.load(sys.stdin) user_email = event_data.get('context', {}).get('userEmail', '') # Only allow deployments for specific users tool_name = event_data.get('tool_name', '') command = event_data.get('tool_input', {}).get('command', '') if tool_name == 'launch-process' and 'deploy' in command: if user_email != 'admin@example.com': print("Only admins can deploy", file=sys.stderr) sys.exit(2) sys.exit(0) ``` #### `mcp_metadata` field (when `includeMCPMetadata: true`) Available for: **PreToolUse and PostToolUse only** ```json theme={null} { "mcp_metadata": { "timestamp": "2025-01-15T10:30:00-08:00", "mcpDecision": "yes", "mcpTotalToolsCount": 215, "mcpExecutedToolName": "search_my-server", "mcpExecutedToolServerName": "my-server", "mcpExecutedToolServerToolsCount": 6 } } ``` **How to use:** * **`timestamp`**: ISO 8601 timestamp. Use for auditing and analytics. * **`mcpDecision`**: Whether this is an MCP tool (`"yes"`) or native tool (`"no"`). * **`mcpTotalToolsCount`**: Total MCP tools available across all servers. * **`mcpExecutedToolName`**: Full MCP tool name (e.g., `"search_my-server"`). * **`mcpExecutedToolServerName`**: MCP server name (e.g., `"my-server"`). * **`mcpExecutedToolServerToolsCount`**: Tools available from the executed server. **Example: MCP-specific rate limiting** ```bash Bash theme={null} #!/usr/bin/env bash EVENT_DATA=$(cat) MCP_DECISION=$(echo "$EVENT_DATA" | jq -r '.mcp_metadata.mcpDecision // "no"') MCP_TOTAL=$(echo "$EVENT_DATA" | jq -r '.mcp_metadata.mcpTotalToolsCount // 0') # Block if too many MCP tools are enabled (security concern) if [[ "$MCP_DECISION" == "yes" ]] && [[ "$MCP_TOTAL" -gt 100 ]]; then echo "Too many MCP tools enabled ($MCP_TOTAL). Contact admin." >&2 exit 2 fi exit 0 ``` ```python Python theme={null} #!/usr/bin/env python3 # /etc/augment/hooks/mcp-limit.sh (Python via shebang) import sys import json event_data = json.load(sys.stdin) mcp_metadata = event_data.get('mcp_metadata', {}) mcp_decision = mcp_metadata.get('mcpDecision', 'no') mcp_total = mcp_metadata.get('mcpTotalToolsCount', 0) # Block if too many MCP tools are enabled (security concern) if mcp_decision == 'yes' and mcp_total > 100: print(f"Too many MCP tools enabled ({mcp_total}). Contact admin.", file=sys.stderr) sys.exit(2) sys.exit(0) ``` #### `conversation` field (when `includeConversationData: true`) Available for: **Stop event only** ```json theme={null} { "conversation": { "timestamp": "2025-01-15T10:30:00-08:00", "userPrompt": "Add error handling to the login function", "agentTextResponse": "I'll add comprehensive error handling...", "agentCodeResponse": [ { "path": "src/auth/login.ts", "changeType": "edit", "content": "export function login() { try { ... } catch (e) { ... } }" } ] } } ``` **How to use:** * **`timestamp`**: ISO 8601 timestamp. Use for auditing. * **`userPrompt`**: The user's original request. * **`agentTextResponse`**: Agent's explanation of what it did. * **`agentCodeResponse`**: Array of file changes. Each entry has: * `path`: File path modified * `changeType`: `"edit"`, `"create"`, or `"delete"` * `content`: New content (for edit/create only) **Example: Require tests before finishing** ```bash Bash theme={null} #!/usr/bin/env bash EVENT_DATA=$(cat) # Extract code changes CODE_RESPONSE=$(echo "$EVENT_DATA" | jq -r '.conversation.agentCodeResponse // []') # Check if any test files were modified TEST_FILES=$(echo "$CODE_RESPONSE" | jq -r '.[] | select(.path | test("test|spec")) | .path') if [[ -z "$TEST_FILES" ]]; then # No test files modified - block stop cat << EOF { "hookSpecificOutput": { "hookEventName": "Stop", "decision": "block", "reason": "Please add or update tests before finishing" } } EOF exit 0 fi exit 0 ``` ```python Python theme={null} #!/usr/bin/env python3 import sys import json import re event_data = json.load(sys.stdin) conversation = event_data.get('conversation', {}) code_response = conversation.get('agentCodeResponse', []) # Check if any test files were modified test_files = [ change['path'] for change in code_response if re.search(r'test|spec', change.get('path', '')) ] if not test_files: # No test files modified - block stop output = { "hookSpecificOutput": { "hookEventName": "Stop", "decision": "block", "reason": "Please add or update tests before finishing" } } print(json.dumps(output)) sys.exit(0) sys.exit(0) ``` ### Reading Hook Input ```bash Bash theme={null} #!/usr/bin/env bash # Read entire JSON from stdin EVENT_DATA=$(cat) # Extract fields using jq HOOK_EVENT=$(echo "$EVENT_DATA" | jq -r '.hook_event_name') TOOL_NAME=$(echo "$EVENT_DATA" | jq -r '.tool_name // ""') CONV_ID=$(echo "$EVENT_DATA" | jq -r '.conversation_id') echo "Event: $HOOK_EVENT, Tool: $TOOL_NAME, Conversation: $CONV_ID" ``` ```python Python theme={null} #!/usr/bin/env python3 import sys import json event_data = json.load(sys.stdin) hook_event = event_data['hook_event_name'] tool_name = event_data.get('tool_name', '') conv_id = event_data['conversation_id'] print(f"Event: {hook_event}, Tool: {tool_name}, Conversation: {conv_id}") ``` ## Hook Output and Communication Hooks communicate results through exit codes and output streams. The behavior depends on the exit code and the hook event type. ### Exit Codes * **Exit code 0**: Success - Hook completed successfully * **Exit code 2**: Blocking error - Prevents tool execution (PreToolUse only) * **Other exit codes**: Non-blocking error - Logged but execution continues ### Output Streams * **stdout**: Standard output from the hook * **stderr**: Error output from the hook ### Communication Matrix The following table shows how hook output is handled based on exit code and event type: | Exit Code | Event Type | Output Stream | Shown To | Behavior | | :-------: | ------------ | :-----------: | -------- | :-----------------------------------------------------: | | 2 | PreToolUse | stderr | Agent | Blocks tool execution, agent sees why it was blocked | | 2 | SessionStart | stderr | User | Hook failed at startup, user needs to fix configuration | | 0 | PreToolUse | stderr | User | Warning message shown to user | | 0 | PreToolUse | stdout | User | Success message shown to user | | 0 | PostToolUse | stderr | User | Warning message shown to user | | 0 | PostToolUse | stdout | User | Success message shown to user | | 0 | SessionStart | stdout | Agent | Inject context at session start | | 0 | SessionEnd | stdout | User | Show completion message | | Other | Any | stderr | User | Error logged, execution continues | **Key Principle**: Exit code 2 with PreToolUse blocks the tool and shows stderr to the agent (so it knows why). Exit code 0 shows output to the user. SessionStart stdout is special - it injects context for the agent. ### PreToolUse Output **Blocking a tool (exit code 2):** ```bash Bash theme={null} #!/usr/bin/env bash EVENT_DATA=$(cat) COMMAND=$(echo "$EVENT_DATA" | jq -r '.tool_input.command // ""') if echo "$COMMAND" | grep -qE "rm -rf|sudo"; then echo "Blocked dangerous command: $COMMAND" >&2 exit 2 # Blocks tool, stderr shown to agent fi exit 0 # Allow tool to proceed ``` ```python Python theme={null} #!/usr/bin/env python3 import sys import json import re event_data = json.load(sys.stdin) command = event_data.get('tool_input', {}).get('command', '') if re.search(r'rm -rf|sudo', command): print(f"Blocked dangerous command: {command}", file=sys.stderr) sys.exit(2) # Blocks tool, stderr shown to agent sys.exit(0) # Allow tool to proceed ``` **Warning message (exit code 0):** ```bash Bash theme={null} #!/usr/bin/env bash EVENT_DATA=$(cat) FILE_PATH=$(echo "$EVENT_DATA" | jq -r '.tool_input.path // ""') if echo "$FILE_PATH" | grep -qE "\.env|secrets"; then echo "Warning: Accessing sensitive file: $FILE_PATH" >&2 fi exit 0 # Allow tool but show warning ``` ```python Python theme={null} #!/usr/bin/env python3 import sys import json import re event_data = json.load(sys.stdin) file_path = event_data.get('tool_input', {}).get('path', '') if re.search(r'\.env|secrets', file_path): print(f"Warning: Accessing sensitive file: {file_path}", file=sys.stderr) sys.exit(0) # Allow tool but show warning ``` ### SessionStart Output SessionStart hooks can inject context for the agent by writing to stdout: ```bash Bash theme={null} #!/usr/bin/env bash # Load current issues from issue tracker ISSUES=$(curl -s https://api.example.com/issues) # Output to stdout - this will be injected as context for the agent echo "Current open issues:" echo "$ISSUES" exit 0 ``` ```python Python theme={null} #!/usr/bin/env python3 import sys import requests # Load current issues from issue tracker response = requests.get('https://api.example.com/issues') issues = response.text # Output to stdout - this will be injected as context for the agent print("Current open issues:") print(issues) sys.exit(0) ``` ## Hook Output Reference Hooks can return structured output to control execution and communicate with the agent or user. Output is provided via **stdout** (as JSON) and **stderr** (for error messages). ### Exit Codes | Exit Code | Meaning | Behavior | | :-------: | ------------------ | :-----------------------------------------------------------------------------------------: | | `0` | Success | Hook completed successfully. Tool execution continues (unless JSON output blocks it). | | `2` | Blocking Error | **PreToolUse only**: Blocks tool execution. Stderr message is shown to both user and agent. | | Other | Non-blocking Error | Hook failed, but tool execution continues. Stderr shown in verbose mode. | ### JSON Output Format Hooks can return JSON on stdout (exit code 0 only) to provide structured control: ```json theme={null} { "continue": true, "stopReason": "Optional reason if continue=false", "suppressOutput": false, "systemMessage": "Message shown to user", "hookSpecificOutput": { "hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": "Security policy violation" } } ``` ### Common JSON Fields (All Events) These fields can be returned by any hook: | Field | Type | Description | Destination | | :--------------: | ------- | :-------------------------------------------------: | :---------: | | `continue` | boolean | If `false`, stops execution (overrides exit code 0) | - | | `stopReason` | string | Reason shown when `continue=false` | User | | `suppressOutput` | boolean | If `true`, hides stdout from verbose mode | - | | `systemMessage` | string | Warning or informational message | User | ### Event-Specific JSON Output #### PreToolUse Output PreToolUse hooks can control tool execution and modify tool input: | Field | Type | Description | Destination | | :------------------------: | -------- | :----------------------------: | :------------: | | `permissionDecision` | `"deny"` | Block tool execution | - | | `permissionDecisionReason` | string | Reason for blocking the tool | Agent and User | | `updatedInput` | object | Modified tool input parameters | - | Currently only `permissionDecision: "deny"` is supported. The `"allow"` and `"ask"` values will be implemented in a future release. **Example: Block dangerous command** ```json theme={null} { "hookSpecificOutput": { "hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": "Command contains 'rm -rf' which is not allowed" } } ``` **Example: Modify tool input** ```json theme={null} { "hookSpecificOutput": { "hookEventName": "PreToolUse", "permissionDecision": "allow", "updatedInput": { "command": "git status --short" } } } ``` #### PostToolUse Output PostToolUse hooks can provide additional context to the agent: | Field | Type | Description | Destination | | :-----------------: | --------- | :------------------------------------------------: | :---------: | | `decision` | `"block"` | Blocks agent with reason | - | | `reason` | string | Reason for blocking (required if decision="block") | Agent | | `additionalContext` | string | Additional context for the agent to consider | Agent | **Example: Provide context to agent** ```json theme={null} { "hookSpecificOutput": { "hookEventName": "PostToolUse", "additionalContext": "The command modified 3 files in the authentication module" } } ``` #### Stop Output Stop hooks can prevent the agent from finishing: | Field | Type | Description | Destination | | :--------: | --------- | :-----------------------------------------------------: | :---------: | | `decision` | `"block"` | Prevents stop | - | | `reason` | string | Reason for blocking stop (required if decision="block") | Agent | **Example: Prevent stop** ```json theme={null} { "hookSpecificOutput": { "hookEventName": "Stop", "decision": "block", "reason": "Please run tests before finishing" } } ``` #### SessionStart Output SessionStart hooks can inject context for the agent: | Field | Type | Description | Destination | | :-----------------: | ------ | :--------------------------------: | :---------: | | `additionalContext` | string | Context to inject at session start | Agent | **Example: Inject context** ```json theme={null} { "hookSpecificOutput": { "hookEventName": "SessionStart", "additionalContext": "Current sprint: Sprint 23. Focus: Authentication refactor" } } ``` ### Output Routing Different output goes to different destinations: **To Agent (injected into conversation):** * Exit code 2 stderr (PreToolUse, PostToolUse, Stop events) * `permissionDecisionReason` (when decision="deny") * `reason` (when decision="block") * `additionalContext` * SessionStart stdout or `additionalContext` **To User (displayed in UI):** * Exit code 2 stderr (SessionStart, SessionEnd events) * `systemMessage` * `permissionDecisionReason` (when decision="allow" or "ask") * Plain stdout (in verbose mode, for non-SessionStart events) ### Complete Output Examples ```bash Bash - Block with Exit Code 2 theme={null} #!/usr/bin/env bash EVENT_DATA=$(cat) COMMAND=$(echo "$EVENT_DATA" | jq -r '.tool_input.command // ""') if echo "$COMMAND" | grep -qE "rm -rf"; then echo "Blocked dangerous command: $COMMAND" >&2 exit 2 # Blocks tool, stderr shown to agent and user fi exit 0 ``` ```python Python - Block with Exit Code 2 theme={null} #!/usr/bin/env python3 import sys import json import re event_data = json.load(sys.stdin) command = event_data.get('tool_input', {}).get('command', '') if re.search(r'rm -rf', command): print(f"Blocked dangerous command: {command}", file=sys.stderr) sys.exit(2) # Blocks tool, stderr shown to agent and user sys.exit(0) ``` ```bash Bash - Block with JSON theme={null} #!/usr/bin/env bash EVENT_DATA=$(cat) COMMAND=$(echo "$EVENT_DATA" | jq -r '.tool_input.command // ""') if echo "$COMMAND" | grep -qE "rm -rf"; then cat << EOF { "hookSpecificOutput": { "hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": "Command contains 'rm -rf' which violates security policy" } } EOF exit 0 fi exit 0 ``` ```python Python - Block with JSON theme={null} #!/usr/bin/env python3 import sys import json import re event_data = json.load(sys.stdin) command = event_data.get('tool_input', {}).get('command', '') if re.search(r'rm -rf', command): output = { "hookSpecificOutput": { "hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": "Command contains 'rm -rf' which violates security policy" } } print(json.dumps(output)) sys.exit(0) sys.exit(0) ``` ## Hook Metadata (Configuration) Hook metadata options are **configuration-level flags** that control what data is included in the hook input. They provide a privacy-first, opt-in model for accessing conversation data, MCP metadata, and user context. ### Available Metadata Options Metadata options are specified in the hook configuration (not in hook output): ```json theme={null} { "hooks": { "PreToolUse": [ { "matcher": ".*", "hooks": [ { "type": "command", "command": "/etc/augment/hooks/analytics.sh" } ], "metadata": { "includeConversationData": true, "includeMCPMetadata": true, "includeUserContext": false } } ] } } ``` **Metadata flags:** * **`includeUserContext`**: Include user and environment context in hook input * Adds `context` field to hook event data * Available for: **All event types** (PreToolUse, PostToolUse, Stop, SessionStart, SessionEnd) * Fields included: * `userEmail` - User's email address (e.g., "[user@example.com](mailto:user@example.com)") * `modelName` - Model name being used (e.g., "Claude Opus 4.5") * `timestamp` - ISO 8601 timestamp (e.g., "2025-01-15T10:30:00-08:00") * Default: `false` (user context excluded) * **`includeMCPMetadata`**: Include MCP-specific metadata in hook input * Adds `mcp_metadata` field to hook event data * Available for: **PreToolUse and PostToolUse only** * Fields included: * `mcpDecision` - Whether MCP tools were used ("yes" | "no") * `mcpTotalToolsCount` - Total number of MCP tools available across all servers * `mcpExecutedToolName` - Name of the executed MCP tool (if any) * `mcpExecutedToolServerName` - Server name of the executed MCP tool (if any) * `mcpExecutedToolServerToolsCount` - Number of tools from the executed server (if any) * Default: `false` (MCP metadata excluded) * **`includeConversationData`**: Include conversation fields in hook input * Adds `conversation` field to hook event data * Available for: **Stop event only** * Fields included: * `userPrompt` - The user's prompt/message that triggered the agent response * `agentTextResponse` - Agent's text response (markdown format) * `agentCodeResponse` - Array of file changes made by the agent, each containing: * `path` - File path relative to workspace root * `changeType` - Type of change ("edit" | "create" | "delete") * `content` - File content after the change (undefined for deletions) * Default: `false` (conversation data excluded for privacy) **Metadata availability by event type:** | Metadata Option | PreToolUse | PostToolUse | Stop | SessionStart | SessionEnd | | :-----------------------: | :--------: | :---------: | :--: | :----------: | :--------: | | `includeUserContext` | ✓ | ✓ | ✓ | ✓ | ✓ | | `includeMCPMetadata` | ✓ | ✓ | - | - | - | | `includeConversationData` | - | - | ✓ | - | - | ### When to Use Metadata Options **Use `includeUserContext` when:** * Implementing user-specific rate limiting * Building per-user analytics * Tracking model usage by user * Implementing user-based access controls * Logging user activity for compliance **Use `includeMCPMetadata` when:** * Monitoring MCP tool usage patterns * Debugging MCP integration issues * Building MCP usage analytics * Rate limiting MCP tool calls * Tracking which MCP servers are being used **Use `includeConversationData` when:** * Building analytics dashboards that track user interactions * Implementing compliance logging for audit trails * Analyzing agent response quality * Tracking code changes made by the agent * Capturing complete conversation context for debugging ### Hook Input with Metadata When metadata options are enabled, the hook receives additional fields in the event data. Here's an example showing all three options enabled: **Configuration:** ```json theme={null} { "hooks": { "Stop": [ { "hooks": [ { "type": "command", "command": "/etc/augment/hooks/analytics.sh" } ], "metadata": { "includeUserContext": true, "includeConversationData": true } } ] } } ``` **Hook Input (Stop event with all metadata options):** ```json theme={null} { "hook_event_name": "Stop", "conversation_id": "conv-xyz789", "workspace_roots": ["/Users/username/project"], "agent_stop_cause": "end_turn", "context": { "userEmail": "user@example.com", "modelName": "Claude Opus 4.5", "toolVersion": "0.6.0", "timestamp": "2025-01-15T10:30:00-08:00" }, "conversation": { "timestamp": "2025-01-15T10:30:00-08:00", "userPrompt": "Add error handling to the login function", "agentTextResponse": "I'll add comprehensive error handling...", "agentCodeResponse": [{ "path": "src/auth/login.ts", "changeType": "edit" }] } } ``` **Hook Input (PostToolUse event with metadata - MCP tool):** ```json theme={null} { "hook_event_name": "PostToolUse", "conversation_id": "conv-xyz789", "workspace_roots": ["/Users/username/project"], "tool_name": "search_example-server", "tool_input": { "query": "latest documentation" }, "tool_output": "Found 5 results...", "is_mcp_tool": true, "context": { "userEmail": "user@example.com", "modelName": "Claude Opus 4.5", "toolVersion": "0.6.0", "timestamp": "2025-01-15T10:30:00-08:00" }, "mcp_metadata": { "timestamp": "2025-01-15T10:30:00-08:00", "mcpDecision": "yes", "mcpTotalToolsCount": 15, "mcpExecutedToolName": "search", "mcpExecutedToolServerName": "example-server", "mcpExecutedToolServerToolsCount": 5 } } ``` **Hook Input (PostToolUse event with file\_changes - file edit):** ```json theme={null} { "hook_event_name": "PostToolUse", "conversation_id": "conv-xyz789", "workspace_roots": ["/Users/username/project"], "tool_name": "str-replace-editor", "tool_input": { "path": "src/auth.ts", "old_str_1": "...", "new_str_1": "..." }, "tool_output": "File edited successfully", "is_mcp_tool": false, "file_changes": [ { "path": "src/auth.ts", "changeType": "edit", "content": "// New content...", "oldContent": "// Old content that was replaced..." } ], "context": { "userEmail": "user@example.com", "modelName": "Claude Opus 4.5", "toolVersion": "0.6.0", "timestamp": "2025-01-15T10:30:00-08:00" } } ``` ### Privacy Considerations Metadata options follow a **privacy-first, opt-in model**: 1. **Default deny**: All sensitive data is excluded by default 2. **Explicit opt-in**: Hooks must explicitly request metadata options 3. **Minimal access**: Request only the options you need 4. **Audit trail**: Metadata usage should be logged for compliance When using metadata options that include user data (`includeConversationData`, `includeUserContext`), ensure your hook scripts: - Handle sensitive data securely - Comply with privacy regulations (GDPR, CCPA, etc.) - Implement appropriate data retention policies - Use encryption for data at rest and in transit ### Example: Analytics Hook with Metadata **Configuration:** ```json theme={null} { "hooks": { "PostToolUse": [ { "matcher": ".*", "hooks": [ { "type": "command", "command": "/etc/augment/hooks/analytics.sh" } ], "metadata": { "includeUserContext": true, "includeMCPMetadata": true } } ] } } ``` **Hook script (with metadata options):** ```bash Bash theme={null} #!/usr/bin/env bash # /etc/augment/hooks/analytics.sh EVENT_DATA=$(cat) # Extract user context (available because includeUserContext=true) USER_EMAIL=$(echo "$EVENT_DATA" | jq -r '.context.userEmail // ""') MODEL_NAME=$(echo "$EVENT_DATA" | jq -r '.context.modelName // ""') # Extract MCP metadata (available because includeMCPMetadata=true) MCP_DECISION=$(echo "$EVENT_DATA" | jq -r '.mcp_metadata.mcpDecision // "no"') MCP_SERVER=$(echo "$EVENT_DATA" | jq -r '.mcp_metadata.mcpExecutedToolServerName // ""') # Log analytics echo "User: $USER_EMAIL, Model: $MODEL_NAME, MCP: $MCP_DECISION, Server: $MCP_SERVER" exit 0 ``` ```python Python theme={null} #!/usr/bin/env python3 # /etc/augment/hooks/analytics.sh (Python via shebang) import sys import json event_data = json.load(sys.stdin) # Extract user context context = event_data.get('context', {}) user_email = context.get('userEmail', '') model_name = context.get('modelName', '') # Extract MCP metadata mcp = event_data.get('mcp_metadata', {}) mcp_decision = mcp.get('mcpDecision', 'no') mcp_server = mcp.get('mcpExecutedToolServerName', '') print(f"User: {user_email}, Model: {model_name}, MCP: {mcp_decision}") sys.exit(0) ``` ## Working with MCP Tools Hooks work seamlessly with [Model Context Protocol (MCP)](/setup-augment/mcp) tools. MCP tools have special naming and metadata that you can use in hooks. ### MCP Tool Naming MCP tools follow the naming pattern `{toolName}_{serverName}`. For example: * `search_my-server` - "search" tool from "my-server" * `query_database-server` - "query" tool from "database-server" * `read_filesystem-mcp` - "read" tool from "filesystem-mcp" Both tool names and server names can contain underscores. The server name is always the suffix after the **last** underscore that matches the known server name. For reliable matching, use the `mcp_server_name` field in your hook script rather than parsing the tool name. ### MCP Tool Matchers Use the `mcp:` prefix to match MCP tools. The pattern after `mcp:` is a regex matched against the full tool name (`toolName_serverName`): * `"mcp:*"` - Match ALL MCP tools (special case) * `"mcp:.*_my-server$"` - Match any tool from `my-server` (use `$` anchor) * `"mcp:^search_my-server$"` - Match exact tool `search` from `my-server` * `"mcp:^search_.*"` - Match `search` tool from any server The `mcp:` prefix ensures only MCP tools are matched. The pattern is a standard regex applied to the full tool name. Use the `$` anchor when matching server names to avoid partial matches. ### MCP Hook Examples **Log MCP tool usage:** ```bash theme={null} #!/usr/bin/env bash EVENT_DATA=$(cat) SERVER=$(echo "$EVENT_DATA" | jq -r '.mcp_server_name // ""') echo "[MCP] Server: $SERVER, Tool: $(echo "$EVENT_DATA" | jq -r '.tool_name')" >&2 exit 0 ``` **Configuration:** ```json theme={null} { "hooks": { "PreToolUse": [ { "matcher": "mcp:*", "hooks": [ { "type": "command", "command": "/etc/augment/hooks/log-mcp-tools.sh", "timeout": 5000 } ] } ] } } ``` **Block specific MCP server:** ```bash theme={null} #!/usr/bin/env bash EVENT_DATA=$(cat) MCP_SERVER=$(echo "$EVENT_DATA" | jq -r '.mcp_server_name // ""') if [ "$MCP_SERVER" = "blocked-server" ]; then echo "This MCP server is blocked by security policy" >&2 exit 2 fi exit 0 ``` **Configuration:** ```json theme={null} { "hooks": { "PreToolUse": [ { "matcher": "mcp:.*_blocked-server$", "hooks": [ { "type": "command", "command": "/etc/augment/hooks/block-mcp-server.sh", "timeout": 5000 } ] } ] } } ``` ## Examples For ready-to-use hook examples, see [Hooks Examples](/cli/hooks-examples). ## Debugging Hooks ### Environment Variables Hooks have access to these environment variables during execution: | Variable | Description | Example | | :-----------------------: | ------------------------------------------------------------ | :-----------------------: | | `AUGMENT_PROJECT_DIR` | First workspace root directory (or `process.cwd()` if empty) | `/Users/username/project` | | `AUGMENT_CONVERSATION_ID` | Current conversation ID | `conv-xyz789` | | `AUGMENT_HOOK_EVENT` | Event type | `PreToolUse` | | `AUGMENT_TOOL_NAME` | Tool name (PreToolUse/PostToolUse only) | `launch-process` | ```bash theme={null} #!/usr/bin/env bash echo "Project: $AUGMENT_PROJECT_DIR, Event: $AUGMENT_HOOK_EVENT" >&2 exit 0 ``` ### Testing Hooks Locally **1. Create a test event file:** ```bash theme={null} cat > test-event.json << 'EOF' { "hook_event_name": "PreToolUse", "conversation_id": "test-conv", "workspace_roots": ["/Users/username/project"], "tool_name": "launch-process", "tool_input": { "command": "git status" } } EOF ``` **2. Test your hook script:** ```bash theme={null} # Test your hook script (works for both bash and Python via shebang) cat test-event.json | /etc/augment/hooks/my-hook.sh echo "Exit code: $?" ``` **3. Validate JSON output:** ```bash theme={null} # Test and validate JSON output OUTPUT=$(cat test-event.json | /etc/augment/hooks/my-hook.sh) echo "$OUTPUT" | jq . # Validates JSON syntax ``` ### Viewing Hook Execution Logs Hooks log to the Augment logger. To see hook execution details: **CLI:** ```bash theme={null} # Run with verbose logging auggie --verbose "your prompt here" # Or set log level export AUGMENT_LOG_LEVEL=debug auggie "your prompt here" ``` **Check logs for:** * `[HookExecutor]` - Hook execution details * `[HookManager]` - Hook matching and routing * `[hook-output-router]` - Output routing decisions ### Common Debugging Techniques **Log to stderr (won't affect hook output):** ```bash theme={null} #!/usr/bin/env bash EVENT_DATA=$(cat) echo "[DEBUG] $(echo "$EVENT_DATA" | jq -r '.hook_event_name')" >&2 exit 0 ``` **Save event data for inspection:** ```bash theme={null} #!/usr/bin/env bash cat > /tmp/hook-debug.json exit 0 ``` #### 3. Validate hook matcher patterns To test if your matcher pattern works: ```bash theme={null} # Test regex pattern in bash TOOL_NAME="search_my-server" PATTERN=".*_my-server$" if [[ "$TOOL_NAME" =~ $PATTERN ]]; then echo "Pattern matches!" else echo "Pattern does not match" fi ``` ```python theme={null} # Test regex pattern in Python import re tool_name = "search_my-server" pattern = r".*_my-server$" if re.match(pattern, tool_name): print("Pattern matches!") else: print("Pattern does not match") ``` ### Performance Tips 1. **Keep hooks fast** - Hooks run synchronously and block tool execution 2. **Cache expensive operations** - Store results in files or environment variables 3. **Use early returns** - Exit as soon as you know the result 4. **Avoid network calls** - Network requests add latency 5. **Minimize JSON parsing** - Parse only the fields you need **Example: Fast hook with early return** ```bash Bash theme={null} #!/usr/bin/env bash EVENT_DATA=$(cat) # Early return if not a launch-process tool TOOL_NAME=$(echo "$EVENT_DATA" | jq -r '.tool_name') if [[ "$TOOL_NAME" != "launch-process" ]]; then exit 0 # Not interested, return immediately fi # Only parse command if we got here COMMAND=$(echo "$EVENT_DATA" | jq -r '.tool_input.command') # Check command if echo "$COMMAND" | grep -qE "rm -rf"; then echo "Blocked dangerous command" >&2 exit 2 fi exit 0 ``` ```python Python theme={null} #!/usr/bin/env python3 import sys import json import re event_data = json.load(sys.stdin) # Early return if not a launch-process tool tool_name = event_data.get('tool_name', '') if tool_name != 'launch-process': sys.exit(0) # Not interested, return immediately # Only parse command if we got here command = event_data.get('tool_input', {}).get('command', '') # Check command if re.search(r'rm -rf', command): print("Blocked dangerous command", file=sys.stderr) sys.exit(2) sys.exit(0) ``` ## Troubleshooting **Check:** 1. **Matcher pattern** - Verify your regex pattern matches the tool name 2. **Event type** - Ensure you're listening to the correct event (PreToolUse vs PostToolUse) 3. **Settings file location** - Verify hooks are in the correct settings file (project vs user vs system) 4. **Hook path** - Ensure the hook script path is correct and the file exists 5. **File permissions** - Make sure the hook script is executable (`chmod +x hook.sh`) **Debug:** ```bash theme={null} # Check if hook file exists and is executable ls -la /etc/augment/hooks/my-hook.sh # Test matcher pattern echo "launch-process" | grep -E "launch-process|str-replace-editor" # Should match echo "view" | grep -E "launch-process|str-replace-editor" # Should not match ``` Hooks have a **60-second timeout** by default. If your hook takes longer: 1. **Optimize the hook** - Make it faster 2. **Run async operations** - Don't wait for slow operations 3. **Use background jobs** - Start long-running tasks in the background ```bash theme={null} #!/usr/bin/env bash EVENT_DATA=$(cat) # Start long-running task in background (don't wait) ( # Long-running operation here sleep 300 ) & # Return immediately exit 0 ``` **Common issues:** * **Invalid JSON syntax** - Use `jq` to validate * **Missing quotes** - Ensure all strings are quoted * **Trailing commas** - JSON doesn't allow trailing commas * **Special characters** - Escape special characters in strings **Validate JSON:** ```bash theme={null} # Test JSON output cat << 'EOF' | jq . { "hookSpecificOutput": { "hookEventName": "PreToolUse", "permissionDecision": "deny" } } EOF ``` **Check:** * **Exit code** - Make sure you're returning `exit 0` for success * **JSON output** - Verify `permissionDecision` is not set to `"deny"` * **stderr output** - Ensure you're not writing errors to stderr with exit code 2 **Debug:** ```bash theme={null} #!/usr/bin/env bash EVENT_DATA=$(cat) # Explicitly allow echo "Allowing tool execution" >&2 # Debug message exit 0 # Success - don't block ``` Check the Auggie logs for hook execution errors: ```bash theme={null} # View recent logs tail -f ~/.augment/logs/auggie.log | grep -i hook ``` Test your hook script manually: ```bash theme={null} # Create test event data echo '{ "hook_event_name": "PreToolUse", "tool_name": "launch-process", "tool_input": {"command": "ls -la"} }' | /etc/augment/hooks/your-hook.sh # Check exit code echo $? ``` ## Security Considerations **USE AT YOUR OWN RISK**: Hooks execute arbitrary shell commands on your system automatically. By using hooks, you acknowledge that: * You are solely responsible for the commands you configure * Hooks can modify, delete, or access any files your user account can access * Malicious or poorly written hooks can cause data loss or system damage * You should thoroughly test hooks in a safe environment before production use Always review and understand any hook commands before adding them to your configuration. ### Security Best Practices 1. **Validate and sanitize inputs** - Never trust input data blindly 2. **Always quote shell variables** - Use `"$VAR"` not `$VAR` 3. **Block path traversal** - Check for `..` in file paths 4. **Use absolute paths** - Specify full paths for scripts 5. **Skip sensitive files** - Avoid `.env`, `.git/`, keys, etc. 6. **Set appropriate timeouts** - Prevent hooks from hanging indefinitely 7. **Test thoroughly** - Test hooks with various inputs before deploying ## Best Practices 1. **Keep hooks fast**: Hooks should complete quickly (\< 1 second) to avoid slowing down the agent 2. **Use timeouts**: Always set reasonable timeouts to prevent hanging 3. **Handle errors gracefully**: Use exit code 0 for non-critical errors to avoid blocking the agent 4. **Log appropriately**: Use stderr for user-facing messages, log files for detailed audit trails 5. **Test thoroughly**: Test hooks with various tool inputs before deploying 6. **Version control**: Keep hook scripts in version control with your project 7. **Document behavior**: Add comments explaining what each hook does and why ## Limitations * Hooks currently only support command execution (webhooks planned for future) * PostToolUse hooks cannot modify tool output (read-only) * Hooks cannot access the agent's conversation history directly * Maximum timeout is enforced to prevent indefinite blocking * Hook execution is sequential, not parallel ## Hook Execution Details * **Timeout**: 60-second execution limit by default, configurable per command * **Execution order**: Hooks execute in the order they are defined * **Environment**: Runs in current directory with Auggie's environment * **Input**: JSON via stdin * **Output**: * PreToolUse/PostToolUse/Stop: Progress shown in logs * SessionStart: stdout added as context for agent * SessionEnd: Logged to debug only ## Related Documentation * [Hooks Examples](/cli/hooks-examples) - Ready-to-use hook examples * [MCP (Model Context Protocol)](/setup-augment/mcp) - External tool integration * [Permissions](/cli/permissions) - Tool permission system * [Rules & Guidelines](/cli/rules) - Custom rules and guidelines * [Custom Commands](/cli/custom-commands) - Create custom CLI commands # Integrations and MCP Source: https://docs.augmentcode.com/cli/integrations Expand Augment's capabilities with external tools and data sources through native integrations and Model Context Protocol (MCP) servers. Auggie runs commands and tools automatically. Only use integrations and MCP servers from trusted sources, and be aware of the risks of combining multiple tools with external data sources or production systems. ## About Integrations and MCP Auggie can utilize external integrations through native integrations like GitHub, Linear, and Notion and Model Context Protocol (MCP) to access external systems for information and integrate tools to take actions. MCP is an open protocol that provides a standardized way to connect AI models to different data sources and tools. ## Native Integrations You'll need to configure the integration in Augment for VS Code or JetBrains IDEs. Once configured, the integration will be available for use with Auggie automatically. See a full list and examples for [native agent integrations](/setup-augment/agent-integrations). ### 1. Setup in Augment extension * **Visual Studio Code**: Click the settings icon in the top right of Augment's chat window or press and select * **JetBrains IDEs**: Click the Augment icon in the bottom right of your JetBrains IDE and select ### 2. Connect the integration Click "Connect" for the integration you want to set up Set up integrations in the settings page You'll be redirected to authorize the integration with the appropriate service. After authorization, the integration will be available for use with Augment Agent. ## MCP Integrations In addition to native integrations, Auggie can also access external systems through Model Context Protocol (MCP) servers. MCP servers enable Auggie to interact with external tools and services through a standardized protocol, such as accessing databases, running browser automation, sending messages to Slack, or integrating with APIs. ### Configure MCP via settings.json You can persist MCP servers in the Augment settings file `~/.augment/settings.json`, which will initialize on startup and can be checked with `/mcp-status`. ```json theme={null} { "mcpServers": { "context7": { "type": "http", "url": "https://mcp.context7.com/mcp", "headers": { "CONTEXT7_API_KEY": "YOUR_API_KEY" } }, "weather": { "type": "sse", "url": "https://weather-mcp.example.com/v1", "headers": { "X-API-Key": "your_weather_api_key", "Content-Type": "application/json" } }, "renderMCP": { "type": "http", "url": "https://mcp.render.com/mcp", "headers": { "Authorization": "Bearer " } }, "local-tool": { "command": "/usr/local/bin/custom-mcp", "args": ["--serve", "--port", "3000"], "env": { "DEBUG": "true" } } } } ``` #### Variable Expansion MCP server configurations support variable expansion for dynamic values. Currently, the `${workspaceFolder}` variable is supported, which expands to the current workspace root path when running Auggie in a workspace context. **Example: Using `${workspaceFolder}` in args** ```json theme={null} { "mcpServers": { "yaml-lsp": { "command": "mcp-language-server", "args": [ "--workspace", "${workspaceFolder}", "--lsp", "yaml-language-server", "--", "--stdio" ] } } } ``` When running in workspace `/Users/username/my-project`, the args are expanded to: ``` ["--workspace", "/Users/username/my-project", "--lsp", "yaml-language-server", "--", "--stdio"] ``` **Supported locations for variable expansion:** * `command` field (for stdio transport) * `args` array elements (for stdio transport) * `url` field (for http and sse transports) **Notes:** * Variables are only expanded when Auggie is run within a workspace context * If no workspace is available, the variable remains unexpanded * Variable expansion works with both `settings.json` configurations and `--mcp-config` overrides #### HTTP Transport with Headers MCP servers using HTTP transport can include a `headers` object for authentication or custom headers: ```json theme={null} { "mcpServers": { "renderMCP": { "type": "http", "url": "https://mcp.render.com/mcp", "headers": { "Authorization": "Bearer ", "X-Custom-Header": "custom-value" } } } } ``` The `headers` field accepts any valid HTTP headers as key-value pairs. **Common uses** * **Authentication** - `Authorization` headers with bearer tokens or API keys * **Custom parameters** - Server-specific information that doesn't fit into standard request parameters * **Session management** - `Mcp-Session-Id` header for managing sessions in Streamable HTTP transport **Considerations** * **Transport type** - Headers are relevant for HTTP and SSE transports only. Stdio transport uses standard input/output and does not use HTTP headers * **Server requirements** - Required headers depend on the MCP server implementation * **Security** - Avoid including sensitive information like API keys directly in configuration files. Consider secure credential management methods ### Manage MCP servers with the Auggie CLI You can add and inspect MCP servers is via Auggie subcommands, which will persist the configuration to your `~/.augment/settings.json` file: #### Usage **Add MCP server:** ```bash theme={null} auggie mcp add [options] ``` Writes the server entry to your settings.json with interactive prompts for overwriting existing configurations. Options: * `--command ` - Executable path (for stdio transport) * `--args ` - Arguments string for command * `-e, --env ` - Environment variable (repeatable) * `-t, --transport ` - stdio|sse|http (default: "stdio") * `-u, --url ` - URL (required for --transport sse or http) * `-h, --header ` - HTTP header (repeatable, for http transport) * `-r, --replace` - Overwrite existing entry without prompt * `--json` - Output JSON **Add MCP server from JSON:** ```bash theme={null} auggie mcp add-json ``` Import an MCP server configuration directly from a JSON string. This is useful when you have a complete server configuration in JSON format and want to add it quickly without specifying individual options. The JSON string should match the structure used in `settings.json` for MCP server configurations. This command uses the same mechanism as `--mcp-config` but provides a convenient way to add servers directly from the command line. **List MCP servers:** ```bash theme={null} auggie mcp list [options] ``` Lists configured MCP servers (from settings and any active overrides). Options: * `--json` - Output JSON format **Remove MCP server:** ```bash theme={null} auggie mcp remove [options] ``` Cleanly removes the named server configuration from settings.json. Examples: ```bash theme={null} # Add a stdio-based MCP server (executable with args and environment) auggie mcp add context7 \ --command npx \ --args "-y @upstash/context7-mcp@latest" \ --env CONTEXT7_API_KEY=your_key # Compressed syntax auggie mcp add context7 -- npx -y @upstash/context7-mcp # Add an SSE-based MCP server (Server-Sent Events with URL) auggie mcp add weather-api \ --transport sse \ --url https://weather-mcp.example.com/sse # Compressed syntax auggie mcp add weather-api --transport sse https://weather-mcp.example.com/sse # Add an HTTP-based MCP server with authentication headers auggie mcp add renderMCP \ --transport http \ --url https://mcp.render.com/mcp \ --header "Authorization:Bearer YOUR_API_TOKEN" # Add HTTP server with multiple headers auggie mcp add api-service \ --transport http \ --url https://api.example.com/mcp \ --header "Authorization:Bearer YOUR_TOKEN" \ --header "X-Custom-Header:custom-value" # List all configured servers (tabular display with status) auggie mcp list # List servers in JSON format for programmatic access auggie mcp list --json # Remove a server configuration auggie mcp remove context7 # Replace existing server without interactive prompt auggie mcp add context7 --command npx --args "..." --replace # Add MCP server from JSON configuration (stdio transport) auggie mcp add-json weather-api '{"type":"stdio","command":"/path/to/weather-cli","args":["--api-key","abc123"],"env":{"CACHE_DIR":"/tmp"}}' # Add MCP server from JSON configuration (SSE transport) auggie mcp add-json remote-api '{"type":"sse","url":"https://api.example.com/sse"}' # Add MCP server from JSON configuration (HTTP transport with headers) auggie mcp add-json renderMCP '{"type":"http","url":"https://mcp.render.com/mcp","headers":{"Authorization":"Bearer ABC_XYZ_123"}}' ``` ### MCP overrides You can define servers by passing ad‑hoc overrides with `--mcp-config`. The structure is the same as `settings.json`: ```json theme={null} // After npm install gitlab-mr-mcp { "mcpServers": { "gitlab-mr-mcp": { "command": "node", "args": ["/path/to/gitlab-mr-mcp/index.js"], "env": { "MR_MCP_GITLAB_TOKEN": "your_gitlab_token", "MR_MCP_GITLAB_HOST": "your_gitlab_host" } } } } ``` # Interactive mode Source: https://docs.augmentcode.com/cli/interactive Use a rich interactive terminal experience to explore your codebase, build new features, debug issues, and integrate your tools. Auggie is currently in beta and does not support all features available in the Augment plugins for Visual Studio Code or JetBrains IDEs. ## About interactive mode Auggie is an agentic terminal-based code assistant that has deep codebase knowledge powered by Augment's context engine. Auggie can help you understand a new codebase, fix bugs quickly, and build new features faster. Auggie has access to your connected integrations and MCP servers and can pull in additional context or run tools to get your tasks done. ## Using interactive mode Run `auggie` without any mode flags to get the full-screen terminal user interface with rich interactive features, real-time streaming of responses, and visual progress indicators. This mode shows all tool calls, results, and allows ongoing conversation through an intuitive interface. ```sh theme={null} # Start Auggie in interactive mode auggie # Provide an initial instruction auggie "Look at my open issues and prioritize the highest impact ones for me" ``` ### Multi-line input Entering a new line in the input box depends on your terminal configuration and platform. You can use `Ctrl + J` to enter a new line in any terminal. See below for instructions to configure your terminal to use `Option + Enter` to enter a new line. | Terminal application | New line shortcut | | :------------------------- | :---------------- | | All terminals | `Ctrl + J` | | MacOS Terminal (see below) | `Option + Enter` | | iTerm2 (see below) | `Option + Enter` | | VS Code Terminal | `Option + Enter` | | Ghostty | `Shift + Enter` | **MacOS Terminal** 1. Go to 2. Check **iTerm2** 1. Go to 2. Check ## Reference ### Shortcuts | Command | Description | | :------------------ | :---------------------------------------------------------- | | `Ctrl + P` | Enhance your prompt with codebase context | | `Escape` | Interrupt the active agent | | `Ctrl + C` | Interrupt the active agent | | `Escape` + `Escape` | Clear the input box | | `Ctrl + C` | Press twice to exit | | `Ctrl + D` | Press twice to exit | | `Up Arrow` | Cycle through previous messages | | `Down Arrow` | Cycle through previous messages | | `Ctrl + O` | Open current input in external editor, inserts text on exit | ### Slash Commands | Command | Description | | :----------------- | :---------------------------------------------------------- | | `/account` | Show account information | | `/clear` | Clear the input box | | `/editor` | Open current input in external editor, inserts text on exit | | `/exit` | Exit Auggie | | `/feedback` | Provide feedback to the Augment team | | `/github-workflow` | Generate a GitHub Action workflow | | `/help` | Show help | | `/logout` | Logout of Augment | | `/mcp-status` | View the status of all configured MCP servers | | `/model` | Select the model for this session | | `/new` | Start a new conversation with no message history | | `/permissions` | View and manage tool permissions | | `/request-id` | Show the request ID for the current conversation | | `/rules` | View loaded rules and their attachment status | | `/skills` | View loaded skills and their token counts | | `/task` | Open task manager to add, edit, and manage tasks | | `/verbose` | Toggle verbose output for tools | | `/vim` | Toggle Vim mode for advanced text editing | For more information about slash commands, including how to create custom commands, see [Custom Slash Commands](/cli/custom-commands). # Prompt Enhancer Source: https://docs.augmentcode.com/cli/interactive/prompt-enhancer Use Ctrl+P to enhance your prompts with relevant context, structure, and conventions from your codebase. ## About the Prompt Enhancer The Auggie CLI prompt enhancer is a powerful feature that helps you craft better prompts by automatically adding relevant context, structure, and conventions from your codebase. Instead of writing detailed prompts from scratch, you can start with a simple idea and let the prompt enhancer transform it into a comprehensive, well-structured prompt. ## Activating the Prompt Enhancer To use the prompt enhancer in Auggie's interactive mode: 1. **Start typing your prompt** in the input box 2. **Press ** to activate the prompt enhancer 3. **Wait for enhancement** - Auggie will process your prompt and replace it with an enhanced version 4. **Review and edit** the enhanced prompt if needed 5. **Submit your enhanced prompt** by pressing Enter The prompt enhancer is only available when you have text entered at the command prompt. The shortcut will only work in interactive mode. ## How It Works When you press , the prompt enhancer: 1. **Captures your current input** and saves it to history 2. **Switches to Enhancement mode** - you'll see the mode indicator change and input will be temporarily disabled 3. **Sends your prompt** to the enhancement service using your current workspace context 4. **Processes the response** and extracts the enhanced prompt 5. **Replaces your input** with the enhanced version and returns to Normal mode During enhancement, you'll see: * The mode indicator shows "Enhancing your prompt, press Esc to cancel" * Input is disabled to prevent conflicts * A visual indication that processing is in progress ## Enhancement Process The prompt enhancer uses your workspace context to improve your prompts by: * **Adding relevant file references** from your current project * **Including coding conventions** and patterns from your codebase * **Structuring the prompt** for better clarity and specificity * **Adding context** about your project's architecture and dependencies * **Suggesting specific examples** based on existing code patterns ## Canceling Enhancement You can cancel the prompt enhancement process at any time: * **Press ** to cancel enhancement and restore your original input * **Press ** to cancel enhancement and restore your original input When canceled, you'll see a brief notification and your original prompt will be restored. ## Error Handling If the prompt enhancement fails: * Your original input will be restored * An error notification will appear briefly (\~3 seconds) * You can try enhancing again or proceed with your original prompt Common reasons for enhancement failure: * Network connectivity issues * Service temporarily unavailable * Input too short or unclear for enhancement ## Examples ### Before Enhancement ``` fix the login bug ``` ### After Enhancement (Example) ``` Fix the authentication bug in the login flow. Please: 1. Review the current login implementation in `src/auth/login.ts` 2. Check for issues with token validation and session management 3. Examine error handling in the authentication middleware 4. Look at recent changes to the user authentication flow 5. Test the fix with both valid and invalid credentials 6. Ensure the fix follows our existing error handling patterns Context: This appears to be related to the recent changes in the authentication system. Please maintain consistency with our existing auth patterns and ensure proper error messages are returned to the user. ``` ## Integration with Other Features The prompt enhancer works seamlessly with other Auggie CLI features: * **History Navigation**: Enhanced prompts are added to your command history * **Multi-line Input**: Works with both single-line and multi-line prompts * **Conversation Context**: Uses your current conversation history for better enhancement * **Workspace Awareness**: Leverages your current workspace and file context ## Tips for Best Results 1. **Start with clear intent** - Even simple prompts like "add tests" or "refactor this" work well 2. **Be specific about scope** - Mention specific files or components when relevant 3. **Use domain language** - Technical terms related to your project help the enhancer understand context 4. **Review enhanced prompts** - The enhancer provides a starting point; feel free to edit further 5. **Iterate if needed** - You can enhance the same prompt multiple times for different approaches ## Troubleshooting **Ctrl+P doesn't work:** * Ensure you have text in the input box * Make sure you're in Normal mode (not in a menu or other mode) * Check that you're using the correct key combination for your terminal **Enhancement takes too long:** * Press Esc to cancel and try again * Check your network connection * Try with a shorter or simpler prompt **Enhanced prompt isn't helpful:** * Edit the enhanced prompt manually * Try starting with a more specific initial prompt * Consider the context - the enhancer works best with workspace-relevant requests ## Related Features * [Task Management](/cli/interactive/task-management) - Break down enhanced prompts into manageable tasks * [Keyboard Shortcuts](/cli/interactive#shortcuts) - Learn other useful CLI shortcuts * [Slash Commands](/cli/interactive#slash-commands) - Discover other interactive commands # Using Task Manager Source: https://docs.augmentcode.com/cli/interactive/task-management Use /task to break down complex problems into manageable steps. ## About the Task Manager The Auggie CLI task manager allows you to break down complex problems into discrete, manageable actions and track your progress through each step. It's particularly useful for automation workflows and keeping the agent focused on multi-step tasks. The task manager maintains state per session and stores tasks under `~/.augment` for persistence across CLI sessions. ## Activating the Task Manager Start Auggie in interactive mode and use the `/task` slash command: ```bash theme={null} # Start Auggie in interactive mode auggie # Then type the slash command /task ``` This opens the task manager interface, which takes over the main panel and provides a focused environment for task management. ### Alternative Access You can also ask the agent to create a task list for you: ```bash theme={null} auggie "Start a task list to implement user authentication" ``` The agent will automatically create and populate a task list when it encounters complex, multi-step problems. ## Task Manager Interface The task manager provides a scrollable interface with comprehensive theming and visual feedback. When active, it replaces the main chat interface to provide a focused task management experience. ### Navigation and Interaction Use your keyboard to interact with the Task Manager: | Key | Action | | :--------- | :----------------------------------------------------------------------------------------- | | `↑` / `↓` | Navigate between tasks. The active task is highlighted with • next to the \[ ] Task Title. | | `J` / `K` | Alternative vim-style navigation (up/down) | | `A` | Add a new task | | `E` | Edit the active task's title and description | | `D` | Delete the active task | | `Spacebar` | Toggle task status | | `Esc` | Dismiss the Task Manager | ## Task Status Indicators Tasks have three distinct states with corresponding visual status indicators: * **\[ ] Not Started** - Empty checkbox, task has not been started * **\[✓] Done** - Checkmark, task has been completed * **\[-] Cancelled** - Dash, task has been cancelled or is no longer needed ## Working with Tasks ### Creating Tasks **Manual Creation:** 1. Press `A` to add a new task 2. Enter the task title when prompted 3. Optionally add a description for more detailed context **Agent-Generated Tasks:** The agent automatically creates tasks inside the Task Manager when it encounters complex problems. You can also explicitly request task creation: ```bash theme={null} "Create a task list to refactor the authentication system" ``` ### Editing Tasks 1. Navigate to the desired task using arrow keys or J/K 2. Press `E` to edit 3. Modify the title first, then the description 4. The task manager provides inline editing with clear visual feedback ### Task Execution **Manual Execution:** * Use the task list as a checklist, manually updating status as you complete work * Toggle status with `Spacebar` to track progress **Agent Execution:** You can ask the agent to work on specific tasks from the task manager: ```bash theme={null} "Work on the first incomplete task in my task list" "Complete the database migration task" ``` The agent will access your task list and update task status as it works. ## Advanced Features ### Task Hierarchy and Subtasks The task manager supports nested task structures: * Main tasks can have subtasks for complex workflows * Subtasks are automatically indented and organized hierarchically * Navigate through nested structures using standard navigation keys ### Persistence and Sessions * Tasks are automatically saved per session under `~/.augment` * Task lists persist across CLI restarts within the same session * Each conversation session maintains its own task list ### Integration with Agent Workflow The task manager is designed to work seamlessly with agent automation: * **Keeps agents focused**: Provides clear structure for multi-step workflows * **Progress tracking**: Agent can update task status as it completes work * **Context preservation**: Tasks maintain context across long conversations * **Automation-friendly**: Particularly useful for non-interactive automation workflows ## Use Cases and Examples ### Development Workflow ```bash theme={null} auggie "Create a task list to implement user registration feature" # Agent creates tasks like: # [ ] Design user registration API endpoints # [ ] Create user model and database schema # [ ] Implement registration validation # [ ] Add password hashing and security # [ ] Write unit tests for registration # [ ] Update API documentation ``` ### Code Refactoring ```bash theme={null} auggie "Break down refactoring the payment system into tasks" # Agent creates structured tasks for complex refactoring ``` ### Bug Investigation ```bash theme={null} auggie "Create tasks to investigate and fix the login timeout issue" # Agent creates systematic debugging tasks ``` ## Tips for Effective Task Management 1. **Be Specific**: Create clear, actionable task descriptions 2. **Break Down Complex Work**: Use subtasks for multi-step processes 3. **Regular Updates**: Keep task status current for accurate progress tracking 4. **Agent Collaboration**: Let the agent help create and organize task structures 5. **Session Organization**: Use task lists to maintain focus across long sessions ## Troubleshooting **Task Manager Won't Open:** * Ensure you're in interactive mode (`auggie` without `-p` flag) * Try typing `/task` exactly as shown * Check that you're not in the middle of another operation **Tasks Not Persisting:** * Tasks are saved per session - starting a new session creates a new task list * Check that `~/.augment` directory has proper write permissions **Navigation Issues:** * Use either arrow keys (↑/↓) or vim keys (J/K) for navigation * Ensure the task manager has focus (not in edit mode) ## Related Features * [Prompt Enhancer](/cli/interactive/prompt-enhancer) - Enhance task descriptions with context * [Keyboard Shortcuts](/cli/interactive#shortcuts) - Learn other useful CLI shortcuts * [Slash Commands](/cli/interactive#slash-commands) - Discover other interactive commands # Introducing Auggie CLI Source: https://docs.augmentcode.com/cli/overview Auggie in the terminal gives you powerful agentic capabilities to analyze code, make changes, and execute tools in an interactive terminal and in your automated workflows. ## Introduction Report issues, leave feature requests and view custom workflows for Auggie CLI Install Auggie CLI from npm Auggie CLI takes the power of Augment's agent and context engine and puts it in your terminal, allowing you to use Augment anywhere your code goes. You can use Auggie in a standalone interactive terminal session alongside your favorite editor or in any part of your software development stack. * Build features and debug issues with a standalone interactive agent. * Get instant feedback, insight, and suggestions for your PRs and builds. * Triage customer issues and alerts from your observability stack. ## Getting started To use Auggie CLI in interactive mode or in your automations, you'll need: * Node 22 or later installed * A compatible shell like zsh, bash, fish ```sh theme={null} npm install -g @augmentcode/auggie ``` You can install Auggie CLI directly from npm anywhere you can run Node 22 or later. Auggie is currently in beta and may not run on all environments and terminal configurations. ```sh theme={null} cd /path/to/your/project ``` Your project will be indexed automatically when you run Auggie in your project directory. Augment's powerful context engine provides the best results when it has access to your project's codebase and any related repositories. ```sh theme={null} auggie login ``` After installing, you'll have to log in to your Augment account. Run auggie login and follow the prompts. ```sh theme={null} auggie "optional initial prompt" ``` Just run `auggie` to start the interactive terminal. You can also pass a prompt as an argument and use `--print` to print the response to stdout instead of the interactive terminal–perfect for automation workflows. ## Using Auggie in interactive mode Run `auggie` without any mode flags to get the full-screen terminal user interface with rich interactive features, real-time streaming of responses, and visual progress indicators. This mode shows all tool calls, results, and allows ongoing conversation through an intuitive interface. Best for manual development work, exploration, and interactive problem-solving sessions where you want the full visual experience and plan to have back-and-forth conversations with the agent. ## Using Auggie in your automations Non-interactive mode is an additional feature that may be disabled if it is not included in your agreement (enterprise). **Print Mode**: Add the `--print` flag (e.g., `auggie --print "your instruction"`) to execute the instruction once without the UI. This mode exits immediately without prompting for additional input. Perfect for automation, CI/CD pipelines, and background tasks where you want the agent to act without follow-up from a person. **Quiet Mode**: `--quiet` flag (e.g., `auggie --print --quiet "your instruction"`) to tell the agent to only reply back with a final output. Ideal when you need to use the agent to provide structured data back without all the steps it took to get there. Provides a simple, clean response. # Tool Permissions Source: https://docs.augmentcode.com/cli/permissions Control what tools Auggie CLI can execute with granular permission settings for security and compliance. Tool permissions configured will only work inside the CLI and not in the Augment code extension. ## About Tool Permissions Auggie CLIs tool permission system provides fine-grained control over what actions the agent can perform in your environment. This security layer ensures that Auggie only executes approved operations, protecting your codebase and system from unintended changes. Tool permissions are especially important when: * Running Auggie in production environments * Working with sensitive codebases * Enforcing organizational security policies * Using Auggie in automated workflows ## How Permissions Work When Auggie attempts to use a tool, the permission system: 1. **Checks for matching rules** in your configuration 2. **Applies the first matching rule** based on tool name and optional patterns 3. **Rules are evaluated top-down** - first match wins 4. **Prompts for approval** when set to ask-user mode (interactive only) ### Permission Flow ``` Tool Request → Check Rules → Apply Permission → Execute/Deny → Log Decision ``` ### Notes on Unmatched Tools * Rules are evaluated in order from top to bottom * The first matching rule determines the permission * If no rules match, the CLI follows its implicit runtime behavior * Configure explicit rules for all tools you want to control ## Configuration Files Tool permissions are configured through the `settings.json` located in `~/.augment/settings.json` as personal settings that apply to all your projects. ## Basic Configuration ### Creating Rules Rules define permissions for specific tools. Each rule can specify: * **Tool name** - The specific tool to control * **Permission type** - `allow`, `deny`, or `ask-user` * **Optional patterns** - For shell commands, use regex matching ### Basic Rule Structure ```json theme={null} { "toolPermissions": [ { "toolName": "launch-process", "permission": { "type": "deny" } }, { "toolName": "view", "permission": { "type": "allow" } } ] } ``` ### Allow List Configuration Create an explicit allow list by only allowing specific tools: ```json theme={null} { "toolPermissions": [ { "toolName": "view", "permission": { "type": "allow" } }, { "toolName": "codebase-retrieval", "permission": { "type": "allow" } }, { "toolName": "grep-search", "permission": { "type": "allow" } }, { "toolName": "github-api", "permission": { "type": "allow" } } ] } ``` This configuration explicitly allows only the listed tools. Tools not in this list will follow the CLI's implicit behavior. ### Block List Configuration Create a block list by explicitly denying specific dangerous tools: ```json theme={null} { "toolPermissions": [ { "toolName": "remove-files", "permission": { "type": "deny" } }, { "toolName": "kill-process", "permission": { "type": "deny" } }, { "toolName": "launch-process", "shellInputRegex": "^(rm|sudo|shutdown|reboot)", "permission": { "type": "deny" } } ] } ``` This configuration blocks specific dangerous operations. Tools not explicitly denied will follow the CLI's implicit behavior. ### Mix and Match Configuration Combine allow, deny, and ask-user rules for fine-grained control: ```json theme={null} { "toolPermissions": [ { "toolName": "view", "permission": { "type": "allow" } }, { "toolName": "codebase-retrieval", "permission": { "type": "allow" } }, { "toolName": "grep-search", "permission": { "type": "allow" } }, { "toolName": "str-replace-editor", "permission": { "type": "ask-user" } }, { "toolName": "save-file", "permission": { "type": "ask-user" } }, { "toolName": "launch-process", "shellInputRegex": "^(npm test|npm run lint|git status|git diff)", "permission": { "type": "allow" } }, { "toolName": "launch-process", "shellInputRegex": "^(rm -rf|sudo|chmod 777)", "permission": { "type": "deny" } }, { "toolName": "launch-process", "permission": { "type": "ask-user" } }, { "toolName": "remove-files", "permission": { "type": "deny" } } ] } ``` This configuration provides fine-grained control with different permission levels based on tool risk and usage patterns. ## Available Tools ### Process Management | Tool | Description | | :--------------- | :--------------------------------- | | `launch-process` | Execute shell commands and scripts | | `read-process` | Read output from running processes | | `write-process` | Send input to running processes | | `list-processes` | List all active processes | | `kill-process` | Terminate running processes | ### File Operations | Tool | Description | | :------------------- | :---------------------------------- | | `view` | Read file contents | | `str-replace-editor` | Edit files with find/replace | | `save-file` | Create or overwrite files | | `remove-files` | Delete files from the filesystem | | `codebase-retrieval` | Search codebase with context engine | | `grep-search` | Search files with regex patterns | ### External Services | Tool | Description | | :----------- | :--------------------------- | | `github-api` | GitHub API operations | | `linear` | Linear issue tracking | | `notion` | Notion workspace access | | `supabase` | Supabase database operations | | `web-search` | Web search queries | | `web-fetch` | Fetch web page content | ### MCP Server Tools MCP tools follow the pattern `{tool-name}_{server-name}`: * Example: `query_database-mcp` * Truncated to 64 characters if longer * Treated like any other tool for permissions ## Advanced Rules ### Shell Command Filtering Control which shell commands can be executed using regex patterns: ```json theme={null} { "toolPermissions": [ { "toolName": "launch-process", "shellInputRegex": "^(ls|pwd|echo|cat|grep)\\s", "permission": { "type": "allow" } }, { "toolName": "launch-process", "permission": { "type": "deny" } } ] } ``` This configuration: 1. Allows only safe commands (ls, pwd, echo, cat, grep) 2. Denies all other shell commands 3. Rules are evaluated in order - first match wins ### Event-Based Permissions Control when permission checks occur: ```json theme={null} { "toolPermissions": [ { "toolName": "github-api", "eventType": "tool-response", "permission": { "type": "allow" } } ] } ``` **Event types:** * **`tool-call`** (default) - Check before tool execution * **`tool-response`** - Check after execution but before returning results to agent ## Interactive Approval When using `ask-user` mode in interactive sessions, Auggie displays approval prompts: ``` 🔒 Tool Approval Required ───────────────────────── Tool: launch-process Command: npm install express [A]llow once [D]eny [Always allow] [Never allow] ``` ### Keyboard Shortcuts | Key | Action | | :---- | :-------------------------- | | `A` | Allow this specific request | | `D` | Deny this specific request | | `Y` | Always allow this tool | | `N` | Never allow this tool | | `Esc` | Cancel and deny request | In non-interactive mode (--print), ask-user permissions default to deny for security. ## Common Configurations ### Read-Only Mode Allow only read operations, perfect for code review and analysis: ```json theme={null} { "toolPermissions": [ { "toolName": "view", "permission": { "type": "allow" } }, { "toolName": "codebase-retrieval", "permission": { "type": "allow" } }, { "toolName": "grep-search", "permission": { "type": "allow" } }, { "toolName": "web-search", "permission": { "type": "allow" } }, { "toolName": "web-fetch", "permission": { "type": "allow" } }, { "toolName": "str-replace-editor", "permission": { "type": "deny" } }, { "toolName": "save-file", "permission": { "type": "deny" } }, { "toolName": "remove-files", "permission": { "type": "deny" } }, { "toolName": "launch-process", "permission": { "type": "deny" } } ] } ``` ### Development Mode Add safety guards for potentially dangerous operations: ```json theme={null} { "toolPermissions": [ { "toolName": "remove-files", "permission": { "type": "ask-user" } }, { "toolName": "launch-process", "shellInputRegex": "^(rm|sudo|chmod)\\s", "permission": { "type": "ask-user" } } ] } ``` ### CI/CD Pipeline Restrictive settings for automated workflows: ```json theme={null} { "toolPermissions": [ { "toolName": "view", "permission": { "type": "allow" } }, { "toolName": "str-replace-editor", "permission": { "type": "allow" } }, { "toolName": "save-file", "permission": { "type": "allow" } }, { "toolName": "launch-process", "shellInputRegex": "^(npm test|npm run lint|jest)\\s", "permission": { "type": "allow" } }, { "toolName": "remove-files", "permission": { "type": "deny" } }, { "toolName": "launch-process", "permission": { "type": "deny" } } ] } ``` ## Custom Policies ### Webhook Validation Use external services to validate tool requests: ```json theme={null} { "toolPermissions": [ { "toolName": "github-api", "permission": { "type": "webhook-policy", "webhookUrl": "https://api.company.com/validate-tool" } } ] } ``` The webhook receives a POST request with the following JSON payload: ```json theme={null} { "tool-name": "github-api", "event-type": "tool-call", "details": { /* tool-specific data, see below */ }, "timestamp": "2025-01-01T02:41:40.580Z" } ``` **Payload fields:** * **`tool-name`**: The name of the tool being invoked * **`event-type`**: Either `"tool-call"` (before execution) or `"tool-response"` (after execution) * **`details`**: Tool-specific data (for `tool-call`) or response data (for `tool-response`) * **`timestamp`**: ISO 8601 timestamp of the request **Details for `tool-call` event type** (varies by tool): | Tool | Details Fields | | :------------------- | :---------------- | | `launch-process` | `cwd`, `command` | | `view` | `path` | | `str-replace-editor` | `path`, `command` | | `save-file` | `path` | | `remove-files` | `file_paths` | | `web-fetch` | `url` | **Details for `tool-response` event type:** ```json theme={null} { "text": "Tool output text", "isError": false } ``` **Expected response:** ```json theme={null} { "allow": true, "output": "Optional message to include in agent response" } ``` ### Script Validation Use local scripts for complex validation logic: ```json theme={null} { "toolPermissions": [ { "toolName": "launch-process", "permission": { "type": "script-policy", "script": "/path/to/validate-command.sh" } } ] } ``` The script receives the same JSON payload as webhooks via **stdin**: ```json theme={null} { "tool-name": "launch-process", "event-type": "tool-call", "details": { "cwd": "/path/to/workspace", "command": "npm install express" }, "timestamp": "2025-01-01T02:41:40.580Z" } ``` **Script behavior:** * **Exit code 0**: Allow the tool execution * **Non-zero exit code**: Deny the tool execution * **stdout/stderr**: Optional message included in the agent response **Example script:** ```bash theme={null} #!/bin/bash # Read JSON payload from stdin payload=$(cat) # Extract command using jq command=$(echo "$payload" | jq -r '.details.command // empty') # Deny dangerous commands if [[ "$command" == *"rm -rf"* ]] || [[ "$command" == *"sudo"* ]]; then echo "Dangerous command blocked: $command" exit 1 fi # Allow all other commands exit 0 ``` ## Best Practices 1. **Be Explicit**: Define clear rules for all tools you want to control 2. **Test Configurations**: Verify permissions work as expected before automation 3. **Log Decisions**: Monitor which tools are being allowed/denied for audit trails 4. **Regular Reviews**: Periodically review and update permission rules 5. **Order Matters**: Remember that rules are evaluated top-down, first match wins ## Troubleshooting **Ask-User Mode in Automation:** * Ask-user permissions automatically deny in non-interactive mode * Use explicit allow/deny rules for automation scenarios * Consider webhook or script policies for dynamic decisions **MCP Tools Not Recognized:** * Ensure MCP server name follows `{tool}_{server}` pattern * Check for 64-character truncation on long names * Verify MCP server is properly configured and running ## Security Considerations * **Never commit sensitive webhook URLs** to version control * **Use `.augment/settings.local.json`** for personal security overrides * **Regularly audit** tool usage in production environments * **Implement defense in depth** with multiple permission layers * **Test permission changes** in isolated environments first ## Related Features * [Authentication](/cli/setup-auggie/authentication) - Secure access to Auggie * [Custom Rules](/cli/rules) - Project-specific guidelines * [MCP Integrations](/cli/integrations) - External tool configuration * [Automation](/cli/automation) - Using permissions in CI/CD # CLI Flags and Options Source: https://docs.augmentcode.com/cli/reference A comprehensive reference for all command-line flags available in the Auggie CLI. ## CLI flags | Command | Description | | :------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `auggie` | Start Auggie in interactive mode | | `auggie --print` (`-p`) | Output simple text for one instruction and exit | | `auggie --quiet` | Output only the final response for one instruction and exit | | `auggie --compact` | Output tool calls, results, and final response as one line each and exit | | `auggie -p --output-format json` | Output the response in structured JSON format. Must be used with `--print` (`-p`) mode. Useful for parsing Auggie's output programmatically in automation workflows. | ### Input | Command | Description | | :------------------------------------------------- | :------------------------------------------------- | | `auggie "Fix the typescript errors"` | Provide an initial instruction in interactive mode | | `auggie --print "Summarize the staged changes"` | Provide an instruction and exit | | `cat file \| auggie --print "Summarize this data"` | Pipe content through stdin | | `auggie --print "Summarize this data" < file.txt` | Provide input from a file | | `auggie --instruction "Fix the errors"` | Provide an initial instruction in interactive mode | | `auggie --instruction-file /path/to/file.txt` | Provide an instruction by file in interactive mode | ### Custom Commands | Command | Description | | :------------------------------ | :--------------------------------------------------------------------------- | | `auggie command ` | Execute a custom command from `.augment/commands/` or `~/.augment/commands/` | Custom commands are reusable instructions stored as markdown files. They can be placed in: * `~/.augment/commands/.md` - Global commands (user-wide) * `./.augment/commands/.md` - Project commands (workspace-specific) * `~/.claude/commands/.md` - Claude Code user commands * `./.claude/commands/.md` - Claude Code workspace commands Commands are resolved in order of precedence, with Auggie-specific locations taking priority over Claude Code locations. **Examples:** ```sh theme={null} # Execute a custom deployment command auggie command deploy-staging # Execute a code review command auggie command security-review # List available commands (shown in help output) auggie command help ``` See [Custom Commands](/cli/custom-commands) for detailed information on creating and managing custom commands. ### Sessions | Command | Description | | :------------------------------- | :------------------------------------------------ | | `auggie --continue` `(-c)` | Resumes the previous conversation | | `auggie --dont-save-session` | Do not save the conversation to the local history | | `auggie --delete-saved-sessions` | Delete all saved sessions from disk | ### Configuration | Command | Description | | :----------------------------------------- | :------------------------------------------------------------------------ | | `auggie --workspace-root /path/to/project` | Specify the root of the workspace | | `auggie --rules /path/to/rules.md` | Additional rules to append to workspace guidelines | | `auggie --model "name"` | Select the model to use (accepts long or short names from the model list) | Skills are loaded automatically from `.augment/skills/` and `.claude/skills/` directories in both your workspace and home directory. See [Skills](/cli/skills) for more information. ### Models List out available models and their short names to be passed into the `--model` flag | Command | Description | | :------------------- | :-------------------- | | `auggie models list` | List available models | ### Tools Manage which tools are available to the agent. You can temporarily disable tools for a session or persistently manage them via settings. | Command | Description | | :--------------------------------- | :--------------------------------------------------------------------------------------- | | `auggie --remove-tool ` | Remove a specific tool by name for the current session. Can be specified multiple times. | | `auggie tools list` | List all available tools and their current status | | `auggie tools remove ` | Persistently remove a tool by adding it to the `removedTools` list in settings.json | | `auggie tools add ` | Re-enable a previously removed tool by removing it from the `removedTools` list | **Examples:** ```sh theme={null} # Disable the web-fetch tool for this session auggie --remove-tool web-fetch # Disable multiple tools for this session auggie --remove-tool web-fetch --remove-tool web-search # Persistently disable a tool auggie tools remove launch-process # Re-enable a previously disabled tool auggie tools add launch-process # See all tools and their status auggie tools list ``` Command-line `--remove-tool` flags take precedence over settings. For fine-grained control over tool behavior (allow, deny, ask-user), see [Permissions](/cli/permissions). ### MCP and integrations | Command | Description | | :---------------------------------- | :------------------------------------------------ | | `auggie mcp add [options] ` | Create or update a named MCP server configuration | | `auggie mcp add-json ` | Add an MCP server from JSON configuration | | `auggie mcp list` | Display all configured MCP servers | | `auggie mcp remove ` | Remove a named MCP server configuration | | Command | Description | | :-------------------------------------- | :--------------------------------- | | `auggie --mcp-config {key: value}` | MCP configuration as a JSON string | | `auggie --mcp-config /path/to/mcp.json` | MCP configuration from a JSON file | You can define MCP servers persistently in the settings files: `~/.augment/settings.json`. Any `--mcp-config` flags are applied last and override settings. For detailed usage examples, options, settings.json format, and precedence rules, see [Integrations and MCP](/cli/integrations#manage-mcp-servers-with-the-auggie-cli). ### MCP Server Mode Run Auggie as an MCP server to expose the codebase-retrieval tool to external AI tools like Claude Code, Cursor, and others. | Flag | Description | | :--------------------- | :------------------------------------------------------------------------------------------------ | | `--mcp` | Run Auggie as an MCP tool server. Uses the current working directory as the workspace by default. | | `--mcp-auto-workspace` | Enable automatic workspace discovery based on client requests (added in v0.14.0) | | `-w /path/to/project` | Specify a workspace to index | #### Automatic Workspace Discovery The `--mcp-auto-workspace` flag enables dynamic workspace discovery in MCP mode. When enabled: * The `codebase-retrieval` tool accepts a `directory_path` parameter to specify which workspace to search * Workspaces are indexed on-demand when first accessed * Multiple workspaces can be searched within a single MCP server session This is useful when the MCP client (e.g., Claude Code) needs to work with multiple projects or when the workspace isn't known at startup time. You can combine `--mcp-auto-workspace` with `-w` to pre-index a primary workspace at startup while still allowing dynamic discovery of additional workspaces. This is useful for large workspaces that take time to index, or to reduce latency on the first query to your main project. **Examples:** ```bash theme={null} # MCP server with auto-discovery (recommended) auggie --mcp --mcp-auto-workspace # Pre-index a workspace, allow dynamic discovery of others auggie --mcp --mcp-auto-workspace -w /path/to/primary/project # Use only a single workspace path auggie --mcp -w /path/to/project # Use current working directory as the workspace auggie --mcp ``` When using `--mcp-auto-workspace`, the first query to a new workspace may take longer as the workspace is indexed. Subsequent queries to the same workspace will be fast. ### Authentication | Command | Description | | :-------------------- | :------------------------------------------- | | `auggie login` | Login to Augment and store the token locally | | `auggie logout` | Remove the locally stored token | | `auggie tokens print` | Print the locally stored token | ### Additional commands | Command | Description | | :----------------- | :----------- | | `auggie --help` | Show help | | `auggie --version` | Show version | ## Environment Variables | Variable | Description | | ----------------------------- | ----------------------------- | | `AUGMENT_SESSION_AUTH` | Authentication JSON. | | `AUGMENT_API_URL` | Backend API endpoint | | `AUGMENT_API_TOKEN` | Authentication token | | `GITHUB_API_TOKEN` | GitHub API token | | `AUGMENT_DISABLE_AUTO_UPDATE` | Disable automatic CLI updates | ### Shell Environment When Auggie executes shell commands using the `launch-process` tool, it sets the following environment variable: | Variable | Description | | --------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `AUGMENT_AGENT` | Set to `1` when a command is executed by Auggie. Scripts can check for this variable to detect if they are being run by the agent. | **Example usage in a script:** ```sh theme={null} if [ -n "$AUGMENT_AGENT" ]; then echo "Running inside Auggie" # Adjust behavior for agent execution fi ``` ## See Also * [Custom Rules and Guidelines](/cli/rules) - Configure custom rules for project-specific guidance * [Skills](/cli/skills) - Extend capabilities with specialized domain knowledge * [Custom Commands](/cli/custom-commands) - Create reusable command templates * [Permissions](/cli/permissions) - Configure tool permissions and security * [Integrations](/cli/integrations) - Connect external tools and services # Rules & Guidelines Source: https://docs.augmentcode.com/cli/rules Configure custom rules and guidelines to provide context-aware assistance in Auggie CLI. ## Overview Auggie automatically loads custom rules and guidelines from several file locations to provide context-aware assistance. These files help Auggie understand your project's conventions, coding standards, and preferences. The Auggie CLI uses the same rules system as the VSCode and JetBrains IDE extensions. For more information on IDE specific features like user guidelines, see [Rules & Guidelines for Agent and Chat](/setup-augment/guidelines). Looking for specialized domain knowledge? Check out [Skills](/cli/skills) - a standardized way to provide framework-specific guidance, tool usage patterns, and workflow procedures following the agentskills.io specification. ## Supported Rules Files Auggie looks for rules files in the following order of precedence: 1. **Custom rules file** (via `--rules` flag): `/path/to/custom-rules.md` 2. **CLAUDE.md**: Compatible with Claude Code and other AI tools 3. **AGENTS.md**: Compatible with Cursor and other AI development tools 4. **Workspace guidelines**: `/.augment/guidelines.md` (legacy format) 5. **Workspace rules folder**: `/.augment/rules/` - Recursively searches .md files in the workspace 6. **User rules folder**: `~/.augment/rules/` - Recursively searches .md files for user-wide rules ### User Rules vs Workspace Rules Rules can be defined at two levels: | Scope | Location | Availability | | :-------- | :--------------------------------- | :---------------------------------- | | User | `~/.augment/rules/` | Available in all workspaces | | Workspace | `/.augment/rules/` | Available in current workspace only | **User rules** are stored in your home directory and apply to all projects. Use these for personal preferences, coding style guidelines, or conventions you want to follow across all your work. User rules are always treated as `always_apply` type and are automatically included in every prompt regardless of any frontmatter configuration. **Workspace rules** are stored in the project repository and apply only to that specific project. Use these for project-specific guidelines that should be shared with your team via version control. ## Rules File Format Rules files should be written in Markdown format with natural language instructions. Here's the recommended structure: ```markdown theme={null} # Project Guidelines ## Code Style - Use TypeScript for all new JavaScript files - Follow the existing naming conventions in the codebase - Add JSDoc comments for all public functions and classes ## Architecture - Follow the MVC pattern established in the codebase - Place business logic in service classes - Keep controllers thin and focused on request/response handling ## Testing - Write unit tests for all new functions - Maintain test coverage above 80% - Use Jest for testing framework ## Dependencies - Prefer built-in Node.js modules when possible - Use npm for package management - Pin exact versions in package.json for production dependencies ``` ## Frontmatter Configuration for Rules Rules files in the `/.augment/rules/` (workspace) directory support frontmatter to configure their behavior. Use YAML frontmatter at the beginning of your rule file to specify how the rule should be applied: User rules in `~/.augment/rules/` are always treated as `always_apply` and do not support other frontmatter types. Frontmatter configuration only affects workspace rules. | Frontmatter Field | Purpose | Options | Default | | :---------------- | :---------------------------------------------------------------------------- | :-------------------------------- | :------------- | | `type` | Controls when the rule is applied | `always_apply`, `agent_requested` | `always_apply` | | `description` | Brief description of the rule's purpose (required for `agent_requested` type) | Any text | None | **Rule Types:** * **`always_apply`**: Rule contents are automatically included in every user prompt * **`agent_requested`**: Rule is automatically detected and attached based on the description field when relevant Manual rules are not yet supported in the CLI. In the CLI, workspace rules in `/.augment/rules/` are currently treated as `always_apply` rules and automatically included. User rules in `~/.augment/rules/` are always `always_apply`. The `manual` type only works in the IDE extensions where you can use @ mentions to selectively attach rules. Use `agent_requested` (also called `auto` in IDE extensions) over `always_apply` if you want to optimize context usage. For these rules, the agent will determine the rule is relevant to your current task, ensuring specialized guidelines are available when needed. **Example with frontmatter:** ```markdown theme={null} --- type: always_apply --- # TypeScript Guidelines - Use strict mode in all TypeScript files - Define explicit return types for all functions - Avoid using `any` type unless absolutely necessary ``` **Agent-requested example:** ```markdown theme={null} --- type: agent_requested description: React component development patterns and best practices --- # React Component Guidelines - Use functional components with hooks - Implement proper TypeScript interfaces for props - Follow the established folder structure in src/components/ ``` ## Hierarchical Rules In addition to workspace-level rules, the agent supports **hierarchical rules** through `AGENTS.md` and `CLAUDE.md` files placed in subdirectories. When working on files in a subdirectory, Augment automatically discovers and applies rule files from that directory and all parent directories. ### How Hierarchical Rules Work 1. When you work on a file, Augment looks for `AGENTS.md` and `CLAUDE.md` in the file's directory 2. It then walks up the directory tree, checking each parent directory for these files 3. All discovered rules are included in the context for that work session 4. The search stops at the workspace root (since workspace root rules are already loaded separately) ### Example Directory Structure ``` my-project/ AGENTS.md <- Always included (workspace root) src/ AGENTS.md <- Included when working in src/ or subdirectories frontend/ AGENTS.md <- Included when working in src/frontend/ App.tsx backend/ AGENTS.md <- Included when working in src/backend/ server.ts tests/ AGENTS.md <- Only included when working in tests/ ``` When working on `src/frontend/App.tsx`: * `src/frontend/AGENTS.md` is loaded (current directory) * `src/AGENTS.md` is loaded (parent directory) * `AGENTS.md` at workspace root is loaded via standard rules * `src/backend/AGENTS.md` and `tests/AGENTS.md` are **not** loaded (different branches) ### Use Cases for Hierarchical Rules * **Framework-specific guidelines**: Place React-specific rules in your frontend directory and Node.js rules in your backend directory * **Module-specific conventions**: Define API design patterns in your `api/` directory * **Test-specific rules**: Add testing conventions that only apply when writing tests * **Team boundaries**: Different teams can maintain their own coding standards in their directories ### Important Notes * Only `AGENTS.md` and `CLAUDE.md` files are discovered hierarchically * Files in `.augment/rules/` are only loaded from the workspace root, not from subdirectories * Rules are cached per conversation session to avoid duplicate inclusion * Hierarchical rules are combined with workspace and user rules ## Best Practices for Rules Files 1. **Be Specific**: Provide clear, actionable guidelines rather than vague suggestions 2. **Use Examples**: Include code examples when describing patterns or conventions 3. **Keep Updated**: Regularly review and update rules as your project evolves 4. **Be Concise**: Focus on the most important guidelines to avoid overwhelming the AI 5. **Test Guidelines**: Verify that Auggie follows your rules by testing with sample requests ## Command-Line Flag You can specify a custom rules file when starting Auggie: ```bash theme={null} auggie --rules /path/to/custom-rules.md ``` This will append the specified rules to any workspace guidelines that are automatically loaded. ## See Also * [Skills](/cli/skills) - Extend capabilities with specialized domain knowledge * [Rules & Guidelines for Agent and Chat](/setup-augment/guidelines) - Configure rules in VSCode and JetBrains IDEs * [CLI Reference](/cli/reference) - Complete command-line reference * [Workspace Context](/cli/setup-auggie/workspace-context) - Understanding workspace configuration * [Custom Commands](/cli/custom-commands) - Create reusable command templates # Auggie SDK Source: https://docs.augmentcode.com/cli/sdk Build custom integrations and agents using the Auggie SDK. Build Node.js and TypeScript applications with the Auggie SDK Build Python applications with the Auggie SDK ## Installation ```sh TypeScript theme={null} npm install @augmentcode/auggie-sdk ``` ```sh Python theme={null} pip install auggie-sdk ``` ## Authentication The Auggie SDK supports multiple authentication methods: 1. **Passing API Key Directly (Recommended)** - Provide `apiKey` parameter when initializing 2. **Using Environment Variables** - Set `AUGMENT_API_TOKEN` and `AUGMENT_API_URL` environment variables 3. **Using `settings.json`** - Store credentials in `settings.json` file ### Finding Your API keys **Coming Soon:** Service accounts and team-level tokens will be available for production deployments and CI/CD environments. Running `auggie token print` will print your API keys: ```json theme={null} { "accessToken": "ABC-XYZ-123", // Use as apiKey "tenantURL": "https://...", // Use as apiUrl ... } ``` ## Quick Start ```typescript TypeScript theme={null} import { Auggie } from "@augmentcode/auggie-sdk"; const client = await Auggie.create({ model: "sonnet4.5" }); const response = await client.prompt("What files are in the current directory?"); console.log(response); await client.close(); ``` ```python Python theme={null} from auggie_sdk import Auggie agent = Auggie(model="sonnet4.5") result = agent.run("What is 2 + 2?", return_type=int) print(result) # 4 ``` ## Key Features Both SDKs provide: * **High-level API** - Simple interface for common tasks * **Multiple Output Modes** - String responses, typed returns, streaming, and more * **Codebase Awareness** - Automatic indexing and context from your workspace * **Custom Tools** - Extend Auggie with your own tools and integrations ## TypeScript-Specific Features The TypeScript SDK also includes: * **AI SDK Provider** - Use Augment as a language model provider with [Vercel's AI SDK](https://sdk.vercel.ai/docs) * Compatible with `generateText`, `streamText`, and other AI SDK functions * Full support for tool calling (function calling) * Works with API credentials only (no local Auggie installation needed) * See the [TypeScript SDK documentation](/cli/sdk-typescript#ai-sdk-provider-vercel-ai-sdk) for details # Python SDK Source: https://docs.augmentcode.com/cli/sdk-python Build custom integrations and agents using the Auggie Python SDK. ## About The Auggie Python SDK provides a programmatic interface to Auggie for building custom integrations and agents in Python applications. ## Installation ```sh theme={null} pip install auggie-sdk ``` ## Usage ### Basic Initialization ```python theme={null} from auggie_sdk import Auggie # Simple initialization agent = Auggie(model="sonnet4.5") # Run a task result = agent.run("What is 2 + 2?", return_type=int) print(result) # 4 ``` ### Full Configuration ```python theme={null} from auggie_sdk import Auggie from auggie_sdk.acp import AgentEventListener # Optional: Create a custom event listener class MyListener(AgentEventListener): def on_agent_message_chunk(self, text: str): print(text, end="", flush=True) agent = Auggie( # Working directory for the agent (default: current directory) workspace_root="/path/to/workspace", # Model to use: "haiku4.5" | "sonnet4.5" | "sonnet4" | "gpt5" model="sonnet4.5", # Event listener for real-time updates (optional) listener=MyListener(), # Allow codebase indexing (default: True) allow_indexing=True, # Default timeout in seconds (default: 300) timeout=600, # API key for authentication (optional, sets AUGMENT_API_TOKEN) api_key="your-api-key", # API URL (optional, sets AUGMENT_API_URL) api_url="https://api.augmentcode.com", # Rule file paths (optional) rules=["/path/to/rules.md"], # Additional CLI arguments (optional) cli_args=["--quiet", "--max-turns", "10"] ) # Use the agent result = agent.run("Your question here", return_type=str) print(result) ``` ### Custom CLI Arguments The `cli_args` parameter allows you to pass additional command-line arguments to the Auggie CLI when spawning the agent process. This is useful for passing custom or experimental CLI flags that aren't exposed as dedicated parameters. ```python theme={null} from auggie_sdk import Auggie # Example 1: Limit agent turns and reduce output agent = Auggie( cli_args=["--quiet", "--max-turns", "10"] ) # Example 2: Configure retry behavior and shell agent = Auggie( cli_args=["--retry-timeout", "60", "--shell", "bash"] ) # Example 3: Add custom rules and startup script agent = Auggie( cli_args=[ "--rules", "/path/to/custom-rules.md", "--startup-script", "export MY_VAR=value" ] ) # Example 4: Configure tool permissions agent = Auggie( cli_args=[ "--permission", "web-search:allow", "--permission", "launch-process:ask-user" ] ) ``` **Common CLI arguments:** * `--quiet` - Only show final assistant message * `--max-turns ` - Limit the number of agentic turns * `--retry-timeout ` - Timeout for rate-limit retries (seconds) * `--shell ` - Select shell: bash | zsh | fish | powershell * `--rules ` - Additional rules file (repeatable) * `--permission ` - Set tool permissions with 'tool-name:policy' format * `--startup-script