# XanoScript Documentation

XanoScript is the declarative scripting language for [Xano](https://xano.com), a no-code/low-code backend platform. Use it to define database schemas, API endpoints, functions, scheduled tasks, and AI agents.

## Quick Reference

| Construct           | File Location                          | Purpose                       |
| ------------------- | -------------------------------------- | ----------------------------- |
| `workspace`         | `workspace/{name}.xs`                  | Workspace-level configuration |
| `workspace_trigger` | `workspace/trigger/{name}.xs`          | Workspace event handlers      |
| `table`             | `table/{name}.xs`                      | Database schema definition    |
| `table_trigger`     | `table/trigger/{name}.xs`              | Table event handlers          |
| `api_group`         | `api/{group}/api_group.xs`             | API group definition          |
| `query`             | `api/{group}/{endpoint}_{verb}.xs`     | HTTP API endpoints            |
| `function`          | `function/{path}/{name}.xs`            | Reusable logic blocks         |
| `task`              | `task/{name}.xs`                       | Scheduled/cron jobs           |
| `addon`             | `addon/{name}.xs`                      | Subqueries for related data   |
| `middleware`        | `middleware/{name}.xs`                 | Request/response interceptors |
| `agent`             | `ai/agent/{name}.xs`                   | AI-powered agents             |
| `agent_trigger`     | `ai/agent/trigger/{name}.xs`           | Agent event handlers          |
| `tool`              | `ai/tool/{name}.xs`                    | Tools for AI agents           |
| `mcp_server`        | `ai/mcp_server/{name}.xs`             | MCP server definitions        |
| `mcp_server_trigger`| `ai/mcp_server/trigger/{name}.xs`     | MCP server event handlers     |
| `workflow_test`     | `workflow_test/{name}.xs`              | End-to-end workflow tests     |
| `realtime_channel`  | `realtime/channel/{name}.xs`           | Realtime channel settings     |
| `realtime_trigger`  | `realtime/trigger/{name}.xs`           | Realtime event handlers       |
| `branch`            | `branch.xs`                            | Branch-level configuration    |

**Naming convention:** All folder and file names use `snake_case` (e.g., `user_profile.xs`, `get_all_users_get.xs`).

**Important:** Each `.xs` file must contain exactly one definition. You cannot define multiple tables, functions, queries, or other constructs in a single file.

**The `guid` field (backend-managed — ignore it):** Any construct may carry a top-level `guid = "..."` — a stable identifier Xano assigns and maintains automatically. **Leave it exactly as-is when editing, omit it when writing new code (the backend adds one on save), and never add, change, or remove one unless explicitly asked.**

## Workspace Structure

After pulling from Xano, files are organized using `snake_case` naming:

```
project/
├── branch.xs                        # Branch configuration
├── workspace/
│   ├── my_workspace.xs              # Workspace configuration
│   └── trigger/
│       └── on_deploy.xs             # Workspace triggers
├── api/
│   └── users/                       # API group folder
│       ├── api_group.xs             # API group definition
│       ├── get_all_get.xs           # GET /api:users/get_all
│       ├── get_one_get.xs           # GET /api:users/get_one/{id}  (query name "get_one/{id}" — static prefix avoids collisions with other path-param queries in the group)
│       ├── create_post.xs           # POST /api:users/create
│       └── nested/
│           └── profile_get.xs       # Nested endpoint: GET /api:users/nested/profile
├── function/
│   └── validate_token.xs            # Reusable functions
├── task/
│   └── daily_cleanup.xs             # Scheduled jobs
├── table/
│   ├── users.xs                     # Table schema
│   └── trigger/
│       └── on_user_create.xs        # Table triggers
├── ai/
│   ├── agent/
│   │   ├── support_bot.xs           # AI agents
│   │   └── trigger/
│   │       └── on_message.xs        # Agent triggers
│   ├── tool/
│   │   └── search_docs.xs           # AI tools
│   └── mcp_server/
│       ├── my_server.xs             # MCP server definitions
│       └── trigger/
│           └── on_connect.xs        # MCP server triggers
├── workflow_test/
│   └── checkout_flow.xs             # End-to-end workflow tests
├── middleware/
│   └── auth_check.xs                # Request/response interceptors
├── addon/
│   └── user_posts.xs                # Query addons
├── realtime/
│   ├── channel/
│   │   └── chat_room.xs             # Realtime channels
│   └── trigger/
│       └── on_message.xs            # Realtime triggers
├── static/                          # Frontend files (HTML, CSS, JS)
└── run/                             # Job and service configurations
```

**Key conventions:**
- All folders and files use `snake_case` naming
- API endpoints include the HTTP verb suffix (e.g., `create_post.xs`, `get_one_get.xs`)
- Triggers are nested under `{type}/trigger/` folders
- Nested API paths become nested folders (e.g., `/users/nested/profile` → `api/users/nested/profile_get.xs`)

## Environment Variables

Access with `$env.<name>`. Common built-in variables include `$env.$remote_ip`, `$env.$http_headers`, `$env.$request_method`, `$env.$datasource`, and `$env.$branch`. Custom environment variables are set in the Xano dashboard and accessed as `$env.MY_VAR`.

For the complete list of system variables, see `xano_xanoscript_docs({ topic: "syntax" })`.

## Core Syntax Patterns

### Block Structure

```xs
<construct> "<name>" {
  input { ... }      // Parameters (optional)
  stack { ... }      // Logic
  response = $var    // Output
}
```

### Variable Access

```xs
$input.field        // Input parameters
$var.field          // Stack variables
$auth.id            // Authenticated user ID
$env.MY_VAR         // Environment variable
$db.table.field     // Database field reference (in queries)
$this               // Current item in loops/maps
```

**Reserved Variables:** The following cannot be used as variable names: `$response`, `$output`, `$input`, `$auth`, `$env`, `$db`, `$this`, `$result`, `$index`. See `xano_xanoscript_docs({ topic: "essentials" })` for detailed variable access rules.

### Type Names

XanoScript uses specific type names:

| Type | Description | Example |
|------|-------------|---------|
| `text` | String (not "string") | `text name` |
| `int` | Integer (not "integer") | `int count` |
| `bool` | Boolean (not "boolean") | `bool active` |
| `decimal` | Float/number | `decimal price` |
| `type[]` | Array (not "array" or "list") | `text[] tags` |
| `json` | Arbitrary JSON data | `json metadata` |

### Comments

XanoScript supports `//` single-line comments. They can be placed above an object definition, above inputs, and above stack items:

```xs
// Example
function empty {
  input {
    // Example
    text test
  }

  stack {
    // Example
    var $x1 {
      value = ""
    }
  }

  response = $x1
}
```

**Note:** XanoScript only supports `//` for comments. Other comment styles like `#` are not supported.

### Filters (Pipe Syntax)

```xs
$value|trim|to_lower                 // Chain filters
$input.name|strlen                   // Get length
$array|first                         // First element
($a + $b)|round:2                    // Math with precision
```

## File Frontmatter

Documentation files use frontmatter to specify which file patterns they apply to:

```markdown
---
applyTo: "function/**/*.xs"
---
```

This helps AI tools apply the correct documentation based on the file being edited.

## Getting Started

For common patterns and quick examples, use:
```
xano_xanoscript_docs({ topic: "essentials" })
```

This includes:
- Variable declaration patterns
- Conditional logic (if/elseif/else)
- API requests with error handling
- Database CRUD operations
- Common mistakes to avoid

---

## Documentation Index

Use `xano_xanoscript_docs({ topic: "<topic>" })` to retrieve documentation.

### Tiers (for context-limited models)

Approximate sizes below; the tool reports exact live sizes in the `mode: "index"` listing and derives the advertised token counts from the actual files at runtime.

| Topic      | Description                                                  | Size |
| ---------- | ------------------------------------------------------------ | ---- |
| `survival` | Minimal syntax survival kit for models with <16K context     | ~5KB (~1.2K tokens) |
| `working`  | Complete working reference for models with 16-64K context    | ~17KB (~4.4K tokens) |

Use `xano_xanoscript_docs({ tier: "survival" })` or `xano_xanoscript_docs({ tier: "working" })`.

### Core Language

| Topic        | Description                                          | Key Sections |
| ------------ | ---------------------------------------------------- | ------------ |
| `essentials` | Common patterns, quick examples, mistakes to avoid   | Patterns, Common Mistakes |
| `syntax`     | Expressions, operators, filters, system variables    | Filters, Error Handling |
| `syntax/string-filters` | String manipulation filters                 | Case, Trim, Split, Replace |
| `syntax/array-filters`  | Array manipulation filters                  | Map, Filter, Sort, Group |
| `syntax/functions`      | Built-in functions                          | Math, Date, Crypto, JSON |
| `types`      | Data types, validation, input blocks                 | Validation Filters, Input Blocks |
| `functions`  | Reusable function stacks, async, loops               | Loops, Async Patterns |

### Data

| Topic       | Description                                                | Key Sections |
| ----------- | ---------------------------------------------------------- | ------------ |
| `tables`    | Database schema definitions with indexes and relationships | Indexes, Foreign Keys |
| `database`  | All db.\* operations: query, get, add, edit, patch, delete | Decision Tree, Bulk Ops |
| `addons`    | Reusable subqueries for fetching related data              | Usage Patterns |
| `streaming` | Streaming data from files, requests, and responses         | File Streams, API Streams |

### APIs & Endpoints

| Topic      | Description                                                     | Key Sections |
| ---------- | --------------------------------------------------------------- | ------------ |
| `apis`     | HTTP endpoint definitions with authentication and CRUD patterns | Decision Tree, CRUD Examples |
| `file-uploads` | Uploading files to native Xano storage                     | `file?` input, create_attachment, signed URLs |
| `tasks`    | Scheduled and cron jobs                                         | Cron Syntax, Input Handling |
| `triggers` | Event-driven handlers (table, realtime, workspace, agent, MCP)  | Predefined Inputs, Event Types |
| `realtime` | Real-time channels and events for push updates                  | Channels, Events |

### AI & Agents

| Topic         | Description                                         | Key Sections |
| ------------- | --------------------------------------------------- | ------------ |
| `agents`      | AI agent configuration with LLM providers and tools | LLM Config, Tool Binding |
| `tools`       | AI tools for agents and MCP servers                 | Tool Schema, Parameters |
| `mcp-servers` | MCP server definitions exposing tools               | Server Config, Tool Exposure |

### Integrations

| Topic          | Description                                       | Sub-topics |
| -------------- | ------------------------------------------------- | ---------- |
| `integrations` | Cloud storage, Redis, security, and external APIs | integrations/cloud-storage, integrations/search, integrations/redis, integrations/external-apis, integrations/utilities |

### Configuration

| Topic        | Description                                                            | Key Sections |
| ------------ | ---------------------------------------------------------------------- | ------------ |
| `workspace`  | Workspace-level settings: environment variables, preferences, realtime | Env Variables, Preferences |
| `branch`     | Branch-level settings: middleware, history retention, visual styling   | Middleware Config, History |
| `middleware` | Request/response interceptors for functions, queries, tasks, and tools | Pre/Post Hooks |

### Development

| Topic       | Description                                                | Key Sections |
| ----------- | ---------------------------------------------------------- | ------------ |
| `unit-testing` | Unit tests, mocks, and assertions within functions, APIs, and middleware | Test Syntax, Assertions, Mocking |
| `workflow-tests` | End-to-end workflow tests with data sources and tags   | Data Sources, Tags, Common Patterns |
| `debugging` | Logging, inspecting, and debugging XanoScript execution    | debug.log, Inspection |
| `frontend`  | Static frontend development and deployment                 | File Structure |

### Best Practices

| Topic         | Description                                                  | Key Sections |
| ------------- | ------------------------------------------------------------ | ------------ |
| `performance` | Performance optimization best practices                      | Caching, Query Optimization |
| `security`    | Security best practices for authentication and authorization | Auth Patterns, Token Handling |

