@xano/developer-mcp 2.2.5 → 2.2.6-beta.0

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.
@@ -1,7 +1,9 @@
1
1
  export const realtimeDoc = {
2
2
  topic: "realtime",
3
- title: "Realtime Channel Management",
4
- description: `Realtime channels enable WebSocket-based push notifications and live updates to connected clients.
3
+ title: "Legacy Realtime Channel Management",
4
+ description: `These endpoints describe legacy Realtime. For Realtime V2, use xano_xanoscript_docs({ topic: "realtime-v2" }) and the workspace XanoScript push/pull workflow.
5
+
6
+ Realtime channels enable WebSocket-based push notifications and live updates to connected clients.
5
7
 
6
8
  ## Key Concepts
7
9
  - Channels are WebSocket endpoints for real-time communication
@@ -243,7 +243,8 @@ Use `xano_xanoscript_docs({ tier: "survival" })` or `xano_xanoscript_docs({ tier
243
243
  | `file-uploads` | Uploading files to native Xano storage | `file?` input, create_attachment, signed URLs |
244
244
  | `tasks` | Scheduled and cron jobs | Cron Syntax, Input Handling |
245
245
  | `triggers` | Event-driven handlers (table, realtime, workspace, agent, MCP) | Predefined Inputs, Event Types |
246
- | `realtime` | Real-time channels and events for push updates | Channels, Events |
246
+ | `realtime` | Legacy V1 channels and events | Channels, Events |
247
+ | `realtime-v2` | V2 servers, channels, message handlers, and publishing | WebSocket Client, Authentication, Join Triggers |
247
248
 
248
249
  ### AI & Agents
249
250
 
@@ -282,4 +283,3 @@ Use `xano_xanoscript_docs({ tier: "survival" })` or `xano_xanoscript_docs({ tier
282
283
  | ------------- | ------------------------------------------------------------ | ------------ |
283
284
  | `performance` | Performance optimization best practices | Caching, Query Optimization |
284
285
  | `security` | Security best practices for authentication and authorization | Auth Patterns, Token Handling |
285
-
@@ -43,6 +43,8 @@ query "endpoint-path" verb=<METHOD> {
43
43
  }
44
44
  ```
45
45
 
46
+ To attach post middleware to this endpoint, add `middleware = { post: [{name: "docs_post"}] }` inside the `query` declaration, alongside `response`. Define the referenced middleware first. See `xano_xanoscript_docs({ topic: "middleware" })` for the fixed input contract and complete examples.
47
+
46
48
  ### Query Name (Required, Non-Empty)
47
49
 
48
50
  The query name is **required** and **must be a non-empty string**. Empty names (`query "" verb=...`) are invalid. The name defines the endpoint path after the API group canonical.
@@ -225,10 +225,35 @@
225
225
  },
226
226
  "realtime": {
227
227
  "file": "realtime.md",
228
- "description": "Real-time channels and events for push updates",
229
- "applyTo": ["realtime/channel/*.xs", "realtime/trigger/*.xs"],
228
+ "description": "Legacy Realtime V1 channels and events; use realtime-v2 for servers, channels, and message handlers",
229
+ "applyTo": [
230
+ "realtime/channel/*.xs",
231
+ "realtime/trigger/*.xs"
232
+ ],
230
233
  "priority": 3,
231
- "aliases": ["websocket", "channels", "pubsub"]
234
+ "aliases": [
235
+ "realtime-v1",
236
+ "legacy-realtime"
237
+ ]
238
+ },
239
+ "realtime-v2": {
240
+ "file": "realtime-v2.md",
241
+ "description": "Realtime V2 servers, typed channel paths, message handlers, native WebSocket clients, publishing, and join authorization",
242
+ "applyTo": [
243
+ "realtime_server/**/*.xs",
244
+ "channel/**/*.xs",
245
+ "message/**/*.xs",
246
+ "channel_trigger/**/*.xs",
247
+ "realtime_server_trigger/**/*.xs"
248
+ ],
249
+ "priority": 3,
250
+ "aliases": [
251
+ "websocket",
252
+ "channels",
253
+ "pubsub",
254
+ "realtime2",
255
+ "realtime_v2"
256
+ ]
232
257
  },
233
258
  "security": {
234
259
  "file": "security.md",
@@ -245,7 +270,7 @@
245
270
  },
246
271
  "middleware": {
247
272
  "file": "middleware.md",
248
- "description": "Request/response interceptors for functions, queries, tasks, and tools",
273
+ "description": "API post middleware attachment, fixed inputs, and merge/replace response handling",
249
274
  "applyTo": ["middleware/*.xs"],
250
275
  "priority": 3,
251
276
  "aliases": ["interceptors", "hooks"]
@@ -337,10 +362,17 @@
337
362
  "mcp_server_trigger": { "file": "triggers.md", "section": "mcp-server-trigger" },
338
363
  "addon": { "file": "addons.md" },
339
364
  "middleware": { "file": "middleware.md" },
340
- "realtime_channel": { "file": "realtime.md" }
365
+ "realtime_channel": { "file": "realtime.md" },
366
+ "realtime_server": { "file": "realtime-v2.md" },
367
+ "channel": { "file": "realtime-v2.md" },
368
+ "message": { "file": "realtime-v2.md" },
369
+ "channel_trigger": { "file": "realtime-v2.md" },
370
+ "realtime_server_trigger": { "file": "realtime-v2.md" }
341
371
  },
342
372
 
343
373
  "operations": {
374
+ "realtime.publish": { "file": "realtime-v2.md" },
375
+ "realtime.get_session": { "file": "realtime-v2.md" },
344
376
  "db.query": { "file": "database.md" },
345
377
  "db.get": { "file": "database.md" },
346
378
  "db.has": { "file": "database.md" },
@@ -4,314 +4,151 @@ 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:** Define a middleware, then attach it inside the API's `query` declaration with `middleware = {post: [{name: "docs_post"}]}`. Post middleware receives the response envelope in `$input.vars`; the successful endpoint result is `$input.vars.result`.
8
8
 
9
9
  ## Quick Reference
10
10
 
11
- ```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
19
- }
20
- ```
11
+ | Need | Syntax |
12
+ |------|--------|
13
+ | Attach to one API | `middleware = {post: [{name: "docs_post"}]}` alongside `response` |
14
+ | Middleware inputs | `json vars` and `enum type { values = ["pre", "post"] }` |
15
+ | Current phase | `$input.type` |
16
+ | Successful post result | `$input.vars.result` |
17
+ | Add response fields | `response_strategy = "merge"` |
18
+ | Replace response | `response_strategy = "replace"` |
19
+ | Surface middleware errors | `exception_policy = "rethrow"` |
21
20
 
22
- ### Required Blocks
23
- | Block | Purpose |
24
- |-------|---------|
25
- | `input` | Define parameters passed to middleware |
26
- | `stack` | Processing logic |
27
- | `response` | Output returned to caller |
21
+ Use an array of `{name: "..."}` objects, not an array of strings. Declare the referenced middleware before attaching it. The name must match exactly.
28
22
 
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 |
23
+ ## Attach Post Middleware to an API
35
24
 
36
- ---
25
+ Create each declaration in its own `.xs` file. This example needs no database table.
37
26
 
38
- ## Basic Structure
27
+ ### 1. Define the middleware
39
28
 
40
29
  ```xs
41
- middleware "log_request" {
42
- description = "Logs all incoming requests"
43
-
30
+ middleware docs_post {
31
+ exception_policy = "rethrow"
32
+ response_strategy = "merge"
44
33
  input {
45
- json request_data
46
- }
47
-
48
- stack {
49
- debug.log {
50
- value = {
51
- timestamp: now,
52
- data: $input.request_data
53
- }
34
+ json vars
35
+ enum type {
36
+ values = ["pre", "post"]
54
37
  }
55
38
  }
56
-
57
- response = null
58
- }
59
- ```
60
-
61
- ---
62
-
63
- ## Exception Policies
64
-
65
- Control how middleware handles errors:
66
-
67
- ### silent
68
- Errors are caught and ignored. Execution continues normally.
69
-
70
- ```xs
71
- middleware "optional_enrichment" {
72
- exception_policy = "silent"
73
-
74
- input {
75
- int user_id
76
- }
77
-
78
39
  stack {
79
- // If this fails, request continues without enrichment
80
- api.call "external_service" {
81
- url = "https://api.example.com/enrich/" ~ $input.user_id
82
- } as $enriched
40
+ var $observed { value = $input.vars }
83
41
  }
84
-
85
- response = $enriched
42
+ response = {middleware_phase: $input.type, observed: $observed}
86
43
  }
87
44
  ```
88
45
 
89
- ### rethrow (default)
90
- Errors are passed through to the caller. Standard error handling applies.
91
-
92
- ```xs
93
- middleware "validate_token" {
94
- exception_policy = "rethrow"
95
-
96
- input {
97
- text token
98
- }
46
+ `input`, `stack`, and `response` are required by the MCP validator. The server supplies the fixed `vars` and `type` inputs. Custom middleware inputs are not a way to pass parameters from an API.
99
47
 
100
- stack {
101
- precondition ($input.token|strlen > 0) {
102
- error_type = "accessdenied"
103
- error = "Token required"
104
- }
105
- }
106
-
107
- response = { valid: true }
108
- }
109
- ```
110
-
111
- ### critical
112
- Errors are treated as critical failures. Request is immediately terminated.
48
+ ### 2. Create an API group
113
49
 
114
50
  ```xs
115
- middleware "security_check" {
116
- exception_policy = "critical"
117
-
118
- input {
119
- text ip_address
120
- }
121
-
122
- stack {
123
- db.query "blocked_ips" {
124
- where = $db.blocked_ips.ip == $input.ip_address
125
- return = { type: "exists" }
126
- } as $is_blocked
127
-
128
- precondition (!$is_blocked) {
129
- error_type = "accessdenied"
130
- error = "Access denied"
131
- }
132
- }
133
-
134
- response = { allowed: true }
51
+ api_group docs_audit {
52
+ canonical = "docs-demo"
135
53
  }
136
54
  ```
137
55
 
138
- ---
139
-
140
- ## Response Strategies
141
-
142
- Control how middleware response combines with the original response:
56
+ Use a unique canonical for a new group. Preserve the existing canonical when editing a group.
143
57
 
144
- ### merge (default)
145
- Middleware response is merged with original response.
58
+ ### 3. Attach the middleware inside the query
146
59
 
147
60
  ```xs
148
- middleware "add_metadata" {
149
- response_strategy = "merge"
150
-
61
+ query check verb=GET {
62
+ api_group = "docs_audit"
151
63
  input {
152
64
  }
153
-
154
65
  stack {
155
- var $meta {
156
- value = {
157
- server_time: now,
158
- version: "1.0.0"
159
- }
160
- }
66
+ var $result { value = {ok: true} }
161
67
  }
162
-
163
- response = { _meta: $meta }
68
+ response = $result
69
+ middleware = {post: [{name: "docs_post"}]}
164
70
  }
165
- // Original: { data: [...] }
166
- // Result: { data: [...], _meta: { server_time: ..., version: "1.0.0" } }
167
71
  ```
168
72
 
169
- ### replace
170
- Middleware response completely replaces original response.
73
+ The middleware block is a sibling of `input`, `stack`, and `response`. Do not put it inside `stack`, and do not add `type = "post"` to the middleware declaration.
171
74
 
172
- ```xs
173
- middleware "transform_response" {
174
- response_strategy = "replace"
175
-
176
- input {
177
- json original_response
178
- }
75
+ Request `GET /api:docs-demo/check` on the instance. The live response is:
179
76
 
180
- stack {
181
- var $transformed {
182
- value = {
183
- success: true,
184
- payload: $input.original_response
185
- }
186
- }
187
- }
188
-
189
- response = $transformed
77
+ ```json
78
+ {
79
+ "ok": true,
80
+ "middleware_phase": "post",
81
+ "observed": {"status": "ok", "result": {"ok": true}}
190
82
  }
191
83
  ```
192
84
 
193
- ---
85
+ The `ok` field comes from the API. The other fields prove that the middleware ran in the post phase and saw the endpoint's response. Returning an object with `merge` adds its fields to the successful response object. This example deliberately echoes the envelope for inspection; a production middleware should return only the intended public fields.
194
86
 
195
- ## Common Patterns
87
+ ## Response Envelope and Replacement
196
88
 
197
- ### Request Logging
89
+ For the successful API above, `$input.vars` is `{status: "ok", result: {ok: true}}`. To wrap the endpoint's payload, use `$input.vars.result`, not the whole envelope. Do not assume this successful-response shape describes an error path or the pre phase.
198
90
 
199
91
  ```xs
200
- middleware "audit_log" {
201
- description = "Logs all API requests for audit trail"
202
- exception_policy = "silent"
203
-
204
- input {
205
- text endpoint
206
- text method
207
- json request_body?
208
- int user_id?
209
- }
210
-
211
- 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
220
- }
221
- }
222
- }
223
-
224
- response = null
225
- }
226
- ```
227
-
228
- ### Rate Limiting
229
-
230
- ```xs
231
- middleware "rate_limit" {
232
- description = "Enforces rate limits per user"
92
+ middleware docs_wrap {
233
93
  exception_policy = "rethrow"
234
-
94
+ response_strategy = "replace"
235
95
  input {
236
- int user_id
237
- int max_requests?=100
238
- int window_seconds?=60
96
+ json vars
97
+ enum type {
98
+ values = ["pre", "post"]
99
+ }
239
100
  }
240
-
241
101
  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"
247
- }
102
+ var $payload { value = $input.vars.result }
248
103
  }
249
-
250
- response = null
104
+ response = {success: true, payload: $payload}
251
105
  }
252
106
  ```
253
107
 
254
- ### Response Caching
108
+ Attach `docs_wrap` as the query's post middleware:
255
109
 
256
110
  ```xs
257
- middleware "cache_response" {
258
- description = "Caches responses in Redis"
259
- exception_policy = "silent"
260
-
111
+ query wrap verb=GET {
112
+ api_group = "docs_audit"
261
113
  input {
262
- text cache_key
263
- int ttl_seconds?=300
264
- json response_data
265
114
  }
266
-
267
115
  stack {
268
- redis.set {
269
- key = $input.cache_key
270
- value = $input.response_data|json_encode
271
- expire = $input.ttl_seconds
272
- }
116
+ var $result { value = {ok: true} }
273
117
  }
274
-
275
- response = null
118
+ response = $result
119
+ middleware = {post: [{name: "docs_wrap"}]}
276
120
  }
277
121
  ```
278
122
 
279
- ---
123
+ Request `GET /api:docs-demo/wrap`. The expected response is:
280
124
 
281
- ## Applying Middleware
125
+ ```json
126
+ {"success": true, "payload": {"ok": true}}
127
+ ```
282
128
 
283
- Middleware is configured at the branch level. See `xano_xanoscript_docs({ topic: "branch" })` for configuration details.
129
+ With `replace`, the middleware's response becomes the endpoint response. With `merge`, the original successful response fields remain alongside middleware fields.
284
130
 
285
- ```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
- }
296
- }
297
- }
298
- ```
131
+ ## Validate and Verify
299
132
 
300
- ---
133
+ 1. Validate every definition with `xano_validate_xanoscript`.
134
+ 2. Preview the scoped workspace push with `--dry-run`, then push the middleware, group, and API together.
135
+ 3. Pull the workspace again and inspect the query's `middleware` attachment.
136
+ 4. Call the real endpoint and assert the final HTTP response. Parsing or a successful push alone does not prove that middleware executed.
301
137
 
302
- ## Best Practices
138
+ The repository's `examples/realtime-v2/verify.mjs` exercises both merge and replace against a live workspace. Its target is configured in `examples/realtime-v2/frontend/config.json`.
303
139
 
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
140
+ ## Common Mistakes
307
141
 
308
- ---
142
+ - **Defining without attaching:** a middleware declaration alone does not attach it to an API. Put the `middleware` block inside the query.
143
+ - **Using string entries:** use `post: [{name: "docs_post"}]`, not `post: ["docs_post"]`.
144
+ - **Inventing middleware inputs:** read the server-provided `$input.vars` and `$input.type`.
145
+ - **Wrapping the wrong value:** for a successful post response, wrap `$input.vars.result`; `$input.vars` also includes execution status.
146
+ - **Trusting validation alone:** check the pulled attachment and execute the endpoint after pushing.
309
147
 
310
148
  ## Related Topics
311
149
 
312
150
  | Topic | Description |
313
151
  |-------|-------------|
314
- | `branch` | Branch-level middleware configuration |
315
- | `security` | Authentication and authorization patterns |
316
- | `apis` | API endpoint request/response lifecycle |
317
- | `performance` | Performance optimization strategies |
152
+ | `apis` | API declarations and responses |
153
+ | `realtime-v2` | Message handlers and live server publishing |
154
+ | `security` | Authentication and authorization |
@@ -0,0 +1,395 @@
1
+ ---
2
+ applyTo: "realtime_server/**/*.xs, channel/**/*.xs, message/**/*.xs, channel_trigger/**/*.xs, realtime_server_trigger/**/*.xs"
3
+ ---
4
+
5
+ # Realtime V2
6
+
7
+ > **TL;DR:** V2 uses `realtime_server` → `channel` → `message`. Clients join resolved paths over `/ws/<server-canonical>` and invoke a message with `action: "broadcast"`. Xano stacks publish with `realtime.publish`. Legacy `realtime_channel`, `realtime_trigger`, `/rt/`, and `api.realtime_event` target a different system.
8
+
9
+ ## Quick Reference
10
+
11
+ | Need | V2 syntax or behavior |
12
+ |------|-----------------------|
13
+ | Create a server | `realtime_server docs_realtime { ... }` |
14
+ | Define a channel template | `channel "rooms/{room_id}"` with `realtime_server = "docs_realtime"` and `input { int room_id }` |
15
+ | Define a client-invoked handler | `message send` with `realtime_server`, `channel`, `input`, `stack`, `response` |
16
+ | Receive everyone’s messages | `deliver_to = "channel"` |
17
+ | Reply only to caller | `deliver_to = "sender"` |
18
+ | Exclude caller | `deliver_to = "others"` |
19
+ | Require a user JWT | `auth = "user"` on the message; `user` must be an auth-enabled table |
20
+ | Inspect socket context | `realtime.get_session as $session` |
21
+ | Publish from an API/function/task | `realtime.publish { realtime_server = "docs_realtime" ... }`; no `as` binding |
22
+ | Veto a channel join | `channel_trigger` with `actions = {join: true}` and `response = {allowed: <boolean>, reason: <text>}` |
23
+
24
+ **Prerequisite:** the instance must have the V2 WebSocket service and `/ws/` route enabled. A successful XanoScript import or publish API response does not prove socket delivery. If a WebSocket upgrade returns HTML instead of HTTP 101, check instance deployment before changing channel code.
25
+
26
+ ## Server, Channel, and Message
27
+
28
+ Create one declaration per `.xs` file. The examples below are also in the source repository’s `examples/realtime-v2/` directory. They are not included in the npm package; copy the definitions below into your own files when using the installed MCP.
29
+
30
+ ### Server
31
+
32
+ ```xs
33
+ realtime_server docs_realtime {
34
+ canonical = "67Dx5RNL"
35
+ active = true
36
+ }
37
+ ```
38
+
39
+ Use a unique `canonical` when creating your own server, or omit it once and pull the generated value. **Preserve the pulled canonical on subsequent pushes.** Omitting it on an update can change the connection address and cause existing clients to receive `Unknown connection hash`. The canonical shown here is illustrative; use your own server’s value.
40
+
41
+ Server references inside XanoScript use the **name**, `docs_realtime`. WebSocket URLs use the **canonical**, not the name.
42
+
43
+ ### Channel
44
+
45
+ ```xs
46
+ channel "rooms/{room_id}" {
47
+ realtime_server = "docs_realtime"
48
+ access = {anonymous: true, presence: false}
49
+ publish = {who: "anyone", direct: false}
50
+ delivery = {guarantee: "at_most_once", per_recipient: false}
51
+ input {
52
+ int room_id
53
+ }
54
+ }
55
+ ```
56
+
57
+ The declaration names the template `rooms/{room_id}`; a client joins a resolved path such as `rooms/42`. Declare each path parameter in the channel's input block. The example permits anonymous clients and client publishing for a test room. These are independent controls:
58
+
59
+ | Clause | Meaning |
60
+ |--------|---------|
61
+ | `access.anonymous` | Whether unauthenticated clients may join |
62
+ | `access.presence` | Whether clients receive presence information |
63
+ | `publish.who` | `nobody`, `anyone`, or `authenticated` may publish |
64
+ | `publish.direct` | Whether clients may address other clients directly |
65
+ | `delivery.guarantee` | The example uses `at_most_once`; delivery may be lost |
66
+
67
+ A room path separates subscriptions; knowing a path is not authorization. Use access policy and a join trigger for restricted rooms.
68
+
69
+ ### Message handler
70
+
71
+ ```xs
72
+ message send {
73
+ realtime_server = "docs_realtime"
74
+ channel = "rooms/{room_id}"
75
+ deliver_to = "channel"
76
+ input {
77
+ text author
78
+ text body
79
+ }
80
+ stack {
81
+ var $sent_at { value = now }
82
+ }
83
+ response = {author: $input.author, body: $input.body, sent_at: $sent_at}
84
+ }
85
+ ```
86
+
87
+ A client invokes `send` with `{author: "Alice", body: "Hello"}`. The server executes the stack and delivers the **response**, including the computed `sent_at`, to subscribed clients. `author` is user-supplied display text in this anonymous demo, not an authenticated identity.
88
+
89
+ The required parent references are the server name and channel **template**. `input`, `stack`, and `response` are required. Message payloads are validated against the input schema; for example, `int count` rejects `"not-an-integer"` with an error frame to the sender.
90
+
91
+ ### Sender-only response and session context
92
+
93
+ ```xs
94
+ message echo {
95
+ realtime_server = "docs_realtime"
96
+ channel = "rooms/{room_id}"
97
+ deliver_to = "sender"
98
+ input {
99
+ text body
100
+ }
101
+ stack {
102
+ realtime.get_session as $session
103
+ }
104
+ response = {body: $input.body, session: $session}
105
+ }
106
+ ```
107
+
108
+ `realtime.get_session` exposes `authenticated`, `client_id`, `dbo_id`, `socket_id`, `channel`, `params`, `extras`, and `opened_at`. For an anonymous client in `rooms/42`, the observed session has `authenticated: false`, `client_id: ""`, `dbo_id: 0`, and `channel: "rooms/42"`.
109
+
110
+ **Path values in the join acknowledgement and `$session.params` were strings** (`{room_id: "42"}`), even though the channel declared `int room_id`. Do not assume these transport/session objects contain already-coerced numbers. Validate or convert them before numeric comparisons or database use.
111
+
112
+ `deliver_to = "others"` delivers to the other subscribers and excludes the caller. The parser also accepts `explicit`; this guide does not prescribe a recipient-selection API for that mode.
113
+
114
+ ## Publish from an API
115
+
116
+ Create the `docs_audit` API group shown in the middleware topic, then add:
117
+
118
+ ```xs
119
+ query publish verb=POST {
120
+ api_group = "docs_audit"
121
+ input {
122
+ int room_id
123
+ text body
124
+ }
125
+ stack {
126
+ realtime.publish {
127
+ realtime_server = "docs_realtime"
128
+ channel = "rooms/" ~ $input.room_id
129
+ message = "announcement"
130
+ data = {body: $input.body}
131
+ }
132
+ }
133
+ response = {ok: true}
134
+ }
135
+ ```
136
+
137
+ POST `{ "room_id": 42, "body": "Hello from Xano" }` to `/api:<api-group-canonical>/publish`. Both connected clients in `rooms/42` should receive a frame with `action: "message"`, `type: "announcement"`, and the supplied body in `payload`.
138
+
139
+ | Attribute | Required | Meaning |
140
+ |-----------|----------|---------|
141
+ | `realtime_server` | Yes | Server name |
142
+ | `channel` | Yes | Resolved channel path |
143
+ | `data` | Yes | Payload to deliver |
144
+ | `message` | No | Delivered frame's `type`; does not invoke a handler |
145
+ | `auth_table`, `auth_id` | No | Identity attribution only; does not authenticate or authorize |
146
+
147
+ `realtime.publish` has no result binding and does not invoke the message handler named by `message`; the `announcement` type above has no handler. Wait for actual incoming frames to verify delivery. A `200 {ok: true}` response alone only confirms the API execution.
148
+
149
+ For an application endpoint, authorize the caller and their access to the target resource before publishing. This anonymous endpoint exists to exercise the demo.
150
+
151
+ ## Publish in the visual editor
152
+
153
+ In a function stack, add **Realtime Publish** from **APIs & Lambdas**, or search for it by name. It is the visual editor equivalent of `realtime.publish`.
154
+
155
+ | Panel field | XanoScript | What to enter |
156
+ | --- | --- | --- |
157
+ | **Realtime Server** | `realtime_server` | Server name, such as `docs_realtime`; not its WebSocket canonical |
158
+ | **Channel** | `channel` | Resolved path, such as `rooms/42` |
159
+ | **Message** (optional) | `message` | Outgoing frame's `type`, such as `announcement` |
160
+ | **Data** | `data` | Payload delivered to subscribers |
161
+ | **Authentication → Database** (optional) | `auth_table` | Table used for identity attribution |
162
+ | **Authentication → Row ID** (optional) | `auth_id` | Attributed record ID; shown after selecting a database |
163
+
164
+ Realtime Server and Channel accept constants, variables, and expressions. Autocomplete offers workspace server names and channel templates as suggestions; it does not restrict values to that list. Resolve a template such as `rooms/{room_id}` to `rooms/42` before publishing. A channel path belongs to a particular server, so supply both fields. If suggestions fail to load, you can still enter the values directly.
165
+
166
+ **Message does not invoke a message handler.** Publishing with `message = "send"` delivers your Data as-is with `type: "send"`; it does not run the `send` handler's input validation, function stack, or per-message authentication. Authorize the calling API or stack before publishing. The optional Authentication fields attach identity metadata only; they do not validate credentials or grant access.
167
+
168
+ ### Availability and version choice
169
+
170
+ **Realtime Publish** requires Realtime V2 support on the instance. In the picker category and search results, it is greyed out with an explanation when V2 is unavailable. An empty autocomplete list is a separate issue and does not mean V2 is disabled.
171
+
172
+ **Realtime Event (v1)** remains available for legacy connections. Its XanoScript statement is `api.realtime_event`. It cannot reach V2 subscribers and can complete without an error while delivering nothing to them. Do not substitute it when Realtime Publish is unavailable; check V2 availability on the instance instead.
173
+
174
+ For raw process-stack integrations, V2 is `mvp:realtime_publish` (`EProcessFunctionType.RealtimePublish`); V1 is `mvp:realtime_event`. These internal identifiers are not XanoScript syntax. Existing statements remain editable; adding a statement is not evidence that socket delivery is available.
175
+
176
+ ## Native WebSocket Client
177
+
178
+ The V2 URL is `wss://<instance-host>/ws/<server-canonical>`. Use the V2 server's canonical, not the workspace's legacy realtime canonical. A user JWT is carried as the WebSocket subprotocol: `new WebSocket(url, [userJwt])`. Do not put a Metadata API access token in frontend code.
179
+
180
+ The following module is shared verbatim with the live demo and verification script. It waits for the join acknowledgement, retries the specific initial readiness error, sends keepalive pings, and closes timers with the socket.
181
+
182
+ ```javascript
183
+ // Native Realtime V2 protocol. Shared by the demo and the live verification.
184
+ export function connectClient({url, channel, token, onFrame = () => {}, onState = () => {}}) {
185
+ const socket = token ? new WebSocket(url, [token]) : new WebSocket(url);
186
+ let joined = false, attempts = 0, retry, heartbeat, deadline;
187
+ let resolveReady, rejectReady;
188
+ const ready = new Promise((resolve, reject) => { resolveReady = resolve; rejectReady = reject; });
189
+ const send = frame => {
190
+ if (socket.readyState !== WebSocket.OPEN) throw new Error('Socket is not open');
191
+ socket.send(JSON.stringify(frame));
192
+ };
193
+ const clear = () => { clearTimeout(retry); clearTimeout(deadline); clearInterval(heartbeat); };
194
+ const join = () => {
195
+ if (socket.readyState !== WebSocket.OPEN || joined) return;
196
+ attempts++;
197
+ send({action: 'join', channel});
198
+ };
199
+ deadline = setTimeout(() => {
200
+ rejectReady(new Error('Timed out joining the V2 channel'));
201
+ clear(); socket.close();
202
+ }, 10000);
203
+ socket.addEventListener('open', () => { onState('Joining'); join(); });
204
+ socket.addEventListener('message', event => {
205
+ let frame;
206
+ try { frame = JSON.parse(event.data); } catch { return; }
207
+ onFrame(frame);
208
+ if (!joined && frame.action === 'error') {
209
+ if (frame.payload?.message === 'Connection is not ready' && attempts < 10) {
210
+ clearTimeout(retry); retry = setTimeout(join, 250);
211
+ } else {
212
+ rejectReady(new Error(frame.payload?.message || 'Join refused'));
213
+ clear(); socket.close();
214
+ }
215
+ }
216
+ if (frame.action === 'join' && frame.channel === channel && frame.payload?.joined) {
217
+ joined = true; clearTimeout(retry); clearTimeout(deadline);
218
+ heartbeat = setInterval(() => { if (socket.readyState === WebSocket.OPEN) send({action:'ping'}); }, 20000);
219
+ onState('Joined'); resolveReady(frame);
220
+ }
221
+ });
222
+ socket.addEventListener('error', () => {
223
+ rejectReady(new Error('WebSocket connection failed. Check the V2 /ws/ route and server canonical.'));
224
+ });
225
+ socket.addEventListener('close', event => {
226
+ clear(); joined = false; onState('Offline');
227
+ rejectReady(new Error(`Connection closed (${event.code})`));
228
+ });
229
+ return {
230
+ ready, socket,
231
+ get joined() { return joined; },
232
+ broadcast(type, payload) {
233
+ if (!joined) throw new Error('Join the channel before publishing');
234
+ send({action: 'broadcast', channel, type, payload});
235
+ },
236
+ send,
237
+ close() { clear(); socket.close(); }
238
+ };
239
+ }
240
+ ```
241
+
242
+ Save that module as `socket.js`, then use it as follows. The address shape is `wss://{instance-host}/ws/{server-canonical}`; the filled-in example below is illustrative. Replace it with your own server address:
243
+
244
+ ```javascript
245
+ import {connectClient} from "./socket.js";
246
+
247
+ const client = connectClient({
248
+ url: "wss://x8ki-letl-twmt.n7.xano.io/ws/67Dx5RNL",
249
+ channel: "rooms/42",
250
+ onFrame(frame) {
251
+ if (frame.action === "message") {
252
+ console.log(frame.type, frame.payload);
253
+ }
254
+ }
255
+ });
256
+
257
+ try {
258
+ await client.ready;
259
+ client.broadcast("send", {author: "Alice", body: "Hello"});
260
+ } catch (error) {
261
+ client.close();
262
+ console.error(error);
263
+ }
264
+ ```
265
+
266
+ Call `client.close()` when the page or component stops using the connection. The demo does this on `pagehide`. A closed connection must join again after reconnecting.
267
+
268
+ ### Wire frames
269
+
270
+ | Direction | Example |
271
+ |-----------|---------|
272
+ | Client → server, join | `{ "action": "join", "channel": "rooms/42" }` |
273
+ | Server → client, joined | `{ "action": "join", "channel": "rooms/42", "payload": { "joined": true, "params": { "room_id": "42" } } }` |
274
+ | Client → server, invoke | `{ "action": "broadcast", "channel": "rooms/42", "type": "send", "payload": { "author": "Alice", "body": "Hello" } }` |
275
+ | Server → client, delivery | `{ "action": "message", "channel": "rooms/42", "type": "send", "payload": { ... } }` |
276
+ | Server → client, error | `{ "action": "error", "payload": { "message": "..." } }` |
277
+
278
+ A `broadcast` receipt is not the delivered message. Render incoming `message` frames, and surface `error` frames separately. The demo never inserts optimistic or simulated deliveries.
279
+
280
+ ## Authentication and Join Authorization
281
+
282
+ A channel can allow anonymous joins while a particular message requires authentication:
283
+
284
+ ```xs
285
+ message protected_echo {
286
+ realtime_server = "docs_realtime"
287
+ channel = "rooms/{room_id}"
288
+ auth = "user"
289
+ deliver_to = "sender"
290
+ input {
291
+ text body
292
+ }
293
+ stack {
294
+ realtime.get_session as $session
295
+ }
296
+ response = {body: $input.body, authenticated: $session.authenticated}
297
+ }
298
+ ```
299
+
300
+ This assumes an existing auth-enabled `user` table. An anonymous invocation is rejected; a valid user JWT supplied as the socket subprotocol can invoke the handler. The JWT is an application user token, distinct from the CLI's administrative token.
301
+
302
+ For a channel-wide gate, create the channel:
303
+
304
+ ```xs
305
+ channel members {
306
+ realtime_server = "docs_realtime"
307
+ access = {anonymous: true, presence: false}
308
+ publish = {who: "authenticated", direct: false}
309
+ input {
310
+ }
311
+ }
312
+ ```
313
+
314
+ Then attach a join trigger by its parent references:
315
+
316
+ ```xs
317
+ channel_trigger member_gate {
318
+ realtime_server = "docs_realtime"
319
+ channel = "members"
320
+
321
+ input {
322
+ enum action {
323
+ values = ["join", "leave", "deliver"]
324
+ }
325
+
326
+ text channel
327
+ json payload
328
+ object client {
329
+ schema {
330
+ json extras
331
+ object permissions {
332
+ schema {
333
+ int dbo_id
334
+ text row_id
335
+ }
336
+ }
337
+ }
338
+ }
339
+ }
340
+
341
+ stack {
342
+ realtime.get_session as $session
343
+ }
344
+
345
+ response = {
346
+ allowed: $session.authenticated
347
+ reason : "Sign in to join members"
348
+ }
349
+
350
+ actions = {join: true}
351
+ }
352
+ ```
353
+
354
+ The trigger input schema above is the platform's pulled schema. The server normalizes these system inputs; do not invent application input parameters on the trigger. This gate explicitly admits authenticated sessions and rejects anonymous sessions with a reason. For membership or tenant authorization, replace the simple authentication decision with checks against your application data.
355
+
356
+ V2 lifecycle scopes are `realtime_server_trigger` for `connect`/`disconnect`, and `channel_trigger` for `join`/`leave`/`deliver`. The executable example here covers `join`. Legacy `realtime_trigger` belongs to V1.
357
+
358
+ ## CLI Workflow and Verification
359
+
360
+ Authenticate with your Xano account at `https://app.xano.com` and select your instance, workspace, and branch:
361
+
362
+ ```bash
363
+ xano auth
364
+ ```
365
+
366
+ Use your selected profile, workspace, and branch explicitly. Replace the uppercase placeholders below with your selections. Save the declarations under `examples/realtime-v2/` in your project, or change `--directory` to the directory you used:
367
+
368
+ ```bash
369
+ xano workspace push --profile YOUR_PROFILE --workspace YOUR_WORKSPACE --branch YOUR_BRANCH --directory examples/realtime-v2 --dry-run
370
+ xano workspace push --profile YOUR_PROFILE --workspace YOUR_WORKSPACE --branch YOUR_BRANCH --directory examples/realtime-v2
371
+ xano workspace pull --profile YOUR_PROFILE --workspace YOUR_WORKSPACE --branch YOUR_BRANCH --directory pulled-workspace
372
+ ```
373
+
374
+ Validate with `xano_validate_xanoscript` before pushing. Pull back and verify server canonicals, channel settings, message parent references, and trigger inputs. Use a current CLI release with Realtime V2 support. V2 objects pull under `realtime_server/`, `channel/`, `message/`, and `channel_trigger/`. Keep explicit parent clauses: folder names do not replace them.
375
+
376
+ If working from the source repository, run `node examples/realtime-v2/verify.mjs` with the frontend config pointed at your deployed examples. Set `XANO_TEST_USER_TOKEN` to an application user JWT to include the authenticated positive test. The script reports that test as skipped if the token is absent.
377
+
378
+ ## Common Mistakes
379
+
380
+ - **Mixing V1 and V2:** `api.realtime_event` and `/rt/` do not target these V2 servers.
381
+ - **Using a template in a publish call:** send to `rooms/42`, not `rooms/{room_id}`.
382
+ - **Using the server name in a socket URL:** use its preserved canonical.
383
+ - **Sending before joining:** wait for a successful join acknowledgement. Socket `open` alone is insufficient.
384
+ - **Confusing acknowledgements with delivery:** assert `action: "message"` on each intended recipient.
385
+ - **Assuming session path values are numeric:** the observed `$session.params.room_id` is text.
386
+ - **Treating a successful import as a realtime test:** connect two clients and verify actual delivered frames.
387
+
388
+ ## Related Topics
389
+
390
+ | Topic | Description |
391
+ |-------|-------------|
392
+ | `realtime` | Legacy V1 channels and events |
393
+ | `middleware` | API post middleware and response envelopes |
394
+ | `apis` | Endpoint definitions |
395
+ | `security` | Application authentication and authorization |
@@ -2,12 +2,16 @@
2
2
  applyTo: "realtime/channel/*.xs, realtime/trigger/*.xs, function/**/*.xs, api/**/*.xs"
3
3
  ---
4
4
 
5
- # Realtime
5
+ # Realtime (Legacy V1)
6
+
7
+ For **Realtime V2** servers, typed channels, message handlers, and `realtime.publish`, use `xano_xanoscript_docs({ topic: "realtime-v2" })`. This topic describes the separate legacy system. The visual editor labels its publishing statement **Realtime Event (v1)** (`api.realtime_event`). For V2, choose **Realtime Publish** (`realtime.publish`) and provide both a server name and resolved channel path. Realtime Event can succeed without delivering anything to V2 subscribers.
6
8
 
7
9
  Push real-time updates to connected clients using channels and events.
8
10
 
9
11
  ## Quick Reference
10
12
 
13
+ **Legacy V1 only.** For V2, request the `realtime-v2` topic.
14
+
11
15
  | Operation | Purpose |
12
16
  |-----------|---------|
13
17
  | `api.realtime_event` | Send event to channel |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xano/developer-mcp",
3
- "version": "2.2.5",
3
+ "version": "2.2.6-beta.0",
4
4
  "description": "MCP server and library for Xano development - XanoScript validation, Meta API, Run API, and CLI documentation",
5
5
  "mcpName": "io.github.xano-inc/xano-developer-mcp",
6
6
  "type": "module",