@rsc-kit/mcp 0.27.1 → 0.28.1

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.
@@ -68,466 +68,10 @@ slots the calling page does have.
68
68
 
69
69
  ## Refreshing on a change from outside
70
70
 
71
- An action can say what it changed because it is the thing changing it. A
72
- webhook, a job finishing in a worker, another visitor's action - none of
73
- those is in the tab that is showing the data. For those a section says what
74
- it depends on, by name:
75
-
76
- ```tsx title="src/app/t/[team]/repos.section.tsx"
77
- export default section('repos', Repos, {
78
- refreshOn: ({ params }) => [`team:${params.team}:repos`],
79
- })
80
- ```
81
-
82
- and whatever changes the data says so, from wherever it is:
83
-
84
- ```ts title="src/app/api/github/webhook/route.ts"
85
- import { changed } from '@rsc-kit/core/changed'
86
-
87
- export async function POST(request: Request) {
88
- const { team, repos } = await request.json()
89
- await saveRepos(team, repos)
90
- await changed(`team:${team}:repos`)
91
- return new Response(null, { status: 204 })
92
- }
93
- ```
94
-
95
- Every open tab showing the section refreshes it - the same refresh as above,
96
- with nothing polling and no client code. `refreshOn` is a list of names, or a
97
- function of the section's props - the page's `params` and `searchParams` -
98
- that makes them. A page can declare its own with `export const refreshOn`,
99
- and a change refreshes the page as `refresh('page')` does.
100
-
101
- The function runs per request, so it can read the request - a name for the
102
- person signed in is the usual one on a dashboard:
103
-
104
- ```tsx title="src/app/dashboard/page.tsx"
105
- import { cookies } from '@rsc-kit/core/request'
106
-
107
- export const refreshOn = async () => [`inbox:${(await cookies()).get('agent')?.value}`]
108
- ```
109
-
110
- That is the whole feature for an app that is only JavaScript. With a Go or
111
- Laravel backend the backend says it instead -
112
- [`reg.Changed(ctx, …)`](/hosts/go#saying-data-changed) or
113
- [`Rsc::changed(…)`](/hosts/laravel#saying-data-changed) - and the page is the same.
114
-
115
- ### How a tab finds out
116
-
117
- Each name has a version, a number that moves when something says the name
118
- changed. Nothing else travels - not what changed, not the data.
119
-
120
- 1. The page renders, reads the version of each name it shows, and hands them
121
- to the tab, signed.
122
- 2. The tab opens one stream, `/_rsc/changes`, for every name on the page. Only
123
- a page with `refreshOn` opens one, and only while the tab is visible.
124
- 3. The server asks where the versions live - "which of these differ from what
125
- I hold?" - once for every open tab it is serving, and again on an interval.
126
- 4. When a version has moved, the stream says so in one line, and the tab asks
127
- for exactly the sections showing that name, the way `refresh('repos')` does.
128
-
129
- A name belongs to the data, not to a section or a page. Any number of
130
- sections, on any number of pages, can refresh on the same name: one
131
- `changed('team:1:repos')` moves its version once, and every open tab showing
132
- any of them refreshes the ones it has. Section *names* are separate - two
133
- pages may both have a section called `stats`; each is resolved through its own
134
- page, and a shared render is never handed from one page to the other.
135
-
136
- The data is never pushed: the section is rendered fresh, through its own
137
- queries and its own guards, as any refresh is. That is also why this runs
138
- on a Worker - the stream holds no state, and a version is a read.
139
-
140
- ### Where the versions live
141
-
142
- **One server, no backend:** in that server's memory. Nothing to set up - but
143
- in production rsc-kit says so in its log, once, because the same default
144
- fails silently the moment there are two instances. If the deploy really is
145
- one instance, say so and the warning goes:
146
-
147
- ```ts title="src/instrumentation.ts"
148
- import { installVersionSource, memoryVersions } from '@rsc-kit/core/changed'
149
-
150
- export function register() {
151
- installVersionSource(memoryVersions()) // one instance, on purpose
152
- }
153
- ```
154
-
155
- **More than one instance, or a worker process:** this is the case to
156
- plan for. In-memory versions fail silently the moment a load balancer adds a
157
- second instance - a change made on one never reaches the tabs held by the
158
- other - and a job finishes in a process that serves no pages at all. Keep
159
- the versions somewhere they all share - any database you already have, through
160
- the client you already use. rsc-kit ships no driver; you hand it yours:
161
-
162
- | Your database | The store | Another instance's change arrives |
163
- | --- | --- | --- |
164
- | Postgres, with postgres.js or `Bun.sql` | `postgresVersions(sql)` | at once with postgres.js; within a second with `Bun.sql` |
165
- | Postgres, with another client | `sqlVersions({ query, placeholder: (n) => '$' + n })` | within a second |
166
- | MySQL, MariaDB | `sqlVersions({ query })` | within a second |
167
- | SQLite, libSQL, Turso, D1 | `sqlVersions({ query })` | within a second |
168
- | Redis | `createVersions({ read, bump, listen, notify })` | at once, through pub/sub |
169
- | An ORM: Drizzle, Prisma, Kysely, Knex | `createVersions` over its query builder, or `sqlVersions` over its raw query | as its database |
170
-
171
- `sqlVersions` takes your driver as one function of SQL text and parameters,
172
- and writes plain SQL every dialect has - a select, an update, an insert:
173
-
174
- ```ts title="src/versions.ts"
175
- import { sqlVersions } from '@rsc-kit/core/changed'
176
-
177
- // MySQL, mysql2
178
- export const versions = sqlVersions({ query: async (text, params) => (await pool.query(text, params))[0] })
179
-
180
- // SQLite, bun:sqlite or better-sqlite3
181
- export const versions = sqlVersions({ query: async (text, params) => db.query(text).all(...params) })
182
-
183
- // libSQL / Turso
184
- export const versions = sqlVersions({ query: async (sql, args) => (await client.execute({ sql, args })).rows })
185
- ```
186
-
187
- and with postgres.js it is one line:
188
-
189
- ```ts title="src/versions.ts"
190
- import postgres from 'postgres'
191
- import { postgresVersions } from '@rsc-kit/core/changed'
192
-
193
- export const sql = postgres(process.env.DATABASE_URL!)
194
- export const versions = postgresVersions(sql)
195
- ```
196
-
197
- A SQLite file is shared by the processes on one machine - a web server and a
198
- worker on the same box. Instances on several machines need a database they
199
- all reach over the network. The table every one of these reads is described
200
- [below](#the-table).
201
-
202
- postgres.js can LISTEN, so a change on one instance reaches the tabs on every
203
- other at once. `Bun.sql` works too, without LISTEN: a waiting server reads the
204
- table once a second, so a change from another instance takes up to a second -
205
- unless a second, listening connection wakes it (below).
206
-
207
- **Any database, any ORM, or no SQL at all.** rsc-kit needs three things from
208
- your storage - read some versions, move some versions, and, if it can,
209
- say the moment one moved - and does the comparing, waiting and waking itself.
210
- `createVersions` takes exactly those:
211
-
212
- With Drizzle, use its query builder rather than raw SQL - the table is one
213
- more table in your schema:
214
-
215
- ```ts title="src/db/schema.ts"
216
- import { bigint, pgTable, text } from 'drizzle-orm/pg-core'
217
-
218
- export const rscVersions = pgTable('rsc_versions', {
219
- name: text('name').primaryKey(),
220
- version: bigint('version', { mode: 'number' }).notNull(),
221
- })
222
- ```
223
-
224
- ```ts title="src/versions.ts"
225
- import { inArray, sql } from 'drizzle-orm'
226
- import { createVersions } from '@rsc-kit/core/changed'
227
- import { db } from './db'
228
- import { rscVersions } from './db/schema'
229
-
230
- export const versions = createVersions({
231
- read: async (names) =>
232
- Object.fromEntries(
233
- (await db.select().from(rscVersions).where(inArray(rscVersions.name, names)))
234
- .map((row) => [row.name, Number(row.version)]),
235
- ),
236
- bump: async (names) => {
237
- await db.insert(rscVersions)
238
- .values(names.map((name) => ({ name, version: 1 })))
239
- .onConflictDoUpdate({ target: rscVersions.name, set: { version: sql`${rscVersions.version} + 1` } })
240
- },
241
- })
242
- ```
243
-
244
- ```ts title="Prisma"
245
- import { sqlVersions } from '@rsc-kit/core/changed'
246
-
247
- // Raw SQL through Prisma; the table is a model in its schema - see "The table" below.
248
- export const versions = sqlVersions({
249
- query: (text, params) => prisma.$queryRawUnsafe(text, ...params),
250
- placeholder: (n) => '$' + n, // Postgres; leave out for MySQL and SQLite
251
- })
252
- ```
253
-
254
- ```ts title="Redis"
255
- import { createVersions } from '@rsc-kit/core/changed'
256
-
257
- const key = (name: string) => 'rsc:' + name
258
-
259
- export const versions = createVersions({
260
- read: async (names) => {
261
- const values = await redis.mget(names.map(key))
262
- return Object.fromEntries(names.map((name, i) => [name, Number(values[i] ?? 0)]))
263
- },
264
- bump: async (names) => { await Promise.all(names.map((name) => redis.incr(key(name)))) },
265
- // Instant across instances: a subscriber connection hears every bump.
266
- listen: (wake) => subscriber.subscribe('rsc:versions', wake),
267
- notify: () => redis.publish('rsc:versions', ''),
268
- })
269
- ```
270
-
271
- `sqlVersions({ query })` takes any SQL driver as a function of text and
272
- parameters - node-postgres, mysql2, Kysely, Knex, D1 - and `createVersions`
273
- takes anything else.
274
-
275
- Install it in every process - the web server once, before the first request.
276
- `register()` also runs during the build, and that is fine: a store opens no
277
- connection until a tab is actually waiting on it, and postgres.js connects
278
- lazily, so a build never holds one open. Keep anything that connects eagerly
279
- out of `register()`, or the build waits on it and never exits.
280
-
281
-
282
- ```ts title="src/instrumentation.ts"
283
- import { installVersionSource } from '@rsc-kit/core/changed'
284
- import { versions } from './versions'
285
-
286
- export function register() {
287
- installVersionSource(versions)
288
- }
289
- ```
290
-
291
- and the worker, which then says what it finished:
292
-
293
- ```ts title="worker.ts"
294
- import { changed, installVersionSource } from '@rsc-kit/core/changed'
295
- import { versions } from './src/versions'
296
-
297
- installVersionSource(versions)
298
-
299
- queue.on('restoration.done', async (job) => {
300
- await changed(`restoration:${job.id}`)
301
- })
302
- ```
303
-
304
- Without `listen` and `notify` - MySQL, SQLite, or a driver that cannot listen -
305
- a waiting server reads the table every second instead (`poll` changes it).
306
-
307
- **From any process, without rsc-kit:** the table is the contract. A cron job,
308
- a service in another language, a database trigger - anything that can write
309
- to it can say a name changed:
310
-
311
- ```sql
312
- -- Postgres
313
- INSERT INTO rsc_versions (name, version) VALUES ('restoration:42', 1)
314
- ON CONFLICT (name) DO UPDATE SET version = rsc_versions.version + 1;
315
- NOTIFY rsc_versions; -- optional: wakes the listening servers at once
316
-
317
- -- MySQL
318
- INSERT INTO rsc_versions (name, version) VALUES ('restoration:42', 1)
319
- ON DUPLICATE KEY UPDATE version = version + 1;
320
-
321
- -- SQLite
322
- INSERT INTO rsc_versions (name, version) VALUES ('restoration:42', 1)
323
- ON CONFLICT (name) DO UPDATE SET version = version + 1;
324
- ```
325
-
326
- A version only has to *change*; the servers compare, they do not count. Go's
327
- `SQLVersions` uses the same table, so a Go service and a JavaScript app can
328
- share one.
329
-
330
- **Instant across instances on a client that cannot LISTEN** - `Bun.sql`, or
331
- a Drizzle or Prisma setup over one: keep it for reading and writing, and open
332
- one postgres.js connection only to listen. It costs one idle connection per
333
- process:
334
-
335
- ```ts title="src/versions.ts"
336
- import postgres from 'postgres'
337
-
338
- const listener = postgres(process.env.DATABASE_URL!, { max: 1 })
339
-
340
- export const versions = createVersions({
341
- read, // as above, on your own client
342
- bump,
343
- listen: (wake) => listener.listen('rsc_versions', wake),
344
- notify: () => listener.notify('rsc_versions', ''),
345
- })
346
- ```
347
-
348
- ### The table
349
-
350
- A shared store keeps one row per name. Your app owns the table: rsc-kit never
351
- creates, alters or migrates it at runtime - make it with your own migrations,
352
- in your own schema, with whatever your ORM calls these types. (Laravel ships
353
- one you publish into your own migrations, `--tag=rsc-migrations`; after that
354
- it is yours too.)
355
-
356
- | Column | Type | |
357
- | --- | --- | --- |
358
- | `name` | text, `PRIMARY KEY` (or a unique index) | the name a section refreshes on |
359
- | `version` | `BIGINT NOT NULL` | any integer; it only has to change |
360
-
361
- ```sql
362
- -- Postgres, SQLite
363
- CREATE TABLE rsc_versions (name TEXT PRIMARY KEY, version BIGINT NOT NULL);
364
- -- MySQL: an indexed TEXT needs a length
365
- CREATE TABLE rsc_versions (name VARCHAR(255) PRIMARY KEY, version BIGINT NOT NULL);
366
- ```
367
-
368
- - **Extra columns are fine** - an `updated_at`, say - as long as each has a
369
- default: rsc-kit and the documented upserts write only `name` and `version`.
370
- - **Another name is fine:** `sqlVersions({ table })`, `postgresVersions(sql,
371
- { table })`, Go's `SQLVersions{Table}`, Laravel's `RSC_VERSIONS_TABLE`.
372
- - **The NOTIFY channel** is `rsc_versions` whatever the table is called;
373
- `postgresVersions(sql, { channel })` changes it.
374
- - The same table works for Go's `SQLVersions` and Laravel's
375
- `RSC_VERSIONS=database`, so a JavaScript app, a Go service and a PHP job
376
- can share one.
377
-
378
- ### Say it after the write commits
379
-
380
- A tab that hears a name moved asks for its section at once. If the write
381
- that changed the data has not committed yet, that render reads the old data -
382
- and the tab is now at the new version, so it will not ask again until the
383
- next change. Inside a transaction, say it changed **after** the transaction,
384
- not inside it:
385
-
386
- ```ts
387
- await db.transaction(async (tx) => {
388
- await tx.insert(conversations).values(row)
389
- // not here: this transaction may still roll back, and has not committed
390
- })
391
-
392
- await changed(`agent:${row.agentId}:conversations`) // here
393
- ```
394
-
395
- The same goes for a worker writing the table directly: in the same
396
- transaction as the data, or after it - never before. In Laravel,
397
- `DB::afterCommit(fn () => Rsc::changed(...))` does this inside a transaction.
398
-
399
- **With a Go or Laravel backend:** the backend keeps them - a table in Go, the
400
- cache in Laravel - and you install nothing here. The renderer asks the
401
- backend which moved: Go holds the question until one does; PHP cannot hold a
402
- request open, so Laravel is asked again every couple of seconds while any tab
403
- is watching. To take PHP out of watching altogether, keep Laravel's versions
404
- in the table (`RSC_VERSIONS=database`) and have the renderer read it itself -
405
- an app's own store always wins over the backend's:
406
-
407
- ```ts title="src/instrumentation.ts"
408
- import { installVersionSource, postgresVersions } from '@rsc-kit/core/changed'
409
- import postgres from 'postgres'
410
-
411
- export function register() {
412
- installVersionSource(postgresVersions(postgres(process.env.DATABASE_URL!)))
413
- }
414
- ```
415
-
416
- Watching then costs PHP nothing, and `Rsc::changed()`'s NOTIFY reaches the
417
- tabs at once.
418
-
419
- ### The signing secret
420
-
421
- The names a page hands the tab are signed, so a tab can only listen for the
422
- names its page was rendered with - a browser cannot make one up. Every
423
- instance has to sign with the same key, or a tab served by one is refused by
424
- the next and never refreshes:
425
-
426
- ```sh
427
- RSC_SIGNING_SECRET=… # the same on every instance: openssl rand -base64 32
428
- ```
429
-
430
- It is its own secret, with or without a backend - not the backend's
431
- `RSC_HOST_CALL_SECRET`, which authorises a different thing. In production, an
432
- app that uses `refreshOn` without it refuses to serve, saying what to set: a
433
- random key per instance would fail silently.
434
-
435
- That refusal comes on the first request, because on some platforms - Workers
436
- - the environment is only there once a request arrives. Under Kubernetes or
437
- any orchestrator with a readiness check, that is too late: the pod is already
438
- taking traffic. Make the deploy itself fail instead, from `register()`, which
439
- runs before the server takes a request:
440
-
441
- ```ts title="src/instrumentation.ts"
442
- import { assertSigningSecret } from '@rsc-kit/core/changed'
443
-
444
- export function register() {
445
- assertSigningSecret() // throws in production without RSC_SIGNING_SECRET
446
- }
447
- ``` In development a random key is
448
- fine, and is what you get.
449
-
450
- How to generate it, where to keep it, and what rotating it does:
451
- [Secrets](/hosts/deployment#secrets).
452
-
453
- Names are signed when the page is served, never at build: a page stored at
454
- build keeps everything else stored, and the part that carries the names is
455
- filled per request. So the build does not need the secret.
456
-
457
- ### When nothing refreshes
458
-
459
- In development the browser console says what the page is watching, region
460
- by region, each time that changes:
461
-
462
- ```
463
- [rsc-kit] refreshOn watching, by region:
464
- repos: team:1:repos @3
465
- page: inbox:ada @0
466
- ```
467
-
468
- A region that declared `refreshOn` but is missing from that list rendered no
469
- names, and the server's log says why, once. And watching **stops while the
470
- tab is hidden** - a background tab holds no connection - which the console
471
- also says. Nothing is missed: shown again, the tab reconnects at the versions
472
- it holds and refreshes whatever moved meanwhile.
473
-
474
- ### When many tabs show the same thing
475
-
476
- When a name moves, every tab showing it asks for its sections again - 500 tabs
477
- on one team's board are 500 renders. Each tab's render can differ by who is
478
- looking, so by default each is its own. A section that is the same for
479
- everyone allowed to see the page can say so:
480
-
481
- ```tsx title="src/app/status/board.section.tsx"
482
- export default section('board', Board, { refreshOn: ['board'], shared: true })
483
- ```
484
-
485
- Then the tabs asking because of the same change get one render between them:
486
- the first tab's request renders it, and every other gets the same bytes.
487
- Each tab's guards still run on its own request - a visitor who may not see
488
- the page is still refused - and only a refresh a change triggered is shared,
489
- so `refresh()` by hand, or after an action, always renders afresh.
490
-
491
- Never set `shared` on a section that shows anything per visitor - their name,
492
- their data, what they may do. The first tab's render is what every other tab
493
- is shown, `rpc()` calls included: they run with the first visitor's session.
494
-
495
- ### What it costs
496
-
497
- - **Per tab:** one open connection while the page is visible, closed when the
498
- tab is hidden and reopened when it is seen again. Idle, it carries a
499
- keepalive line every eight seconds ([set it lower](/hosts/deployment#streams-and-idle-timeouts)
500
- under a shorter idle timeout); a change is one line of about forty
501
- bytes.
502
- - **Per change:** each tab showing the name asks for the sections that show
503
- it, once, however many names moved together. That request is the size of
504
- the section, not the page. A `shared` section renders once per change for
505
- every tab; any other renders once per tab.
506
- - **On the server:** one ask of wherever the versions live, covering every tab
507
- that server holds - a thousand open tabs are one query, not a thousand. The
508
- ask may wait up to five seconds for a change: a database with `listen`, or a
509
- Go backend, answers the moment a version moves; a table without it is read
510
- once a second while the ask waits; Laravel answers at once and is asked again
511
- two seconds later. Plus one small read when each tab opens its stream.
512
-
513
- Polling a section every two seconds instead costs a full render of it, per
514
- tab, every two seconds, whether anything changed or not. The trade is the open
515
- connection: cheap on Bun, Node and Workers; on a host that bills a function
516
- for every second it is open, it is a second billed for as long as the tab is.
517
-
518
- ### Coming from Next.js
519
-
520
- This is where `revalidateTag` was, and it is not the same thing. Next's tags
521
- label entries in its Data Cache and `revalidateTag()` throws them away, so the
522
- *next request* refetches; an open tab learns nothing until it navigates.
523
- There is no data cache here - every render is fresh - so `refreshOn` names
524
- what is *on screen*, and `changed()` refreshes every open tab showing it, now.
525
- A port keeps its names: `tags: ['posts']` on the fetch becomes
526
- `refreshOn: ['posts']` on the section, and `revalidateTag('posts')` becomes
527
- `changed('posts')`.
528
-
529
- A name's version reveals only that something with that name changed. Do not
530
- put a secret in a name.
71
+ An action refreshes the sections it changed. For a change made anywhere else -
72
+ a webhook, a job, another visitor - a section can name what it depends on and
73
+ refresh itself in every open tab: `section('repos', Repos, { refreshOn })`.
74
+ That has its own guide: [Live data](/guides/live-data).
531
75
 
532
76
  ## The name is scoped to the module, not the app
533
77
 
@@ -44,6 +44,14 @@ change:
44
44
  nitro({ preset: 'vercel', serveStatic: 'inline' })
45
45
  ```
46
46
 
47
+ ## Streams on serverless platforms
48
+
49
+ `events()` routes and `refreshOn` hold a connection open. On Workers and
50
+ serverless functions each isolate or instance watches for its own tabs, a
51
+ platform's request limits cut streams (they reconnect and catch up), and
52
+ versions must live in a shared store. [On Workers and serverless](/guides/live-data#on-workers-and-serverless)
53
+ has the details.
54
+
47
55
  ## Running it
48
56
 
49
57
  ```bash
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rsc-kit/mcp",
3
- "version": "0.27.1",
3
+ "version": "0.28.1",
4
4
  "description": "An MCP server over what an rsc-kit build decided: the routes, why each one is static or not, and what it costs the browser.",
5
5
  "type": "module",
6
6
  "license": "MIT",