@xano/developer-mcp 2.2.2-beta.1 → 2.2.2-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -218,13 +218,13 @@ For lighter-weight iterative development without pulling the whole workspace, se
218
218
  },
219
219
  {
220
220
  name: "workspace push",
221
- description: "Upload local XanoScript files to a workspace. Default mode is partial (only changed files). Use --sync for a full push. The source directory is the -d/--directory flag (default: current directory), not a positional argument.",
221
+ description: "Upload local XanoScript files to a workspace. Default mode is partial (only changed files). Use --sync for a full push. The source directory is the -d/--directory flag (default: current directory), not a positional argument. A partial push is additive, not declarative: it adds and updates but makes no destructive changes (it won't drop a removed column or relax a constraint), so local files and the live workspace can diverge. Use --sync for destructive changes; --dry-run to preview.",
222
222
  usage: "xano workspace push [options]",
223
223
  flags: [
224
224
  { name: "directory", short: "d", type: "string", required: false, default: ".", description: "Directory containing documents to push (defaults to current directory)" },
225
225
  { name: "workspace", short: "w", type: "string", required: false, description: "Workspace ID (uses profile default if not set)" },
226
226
  { name: "branch", short: "b", type: "string", required: false, description: "Branch label to push to (defaults to live branch or profile branch)" },
227
- { name: "sync", type: "boolean", required: false, default: "false", description: "Full push (default is partial/changed-only). Required for --delete." },
227
+ { name: "sync", type: "boolean", required: false, default: "false", description: "Full push (default is partial/changed-only). Required for --delete and for destructive schema changes (a partial push never drops or relaxes anything)." },
228
228
  { name: "delete", type: "boolean", required: false, default: "false", description: "Delete remote objects not present in local files (requires --sync)" },
229
229
  { name: "dry-run", type: "boolean", required: false, default: "false", description: "Preview changes without applying" },
230
230
  { name: "force", type: "boolean", required: false, default: "false", description: "Skip preview and confirmation prompt (for CI/CD)" },
@@ -125,6 +125,12 @@
125
125
  "priority": 3,
126
126
  "aliases": ["mcp", "model-context-protocol"]
127
127
  },
128
+ "knowledge": {
129
+ "file": "knowledge.md",
130
+ "description": "Agent Knowledge: Skills, Docs, and AGENTS.md Context that steer the Xano AI agent (disclosure modes, scopes, authoring)",
131
+ "applyTo": [],
132
+ "aliases": ["skills", "skill", "docs", "agent-knowledge", "agents-md", "context"]
133
+ },
128
134
  "unit-testing": {
129
135
  "file": "unit-testing.md",
130
136
  "description": "Unit tests, mocks, and assertions within functions, APIs, and middleware",
@@ -184,10 +190,10 @@
184
190
  },
185
191
  "frontend": {
186
192
  "file": "frontend.md",
187
- "description": "Static frontend development and deployment",
193
+ "description": "Static frontend development and deployment (static hosting)",
188
194
  "applyTo": ["static/**/*"],
189
195
  "priority": 3,
190
- "aliases": ["static", "html", "css", "web"]
196
+ "aliases": ["static", "html", "css", "web", "spa", "hosting", "static-host", "deploy"]
191
197
  },
192
198
  "addons": {
193
199
  "file": "addons.md",
@@ -668,6 +668,12 @@ See `xano_xanoscript_docs({ topic: "file-uploads" })` for the full pattern.
668
668
 
669
669
  ---
670
670
 
671
+ ## Validation is syntax-only
672
+
673
+ `xano_validate_xanoscript` checks syntax, not runtime behavior. A `valid` result means the code parses — it can still fail at execution (often a 500). Validation is necessary but not sufficient: after it passes, `push` and run the endpoint once (`validate → push → run`) before trusting the code.
674
+
675
+ ---
676
+
671
677
  ## Related Topics
672
678
 
673
679
  Explore more with `xano_xanoscript_docs({ topic: "<topic>" })`:
@@ -4,158 +4,86 @@ applyTo: "static/**/*"
4
4
 
5
5
  # Frontend
6
6
 
7
- Static frontend development with Xano APIs.
8
-
9
- ## Quick Reference
10
-
11
- ### Directory Structure
12
- ```
13
- static/
14
- ├── index.html // Main entry point
15
- ├── css/
16
- ├── js/
17
- │ └── api.js // Centralized API calls
18
- └── assets/
19
- ```
20
-
21
- ### Key Tools
22
- | Tool | Purpose |
23
- |------|---------|
24
- | `get_xano_api_specifications` | Get OpenAPI specs before frontend work |
25
- | `upload_static_files_to_xano` | Deploy to Xano CDN |
26
-
27
- ---
28
-
29
- ## Base Template
30
-
31
- ```html
32
- <!DOCTYPE html>
33
- <html lang="en">
34
- <head>
35
- <meta charset="utf-8">
36
- <meta name="viewport" content="width=device-width, initial-scale=1">
37
- <title>My App</title>
38
- <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet">
39
- <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
40
- </head>
41
- <body>
42
- <div id="app"></div>
43
- <script src="js/api.js"></script>
44
- <script src="js/app.js"></script>
45
- </body>
46
- </html>
47
- ```
48
-
49
- ---
50
-
51
- ## API Client
52
-
53
- ### Basic Setup (api.js)
54
- ```javascript
55
- const API_BASE = 'https://your-instance.xano.io/api:group';
56
-
57
- async function apiCall(endpoint, options = {}) {
58
- const token = localStorage.getItem('auth_token');
59
- const headers = {
60
- 'Content-Type': 'application/json',
61
- ...(token && { 'Authorization': `Bearer ${token}` })
62
- };
63
-
64
- const response = await fetch(`${API_BASE}${endpoint}`, {
65
- ...options,
66
- headers: { ...headers, ...options.headers }
67
- });
68
-
69
- if (!response.ok) {
70
- throw new Error(`API Error: ${response.status}`);
7
+ Build a static frontend (any framework that emits static output, or plain
8
+ HTML/CSS/JS) that calls your Xano APIs directly, then deploy it to **Xano static
9
+ hosting** (paid plans). There's no server tier — only static files; all dynamic
10
+ data comes from your APIs.
11
+
12
+ Keep frontend source in a **`static/`** directory at the project root, beside the
13
+ backend code.
14
+
15
+ ## Get the API spec first
16
+
17
+ Before wiring calls, get the OpenAPI/Swagger spec for the API group you'll
18
+ consume: the `xano_get_openapi_spec` tool (if exposed), the Meta API `/openapi`
19
+ endpoint (see `xano_meta_api_docs`), or the API group's `…/swagger.json` URL.
20
+ It also drives typed-client codegen in the starter below.
21
+
22
+ ## Two starting points
23
+
24
+ - **Opinionated starter (recommended for apps)** — clone
25
+ [`xano-inc/static_template`](https://github.com/xano-inc/static_template) into
26
+ `static/`: a Vite + React + TS SPA with auth and typed API hooks (generated from
27
+ your Swagger) already wired. Point it at your instance (`VITE_XANO_API_BASE` +
28
+ `VITE_XANO_SWAGGER_URL`) and build. It ships its own docs — follow those.
29
+
30
+ - **Plain static (no build)** — hand-write files into `static/`. Centralize calls
31
+ in one client module that prefixes a base URL and attaches the auth token:
32
+
33
+ ```javascript
34
+ const API_BASE = "https://your-instance.xano.io/api:group";
35
+
36
+ async function apiCall(endpoint, options = {}) {
37
+ const token = localStorage.getItem("auth_token");
38
+ const res = await fetch(`${API_BASE}${endpoint}`, {
39
+ ...options,
40
+ headers: {
41
+ "Content-Type": "application/json",
42
+ ...(token && { Authorization: `Bearer ${token}` }),
43
+ ...options.headers,
44
+ },
45
+ });
46
+ if (!res.ok) throw new Error(`API Error: ${res.status}`);
47
+ return res.json();
71
48
  }
49
+ ```
72
50
 
73
- return response.json();
74
- }
75
-
76
- // CRUD helpers
77
- const api = {
78
- get: (endpoint) => apiCall(endpoint),
79
- post: (endpoint, data) => apiCall(endpoint, {
80
- method: 'POST',
81
- body: JSON.stringify(data)
82
- }),
83
- patch: (endpoint, data) => apiCall(endpoint, {
84
- method: 'PATCH',
85
- body: JSON.stringify(data)
86
- }),
87
- delete: (endpoint) => apiCall(endpoint, { method: 'DELETE' })
88
- };
89
- ```
90
-
91
- ---
51
+ Auth follows the same pattern: `POST /auth/login` (or `/auth/signup`) returns an
52
+ `authToken`; store it in `localStorage`, send it as `Authorization: Bearer`, and
53
+ remove it to log out.
92
54
 
93
- ## Authentication
55
+ ## Deploy
94
56
 
95
- ### Login
96
- ```javascript
97
- async function login(email, password) {
98
- const { authToken } = await api.post('/auth/login', { email, password });
99
- localStorage.setItem('auth_token', authToken);
100
- return authToken;
101
- }
102
- ```
57
+ Deploy with the **`xano` CLI** (`npm i -g @xano/cli`, then `xano auth`). A
58
+ **build** is an uploaded snapshot; a **deploy** points an environment (`dev` or
59
+ `prod`, each its own URL) at a build.
103
60
 
104
- ### Signup
105
- ```javascript
106
- async function signup(email, password, name) {
107
- const { authToken } = await api.post('/auth/signup', {
108
- email, password, name
109
- });
110
- localStorage.setItem('auth_token', authToken);
111
- return authToken;
112
- }
61
+ ```bash
62
+ xano static_host create my-app # one-time
63
+ xano static_host build push my-app -d ./static -n "v1.0.0" # push snapshot
64
+ xano static_host deploy my-app --build_id <id> --env dev # then --env prod
113
65
  ```
114
66
 
115
- ### Logout
116
- ```javascript
117
- function logout() {
118
- localStorage.removeItem('auth_token');
119
- window.location.href = '/login.html';
120
- }
121
- ```
67
+ When `static/` has a `package.json`, **Xano runs your `build` script
68
+ server-side** on push. Changes aren't auto-synced — push a new build to publish.
69
+ Full reference (flags, `build pull`, rollback, git integration):
70
+ `xano_cli_docs(topic='static_host')`.
122
71
 
123
- ### Get Current User
124
- ```javascript
125
- async function getCurrentUser() {
126
- return api.get('/auth/me');
127
- }
128
- ```
72
+ **After deploy:** the environment URL can 404 briefly until the build
73
+ propagates — allow a few seconds before treating a deploy as failed. Assets are
74
+ cached by filename, so redeploys can serve stale files to returning visitors;
75
+ version asset URLs (e.g. `app.js?v=2`) when an update must take effect immediately.
129
76
 
130
- ---
131
-
132
- ## Deployment
77
+ ## Best practices
133
78
 
134
- Deploy static files to Xano CDN:
135
-
136
- ```
137
- invoke upload_static_files_to_xano
138
- ```
139
-
140
- The tool will:
141
- 1. Bundle files from `static/`
142
- 2. Upload to Xano CDN
143
- 3. Return hosted URL
144
-
145
- ---
146
-
147
- ## Best Practices
148
-
149
- 1. **Get API specs first** - Use `get_xano_api_specifications` before coding
150
- 2. **Centralize API calls** - Single `api.js` file
151
- 3. **Store tokens securely** - localStorage for web, secure storage for mobile
152
-
153
- ---
79
+ - **Never ship secrets** — the bundle is world-readable. The only credential is
80
+ the user's own auth token in `localStorage`. No API keys or DB credentials in
81
+ client code, including any `VITE_*` variable (inlined into the bundle).
154
82
 
155
83
  ## Related Topics
156
84
 
157
- | Topic | Description |
158
- |-------|-------------|
159
- | `apis` | Backend API endpoints |
85
+ | Topic | Description |
86
+ | ----------- | ----------------------- |
87
+ | `apis` | Backend API endpoints |
160
88
  | `workspace` | Workspace configuration |
161
- | `security` | CORS and authentication |
89
+ | `security` | CORS and authentication |
@@ -0,0 +1,146 @@
1
+ ---
2
+ applyTo: []
3
+ ---
4
+
5
+ # Skills & Docs (Agent Knowledge)
6
+
7
+ Teach the Xano AI agent how to work in your workspace — standing rules, reference docs, and repeatable procedures it follows when building your backend.
8
+
9
+ > **TL;DR:** Agent Knowledge has three kinds of files. **Context** (`AGENTS.md`) is always loaded — standing rules for every run. A **Doc** is a single markdown file the agent reads for reference when a task calls for it. A **Skill** is a folder (`SKILL.md` + optional reference files) the agent follows step by step. Control *when* each loads with a disclosure mode, and *who* sees it with a scope.
10
+
11
+ ---
12
+
13
+ ## Quick Reference
14
+
15
+ | Type | Lives at | Best for | Loading |
16
+ |------|----------|----------|---------|
17
+ | **Context** | `AGENTS.md` | Standing rules & conventions the agent must always know | Always, in full |
18
+ | **Doc** | `docs/<name>.md` | Facts, specs, guidelines the agent reads on demand | On demand |
19
+ | **Skill** | `skills/<name>/SKILL.md` | Repeatable, multi-step procedures | On demand or manual |
20
+ | **Reference** | a file inside a skill | Supporting detail a skill step needs | Pulled in by its skill |
21
+
22
+ **Disclosure** (when it loads): `Always included` · `On demand` · `Manual`
23
+ **Scope** (who sees it): `Workspace` (everyone) · `Private` (only you)
24
+
25
+ ---
26
+
27
+ ## The three knowledge types
28
+
29
+ ### Context — your `AGENTS.md`
30
+
31
+ A single `AGENTS.md` file that is **injected into every agent session, in full**. It's the right home for the conventions, rules, and patterns you want the agent to repeat on every run: the backend's purpose, the data model's shape, naming conventions, the auth model, standard error shapes.
32
+
33
+ Because every line is loaded on every run, every line has a permanent context cost — so keep it lean. Capture the *shape* and the *non-obvious*; let the agent drill into specifics with its own tools when it needs them.
34
+
35
+ ```markdown
36
+ # Acme Orders API
37
+
38
+ > Backend for the Acme storefront — handles auth, catalog, and checkout.
39
+
40
+ ## Data model
41
+ | Table | Purpose | Key fields / relationships |
42
+ | ------ | --------------- | ---------------------------- |
43
+ | users | Auth + profile | id, email; has many `orders` |
44
+ | orders | Customer orders | id, user_id → users, status |
45
+
46
+ Orders are soft-deleted (`deleted_at`), never hard-deleted.
47
+
48
+ ## Conventions
49
+ - Auth: JWT in `Authorization: Bearer`. Protect every non-public endpoint.
50
+ - Errors: return `{ error: { code, message } }`, never a bare string.
51
+ ```
52
+
53
+ > **Tip:** Use the **`init`** skill to scaffold `AGENTS.md` — it inspects your workspace (read-only) and works with you to capture purpose, data model, APIs, logic, and conventions, asking one question at a time rather than guessing.
54
+
55
+ ### Doc — reference material
56
+
57
+ A single markdown file at `docs/<name>.md` that the agent reads **when a task calls for it**. Best for facts, specs, and guidelines — a style guide, an external API's quirks, a domain glossary. The agent sees the title and description up front and pulls in the full file only when relevant, so docs don't spend context on every run.
58
+
59
+ ### Skill — a repeatable procedure
60
+
61
+ A folder at `skills/<name>/` containing a `SKILL.md` (and optional reference files) that the agent **follows step by step**. Best for multi-step workflows that recur — "scaffold a CRUD API for a table", "apply rate limiting to an endpoint", "add audit logging to a mutation".
62
+
63
+ ```markdown
64
+ ---
65
+ name: rate-limit-endpoint
66
+ description: Apply rate limiting to an endpoint. Use when a user asks to
67
+ throttle, protect, or rate-limit an endpoint, or guard it from abuse.
68
+ ---
69
+
70
+ # Rate Limit an Endpoint
71
+
72
+ Add a Rate Limit function to the start of an endpoint's stack so repeated
73
+ calls from the same caller are rejected before they do work.
74
+
75
+ ## Steps
76
+ 1. Confirm which endpoint and the limit (requests per window) with the user.
77
+ 2. Add a `precondition` that checks the caller's recent request count.
78
+ 3. Return a 429 with a clear message when the limit is exceeded.
79
+ ```
80
+
81
+ > **Tip:** Use the **`create-skill`** skill to author one — it captures *what* the agent should do, *when* it should trigger, and *what good looks like*, then writes a well-formed `SKILL.md`.
82
+
83
+ ---
84
+
85
+ ## Disclosure — controlling when knowledge loads
86
+
87
+ Each doc and skill has a disclosure mode that decides how it enters the agent's context:
88
+
89
+ | Mode | What loads | Use when |
90
+ |------|-----------|----------|
91
+ | **Always included** | The full file, every run | Rules the agent must never miss. Use sparingly — it spends context on every run. |
92
+ | **On demand** | Only the title + description up front; the agent pulls the full file when it judges it relevant | The default. Reference material and most skills. |
93
+ | **Manual** | Nothing automatically; loads only when you name it in the prompt | Niche or expensive procedures you want to invoke deliberately. |
94
+
95
+ `AGENTS.md` is always *Always included* — that's the whole point of Context. Reserve *Always included* on docs and skills for the rare thing the agent genuinely must read every time.
96
+
97
+ ---
98
+
99
+ ## Scope — controlling who sees it
100
+
101
+ | Scope | Who | Use for |
102
+ |-------|-----|---------|
103
+ | **Workspace** | Everyone in the workspace | Shared conventions, team procedures, project docs |
104
+ | **Private** | Only you | Personal helpers and drafts you're still refining |
105
+
106
+ ---
107
+
108
+ ## Writing knowledge the agent actually follows
109
+
110
+ The same principles run through good Context, Docs, and Skills:
111
+
112
+ - **Write a description that earns its place.** For docs and skills, the description is the *only* text always loaded — it's what the agent uses to decide whether to pull in the rest. Be explicit and specific: name the exact situations and phrases that should trigger it. A vague description means the file never gets used (or gets used at the wrong time).
113
+ - **Explain *why*, not just *what*.** Rigid commands ("ALWAYS do X") are brittle — the agent can't adapt when a situation differs slightly. Give the reasoning instead, so it applies the rule correctly in cases you didn't foresee. Weak: "Validate input before saving." Better: "Validate input before saving — bad records are far harder to find and fix once they're in your live tables."
114
+ - **Keep it lean.** Every line costs context the agent could spend reasoning. Cut preamble, ceremony, and anything the agent already knows.
115
+ - **Put rules in `AGENTS.md`, procedures in skills.** Workspace-wide conventions (naming, auth, error shapes) belong in `AGENTS.md`, which is always loaded. A skill is for a repeatable *workflow* — it should *assume* those conventions and use them, not restate them.
116
+ - **Generalize past the example.** A skill is usually born from one concrete request. Write the general pattern, not the one case, so it helps with the whole class of tasks.
117
+ - **Add a guardrail before anything hard to reverse.** Have a skill confirm with the user before a destructive change (deleting a table, dropping an endpoint).
118
+
119
+ ---
120
+
121
+ ## Common Mistakes
122
+
123
+ ❌ **Putting a one-off task in a skill.** Skills are for workflows that recur. A single task is faster to just ask for.
124
+ ✅ Create a skill only when the same multi-step workflow comes up again and again.
125
+
126
+ ❌ **Restating `AGENTS.md` conventions inside a skill.** Duplicated instructions drift out of sync and bloat the body.
127
+ ✅ Assume `AGENTS.md` is loaded; reference its conventions and use them.
128
+
129
+ ❌ **Stuffing reference material into `AGENTS.md` to "make sure the agent has it".** It then pays that cost on every run.
130
+ ✅ Put reference material in a **Doc** (on demand). Reserve `AGENTS.md` for rules that apply every time.
131
+
132
+ ❌ **A vague skill description** ("helps with endpoints").
133
+ ✅ A pushy, specific one that names the trigger: "Apply rate limiting to an endpoint. Use when a user asks to throttle or protect an endpoint from abuse."
134
+
135
+ ❌ **Marking many skills "Always included".**
136
+ ✅ Default to **On demand**; reserve *Always included* for the rare thing the agent must read every time.
137
+
138
+ ---
139
+
140
+ ## Related Topics
141
+
142
+ | Topic | Description |
143
+ |-------|-------------|
144
+ | `agents` | XanoScript `agent` construct — LLM providers and tools |
145
+ | `tools` | Functions an agent can execute |
146
+ | `workspace` | Workspace-level settings and preferences |
@@ -4,52 +4,91 @@ applyTo: "middleware/*.xs"
4
4
 
5
5
  # Middleware
6
6
 
7
- Middleware intercepts and processes requests before and after your functions, queries, tasks, and tools execute.
7
+ > **TL;DR:** Declare a middleware once (`middleware <name> { … }`), then attach it
8
+ > with a `middleware = { pre: [...], post: [...] }` block on a **query/API**, a
9
+ > **function**, or an **API group**. One middleware object serves both phases;
10
+ > branch on `$input.type` (`"pre"` | `"post"`). Its `input` block is fixed to
11
+ > `vars` + `type` — custom parameters are stripped.
12
+
13
+ Middleware intercepts requests before (`pre`) and after (`post`) your queries,
14
+ functions, tasks, and tools run. You define the middleware in one place and attach
15
+ it to the constructs that should use it.
8
16
 
9
17
  ## Quick Reference
10
18
 
11
19
  ```xs
12
- middleware "<name>" {
13
- description = "What this middleware does"
14
- exception_policy = "silent" | "rethrow" | "critical"
15
- response_strategy = "merge" | "replace"
16
- input { ... }
17
- stack { ... }
18
- response = $result
20
+ // 1. Declare the middleware (the input block is fixed — see Input Contract)
21
+ middleware add_metadata {
22
+ input {
23
+ json vars
24
+ enum type {
25
+ values = ["pre", "post"]
26
+ }
27
+ }
28
+
29
+ stack {
30
+ conditional {
31
+ if ($input.type == "post") {
32
+ // post-phase work
33
+ }
34
+ else {
35
+ // pre-phase work
36
+ }
37
+ }
38
+ }
39
+
40
+ response = { server_time: now }
41
+ response_strategy = "merge"
42
+ exception_policy = "silent"
19
43
  }
20
44
  ```
21
45
 
22
- ### Required Blocks
23
- | Block | Purpose |
24
- |-------|---------|
25
- | `input` | Define parameters passed to middleware |
26
- | `stack` | Processing logic |
27
- | `response` | Output returned to caller |
46
+ ```xs
47
+ // 2. Attach it — reference the middleware by name
48
+ query list_items verb=GET {
49
+ api_group = "catalog"
28
50
 
29
- ### Optional Attributes
30
- | Attribute | Values | Default | Description |
31
- |-----------|--------|---------|-------------|
32
- | `description` | text | - | Documents middleware purpose |
33
- | `exception_policy` | `silent`, `rethrow`, `critical` | `rethrow` | How to handle errors |
34
- | `response_strategy` | `merge`, `replace` | `merge` | How response combines with original |
51
+ stack {
52
+ db.query "items" { } as $items
53
+ }
54
+
55
+ response = $items
56
+ middleware = {
57
+ pre : [{name: "rate_limit"}]
58
+ post: [{name: "add_metadata"}]
59
+ }
60
+ }
61
+ ```
62
+
63
+ | Piece | Purpose |
64
+ |-------|---------|
65
+ | `middleware <name> { … }` | The reusable definition |
66
+ | `input { json vars; enum type { … } }` | Fixed system inputs (see Input Contract) |
67
+ | `response_strategy` | `merge` (default) or `replace` — how the middleware response combines |
68
+ | `exception_policy` | `silent` (default), `rethrow`, or `critical` |
69
+ | `middleware = { pre: [...], post: [...] }` | Attaches middleware to a construct or group by name |
35
70
 
36
71
  ---
37
72
 
38
- ## Basic Structure
73
+ ## Declaring a Middleware
39
74
 
40
75
  ```xs
41
- middleware "log_request" {
76
+ middleware log_request {
42
77
  description = "Logs all incoming requests"
43
78
 
44
79
  input {
45
- json request_data
80
+ json vars
81
+ enum type {
82
+ values = ["pre", "post"]
83
+ }
46
84
  }
47
85
 
48
86
  stack {
87
+ var $timestamp { value = now }
49
88
  debug.log {
50
89
  value = {
51
- timestamp: now,
52
- data: $input.request_data
90
+ timestamp: $timestamp,
91
+ data: $input.vars
53
92
  }
54
93
  }
55
94
  }
@@ -58,70 +97,237 @@ middleware "log_request" {
58
97
  }
59
98
  ```
60
99
 
100
+ ### Required Blocks
101
+ | Block | Required | Purpose |
102
+ |-------|----------|---------|
103
+ | `input` | Yes | Fixed system inputs (`vars`, `type`) — see Input Contract |
104
+ | `stack` | Yes | Processing logic |
105
+ | `response` | No | Output returned to the caller (omit it freely) |
106
+
107
+ Omitting `input` or `stack` is a syntax error. Omitting `response` is fine.
108
+
109
+ ### Optional Attributes
110
+ | Attribute | Values | Default | Description |
111
+ |-----------|--------|---------|-------------|
112
+ | `description` | text | - | Documents the middleware (stored as a leading comment) |
113
+ | `exception_policy` | `silent`, `rethrow`, `critical` | `silent` | How errors are handled |
114
+ | `response_strategy` | `merge`, `replace` | `merge` | How the middleware response combines with the original |
115
+
116
+ Values outside the listed enums are rejected (`Input "…" is not one of the allowable values.`).
117
+
118
+ > The quoted name (`middleware "<name>"`) parses, but the canonical form is
119
+ > unquoted: `middleware <name> { … }`. There is **no** `type` attribute on the
120
+ > declaration — `type = "post"` fails with `Invalid block: type`. Which phase a
121
+ > middleware runs in is decided where you attach it, not here.
122
+
123
+ ---
124
+
125
+ ## Input Contract (footgun)
126
+
127
+ A middleware's `input` block is **fixed**. It is always normalised to exactly two
128
+ system inputs, and **any custom parameters you add are silently discarded on push**:
129
+
130
+ ```xs
131
+ // ❌ These custom params are stripped — $input.token / $input.user_id become null
132
+ input {
133
+ text token
134
+ int user_id
135
+ }
136
+
137
+ // ✅ The only inputs that survive — this is what every middleware receives
138
+ input {
139
+ json vars // request (pre) or response (post) payload context
140
+ enum type { // which phase this invocation is running in
141
+ values = ["pre", "post"]
142
+ }
143
+ }
144
+ ```
145
+
146
+ Read middleware data through `$input.vars` and branch on `$input.type` — never
147
+ through named custom parameters.
148
+
149
+ ### Pre vs Post phases
150
+
151
+ There is **one middleware object per name, and it serves both phases**. The same
152
+ `stack` runs for the pre and the post invocation; `$input.type` (`"pre"` |
153
+ `"post"`) tells you which one you are in. Branch on it to do pre-work vs post-work
154
+ in a single middleware:
155
+
156
+ ```xs
157
+ stack {
158
+ conditional {
159
+ if ($input.type == "pre") {
160
+ // runs BEFORE the endpoint — inspect $input.vars (the request);
161
+ // short-circuit with a precondition to block the request.
162
+ }
163
+ else {
164
+ // runs AFTER the endpoint — $input.vars carries the response;
165
+ // transform or augment it (combined per response_strategy).
166
+ }
167
+ }
168
+ }
169
+ ```
170
+
171
+ ---
172
+
173
+ ## Attaching Middleware
174
+
175
+ A middleware does nothing until it is **attached**. Attach it with a `middleware`
176
+ block that lists middleware by name for the `pre` and/or `post` phase:
177
+
178
+ ```xs
179
+ middleware = {
180
+ pre : [{name: "rate_limit"}]
181
+ post: [{name: "add_metadata"}]
182
+ }
183
+ ```
184
+
185
+ Both lists are optional and independent — supply only the phase you need. A list
186
+ can hold more than one middleware, and they run in the order written:
187
+
188
+ ```xs
189
+ middleware = {
190
+ pre: [{name: "rate_limit"}, {name: "auth_check"}]
191
+ }
192
+ ```
193
+
194
+ You can attach middleware at three scopes:
195
+
196
+ ### On a query / API endpoint (per-endpoint)
197
+
198
+ ```xs
199
+ query create_order verb=POST {
200
+ api_group = "orders"
201
+
202
+ input {
203
+ json order
204
+ }
205
+
206
+ stack {
207
+ db.add "orders" { data = $input.order } as $new
208
+ }
209
+
210
+ response = $new
211
+ middleware = {
212
+ pre : [{name: "rate_limit"}]
213
+ post: [{name: "add_metadata"}]
214
+ }
215
+ }
216
+ ```
217
+
218
+ ### On a function (function-stack)
219
+
220
+ ```xs
221
+ function process_payment {
222
+ input {
223
+ decimal amount
224
+ }
225
+
226
+ stack {
227
+ var $result { value = { charged: $input.amount } }
228
+ }
229
+
230
+ response = $result
231
+ middleware = {
232
+ post: [{name: "audit_log"}]
233
+ }
234
+ }
235
+ ```
236
+
237
+ ### On an API group (applies to the whole group)
238
+
239
+ Attach a `middleware` block to the `api_group` declaration to run it for every
240
+ endpoint in that group:
241
+
242
+ ```xs
243
+ api_group orders {
244
+ canonical = "orders_grp"
245
+ middleware = {
246
+ pre : [{name: "rate_limit"}]
247
+ post: [{name: "add_metadata"}]
248
+ }
249
+ }
250
+ ```
251
+
252
+ > **Workspace-wide (global) middleware is configured in the Xano dashboard.** The
253
+ > `middleware` block is only valid on queries, functions, and API groups — placing
254
+ > it on the `workspace` declaration fails with `Invalid block: middleware`. To run
255
+ > a middleware across the whole workspace, attach it from the dashboard's
256
+ > middleware settings.
257
+
258
+ > ⚠️ **Middleware names must match exactly.** A name that doesn't resolve to an
259
+ > existing middleware is silently blanked (`{name: ""}`) on push, and the endpoint
260
+ > then runs with no middleware — no error at push or request time. Double-check the
261
+ > spelling against the middleware's declared name.
262
+
61
263
  ---
62
264
 
63
265
  ## Exception Policies
64
266
 
65
- Control how middleware handles errors:
267
+ Control how errors thrown inside the middleware are handled.
66
268
 
67
- ### silent
68
- Errors are caught and ignored. Execution continues normally.
269
+ ### silent (default)
270
+ Errors are caught and ignored; execution continues.
69
271
 
70
272
  ```xs
71
- middleware "optional_enrichment" {
273
+ middleware optional_enrichment {
72
274
  exception_policy = "silent"
73
275
 
74
276
  input {
75
- int user_id
277
+ json vars
278
+ enum type { values = ["pre", "post"] }
76
279
  }
77
280
 
78
281
  stack {
79
- // If this fails, request continues without enrichment
80
- api.call "external_service" {
81
- url = "https://api.example.com/enrich/" ~ $input.user_id
282
+ // If this fails, the request continues without enrichment
283
+ api.request {
284
+ url = "https://api.example.com/enrich"
285
+ method = "GET"
82
286
  } as $enriched
83
287
  }
84
288
 
85
- response = $enriched
289
+ response = { enrichment: $enriched }
86
290
  }
87
291
  ```
88
292
 
89
- ### rethrow (default)
90
- Errors are passed through to the caller. Standard error handling applies.
293
+ ### rethrow
294
+ Errors are passed through to the caller; standard error handling applies.
91
295
 
92
296
  ```xs
93
- middleware "validate_token" {
297
+ middleware validate_token {
94
298
  exception_policy = "rethrow"
95
299
 
96
300
  input {
97
- text token
301
+ json vars
302
+ enum type { values = ["pre", "post"] }
98
303
  }
99
304
 
100
305
  stack {
101
- precondition ($input.token|strlen > 0) {
306
+ precondition (($input.vars|get:"token"|strlen) > 0) {
102
307
  error_type = "accessdenied"
103
308
  error = "Token required"
104
309
  }
105
310
  }
106
311
 
107
- response = { valid: true }
312
+ response = null
108
313
  }
109
314
  ```
110
315
 
111
316
  ### critical
112
- Errors are treated as critical failures. Request is immediately terminated.
317
+ Errors are treated as critical failures and terminate the request immediately.
113
318
 
114
319
  ```xs
115
- middleware "security_check" {
320
+ middleware security_check {
116
321
  exception_policy = "critical"
117
322
 
118
323
  input {
119
- text ip_address
324
+ json vars
325
+ enum type { values = ["pre", "post"] }
120
326
  }
121
327
 
122
328
  stack {
123
329
  db.query "blocked_ips" {
124
- where = $db.blocked_ips.ip == $input.ip_address
330
+ where = $db.blocked_ips.ip == $env.$remote_ip
125
331
  return = { type: "exists" }
126
332
  } as $is_blocked
127
333
 
@@ -131,7 +337,7 @@ middleware "security_check" {
131
337
  }
132
338
  }
133
339
 
134
- response = { allowed: true }
340
+ response = null
135
341
  }
136
342
  ```
137
343
 
@@ -139,54 +345,68 @@ middleware "security_check" {
139
345
 
140
346
  ## Response Strategies
141
347
 
142
- Control how middleware response combines with the original response:
348
+ Control how the middleware's `response` combines with the endpoint's response.
349
+ This applies to the **post** phase, where `$input.vars` carries the response.
143
350
 
144
351
  ### merge (default)
145
- Middleware response is merged with original response.
352
+ The middleware response is merged into the original response.
146
353
 
147
354
  ```xs
148
- middleware "add_metadata" {
355
+ middleware add_metadata {
149
356
  response_strategy = "merge"
150
357
 
151
358
  input {
359
+ json vars
360
+ enum type { values = ["pre", "post"] }
152
361
  }
153
362
 
154
363
  stack {
155
- var $meta {
156
- value = {
157
- server_time: now,
158
- version: "1.0.0"
159
- }
160
- }
364
+ var $server_time { value = now }
161
365
  }
162
366
 
163
- response = { _meta: $meta }
367
+ response = {
368
+ _meta: {
369
+ server_time: $server_time,
370
+ version: "1.0.0"
371
+ }
372
+ }
164
373
  }
165
374
  // Original: { data: [...] }
166
- // Result: { data: [...], _meta: { server_time: ..., version: "1.0.0" } }
375
+ // Result: { data: [...], _meta: { server_time: ..., version: "1.0.0" } }
167
376
  ```
168
377
 
378
+ > ⚠️ **`now` only evaluates as a direct value.** Bare `now` returns the current
379
+ > timestamp when it is the whole value of a `var` or a top-level entry of the
380
+ > `response` object. Nested **inside** a `response` object literal (e.g. under
381
+ > `_meta`) it is emitted as the literal string `"now"`. Compute it into a `var`
382
+ > first and reference that var:
383
+ > ```xs
384
+ > stack { var $server_time { value = now } }
385
+ > response = { _meta: { server_time: $server_time } } // ✅ real timestamp
386
+ > ```
387
+
169
388
  ### replace
170
- Middleware response completely replaces original response.
389
+ The middleware response completely replaces the original response.
171
390
 
172
391
  ```xs
173
- middleware "transform_response" {
392
+ middleware wrap_response {
174
393
  response_strategy = "replace"
175
394
 
176
395
  input {
177
- json original_response
396
+ json vars
397
+ enum type { values = ["pre", "post"] }
178
398
  }
179
399
 
180
400
  stack {
181
- var $transformed {
401
+ var $wrapped {
182
402
  value = {
183
403
  success: true,
184
- payload: $input.original_response
404
+ payload: $input.vars
185
405
  }
186
406
  }
187
407
  }
188
408
 
189
- response = $transformed
409
+ response = $wrapped
190
410
  }
191
411
  ```
192
412
 
@@ -194,116 +414,153 @@ middleware "transform_response" {
194
414
 
195
415
  ## Common Patterns
196
416
 
197
- ### Request Logging
417
+ Every middleware receives the same two inputs (`vars`, `type`). Read request or
418
+ response data from `$input.vars` and use `$input.type` to act only in the phase you
419
+ want.
420
+
421
+ ### Audit logging (post)
198
422
 
199
423
  ```xs
200
- middleware "audit_log" {
201
- description = "Logs all API requests for audit trail"
424
+ middleware audit_log {
425
+ description = "Logs requests for an audit trail"
202
426
  exception_policy = "silent"
203
427
 
204
428
  input {
205
- text endpoint
206
- text method
207
- json request_body?
208
- int user_id?
429
+ json vars
430
+ enum type { values = ["pre", "post"] }
209
431
  }
210
432
 
211
433
  stack {
212
- db.add "audit_log" {
213
- data = {
214
- endpoint: $input.endpoint,
215
- method: $input.method,
216
- request_body: $input.request_body,
217
- user_id: $input.user_id,
218
- ip_address: $env.$remote_ip,
219
- created_at: now
434
+ conditional {
435
+ if ($input.type == "post") {
436
+ db.add "audit_log" {
437
+ data = {
438
+ context: $input.vars,
439
+ ip_address: $env.$remote_ip,
440
+ created_at: now
441
+ }
442
+ }
220
443
  }
221
444
  }
222
445
  }
223
-
224
- response = null
225
446
  }
226
447
  ```
227
448
 
228
- ### Rate Limiting
449
+ ### Rate limiting (pre)
229
450
 
230
451
  ```xs
231
- middleware "rate_limit" {
232
- description = "Enforces rate limits per user"
233
- exception_policy = "rethrow"
452
+ middleware rate_limit {
453
+ description = "Limits requests per client IP"
234
454
 
235
455
  input {
236
- int user_id
237
- int max_requests?=100
238
- int window_seconds?=60
456
+ json vars
457
+ enum type { values = ["pre", "post"] }
239
458
  }
240
459
 
241
460
  stack {
242
- redis.ratelimit {
243
- key = "ratelimit:" ~ $input.user_id
244
- max = $input.max_requests
245
- ttl = $input.window_seconds
246
- error = "Rate limit exceeded"
461
+ conditional {
462
+ if ($input.type == "pre") {
463
+ redis.ratelimit {
464
+ key = "ratelimit:" ~ $env.$remote_ip
465
+ max = 100
466
+ ttl = 60
467
+ error = "Rate limit exceeded"
468
+ }
469
+ }
247
470
  }
248
471
  }
249
-
250
- response = null
251
472
  }
252
473
  ```
253
474
 
254
- ### Response Caching
475
+ ### Response caching (post)
255
476
 
256
477
  ```xs
257
- middleware "cache_response" {
478
+ middleware cache_response {
258
479
  description = "Caches responses in Redis"
259
480
  exception_policy = "silent"
260
481
 
261
482
  input {
262
- text cache_key
263
- int ttl_seconds?=300
264
- json response_data
483
+ json vars
484
+ enum type { values = ["pre", "post"] }
265
485
  }
266
486
 
267
487
  stack {
268
- redis.set {
269
- key = $input.cache_key
270
- value = $input.response_data|json_encode
271
- expire = $input.ttl_seconds
488
+ conditional {
489
+ if ($input.type == "post") {
490
+ redis.set {
491
+ key = "cache:" ~ ($input.vars|json_encode)
492
+ data = $input.vars
493
+ ttl = 300
494
+ }
495
+ }
272
496
  }
273
497
  }
274
-
275
- response = null
276
498
  }
277
499
  ```
278
500
 
279
501
  ---
280
502
 
281
- ## Applying Middleware
503
+ ## Common Mistakes
282
504
 
283
- Middleware is configured at the branch level. See `xano_xanoscript_docs({ topic: "branch" })` for configuration details.
505
+ ❌ **Adding custom inputs to a middleware:**
506
+ ```xs
507
+ input {
508
+ text token // stripped on push — $input.token is null at runtime
509
+ }
510
+ ```
511
+ ✅ **Read from the fixed `vars` input:**
512
+ ```xs
513
+ input {
514
+ json vars
515
+ enum type { values = ["pre", "post"] }
516
+ }
517
+ // ... reference $input.vars, e.g. ($input.vars|get:"token")
518
+ ```
284
519
 
520
+ ❌ **Expecting a `type` attribute to pick the phase:**
285
521
  ```xs
286
- branch "production" {
287
- middleware = {
288
- query: {
289
- pre: ["validate_token", "rate_limit"],
290
- post: ["audit_log", "cache_response"]
291
- },
292
- function: {
293
- pre: ["validate_token"],
294
- post: ["audit_log"]
295
- }
522
+ middleware log_request {
523
+ type = "post" // Invalid block: type
524
+ ...
525
+ }
526
+ ```
527
+ ✅ **One object serves both phases — branch on `$input.type`:**
528
+ ```xs
529
+ stack {
530
+ conditional {
531
+ if ($input.type == "post") { /* ... */ }
296
532
  }
297
533
  }
298
534
  ```
299
535
 
536
+ ❌ **Misspelling the attached name:**
537
+ ```xs
538
+ middleware = { pre: [{name: "rate_limitr"}] } // silently becomes {name: ""} — no middleware runs
539
+ ```
540
+ ✅ **Match the declared middleware name exactly:**
541
+ ```xs
542
+ middleware = { pre: [{name: "rate_limit"}] }
543
+ ```
544
+
545
+ ❌ **Putting a middleware block on the workspace declaration:**
546
+ ```xs
547
+ workspace "my-app" {
548
+ middleware = { pre: [...] } // Invalid block: middleware
549
+ }
550
+ ```
551
+ ✅ **Attach on a query, function, or API group — or configure workspace-wide
552
+ middleware in the dashboard.**
553
+
300
554
  ---
301
555
 
302
556
  ## Best Practices
303
557
 
304
- 1. **Keep middleware focused** - Each middleware should do one thing well
305
- 2. **Use appropriate exception policies** - Critical for security, silent for optional enrichment
306
- 3. **Consider performance** - Middleware runs on every request; log even silent failures
558
+ 1. **Keep middleware focused** — each one should do a single thing well.
559
+ 2. **Choose the exception policy deliberately** — `critical` for security gates,
560
+ `silent` for optional enrichment.
561
+ 3. **Attach at the right scope** — per-endpoint for targeted logic, on the API
562
+ group for cross-cutting concerns shared by every endpoint in the group.
563
+ 4. **Mind performance** — middleware runs on every matching request.
307
564
 
308
565
  ---
309
566
 
@@ -311,7 +568,7 @@ branch "production" {
311
568
 
312
569
  | Topic | Description |
313
570
  |-------|-------------|
314
- | `branch` | Branch-level middleware configuration |
315
- | `security` | Authentication and authorization patterns |
316
571
  | `apis` | API endpoint request/response lifecycle |
317
- | `performance` | Performance optimization strategies |
572
+ | `functions` | Reusable function stacks |
573
+ | `security` | Authentication and authorization patterns |
574
+ | `integrations/redis` | Rate limiting and caching primitives |
@@ -323,6 +323,7 @@ table "order" {
323
323
  2. **Use `auth = true`** only for the authentication table (typically just `user`)
324
324
  3. **Add indexes** for fields used in `db.query` WHERE clauses and JOINs to avoid full table scans
325
325
  4. **Add new fields to the bottom of the schema** - When adding new fields to an existing table, append them to the end of the schema block rather than inserting them in the middle. This preserves column ordering consistency and avoids unexpected side effects
326
+ 5. **`workspace push` is additive, not declarative** - A partial push (the default) adds and updates schema but makes no destructive changes — it won't drop a column you removed or relax an existing constraint, so local files and the live table can diverge. Use `xano workspace push --sync` for destructive schema changes.
326
327
 
327
328
  ---
328
329
 
@@ -1,4 +1,4 @@
1
1
  {
2
- "version": "2.4.0",
3
- "updated": "2026-06-10"
2
+ "version": "2.5.0",
3
+ "updated": "2026-07-02"
4
4
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xano/developer-mcp",
3
- "version": "2.2.2-beta.1",
3
+ "version": "2.2.2-beta.2",
4
4
  "description": "MCP server and library for Xano development - XanoScript validation, Meta API, Run API, and CLI documentation",
5
5
  "type": "module",
6
6
  "main": "dist/lib.js",