0
Fork 0
mirror of https://github.com/mastra-ai/mastra.git synced 2026-11-17 08:44:46 +00:00
mastra/examples
Marvin Frachet 1034a4e41f
feat(json-render): add @mastra/json-render so agents can compose json-render interfaces (#29914)
(starts after a few seconds, white screens stays a bit)


https://github.com/user-attachments/assets/27f91819-b4ad-41b5-b743-6de6e5690099





## Description

Adds `@mastra/json-render`, a new integration that lets Mastra agents
compose [json-render](https://json-render.dev) interfaces from a
component catalog you define. json-render owns the spec format, the
prompt and the rendering. Mastra handles streaming, memory and
validation.

The catalog lists the components and actions the model may use. It has
no React in it, so the server (prompt, validation) and the client
(rendering) share the same file:

```ts
// src/catalog.ts
import { defineCatalog } from '@json-render/core';
import { schema } from '@json-render/react/schema';
import { z } from 'zod';

export const catalog = defineCatalog(schema, {
  components: {
    Stack: { description: 'Lays out its children vertically', props: z.object({ gap: z.number().optional() }) },
    Card: { description: 'A card with a title', props: z.object({ title: z.string() }) },
    Text: { description: 'A line of text', props: z.object({ text: z.string() }) },
    Button: { description: 'A button that runs an action on press', props: z.object({ label: z.string() }) },
  },
  actions: {
    ask: {
      description: 'Send a follow-up prompt to the agent',
      params: z.object({ prompt: z.string() }),
    },
  },
});
```

The Zod schemas describe each component's props in the prompt, and the
processor validates every spec against them before saving it. The agent
gets its instructions from the catalog and runs the processor on both
sides:

```ts
// src/mastra/agents/ui-agent.ts
import { Agent } from '@mastra/core/agent';
import { JsonRenderProcessor } from '@mastra/json-render';
import { Memory } from '@mastra/memory';
import { catalog } from '../../catalog';

const ui = new JsonRenderProcessor({ catalog });

const agent = new Agent({
  id: 'ui-agent',
  name: 'UI Agent',
  model: 'openai/gpt-6.1-sol',
  instructions: catalog.prompt({
    mode: 'inline',
    editModes: ['patch'],
    system: 'You are a travel assistant. Prefer showing an interface over describing it.',
    customRules: ['Wrap everything in a Stack root.'],
  }),
  inputProcessors: [ui],
  outputProcessors: [ui],
  maxProcessorRetries: 2,
  memory: new Memory(),
});
```

`system` holds the agent's own instructions and replaces json-render's
default intro at the top of the prompt. `customRules` adds rules at the
end. The catalog's component list and output format go in between.

**What it does**

- **Streams interfaces.** The model writes spec blocks in json-render's
inline format. The processor turns them into `data-spec` parts, so the
interface streams to the client while the reply's text keeps only the
prose. The client renders them with `useJsonRenderMessage()` from
`@json-render/react`.
- **Saves interfaces in memory.** The `data-spec` parts are stored with
the message, so interfaces render again after a reload.
- **Edits interfaces in later turns.** Mastra drops data parts when it
builds the prompt, so on its own the model would forget the interface it
wrote. Before each model call, the processor replays the latest
interface into the reply that wrote it, in the prompt only, without
changing the stored thread. The model can then edit that interface with
a few patches.
- **Keeps what the user set.** The client sends the interface's state,
such as ticked checkboxes or selected filters, under the
`JSON_RENDER_STATE` request context key. The model sees it, and edits
keep it.
- **Validates specs.** Each spec is checked against the catalog,
including props inside repeated elements and duplicate repeat keys. An
invalid spec goes back to the model to fix before it's saved.

Tools can show their own interface by writing `data-spec` parts, and
later turns can edit those too.

**Docs:** adds a new page under Agentic UI
(`integrations/agentic-ui/json-render`).

**Studio:** unchanged. Studio keeps showing only the prose of these
replies. `examples/agent` adds a `gen-ui-agent` with its own catalog to
try the processor.

**Known limitation:** in json-render `0.22`, `buildSpecFromParts()`
changes the parts it applies, so rebuilding from the same parts repeats
list items. The processor works around this on the server. On the
client, apps should pass `useJsonRenderMessage()` a copy of the parts.
The docs page covers this.

## Related issue(s)

<!-- TODO: link issue -->

## Type of change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [x] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test update

## Test plan

- `integrations/json-render`: 32 tests pass. They run a real `Agent`
with `Memory` and a mocked model. They cover streaming, reload from
memory, edits, replay into the prompt, user state, tool-written
interfaces, validation retries, patches that cannot be applied, repeated
elements, duplicate keys, and JSON Patch examples in other code blocks
staying as prose. A React test drives `useChat` and json-render's
`Renderer` through MSW.
- `tsc`, oxlint, prettier and the package builds pass.
- The docs page passes `pnpm check`. Its code examples typecheck against
the real packages.
- Tested by hand in a Vite + React example app with Playwright: weather
interface from a tool result, streamed itinerary with Stop mid-stream,
dashboard filters followed by "which filters did I pick?" (answered in
plain text, no new interface), follow-up action buttons, a large
composed board, an edit that keeps ticked items, editing a tool-written
interface, and reloading a long thread.

## Checklist

- [ ] I have linked the related issue(s) in the description above
- [x] I have made corresponding changes to the documentation (if
applicable)
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] I have addressed all Coderabbit comments on this PR




<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

**ELI5:** This PR adds a package that lets an AI agent send small
interface layouts, such as cards and metrics, to a web app. The app
draws them as real UI. The package also checks each layout against a
list of allowed parts, so the model can fix mistakes.

## Summary

This PR adds `@mastra/json-render`. The package connects json-render
interfaces with Mastra agents.

The package provides:

- `JsonRenderProcessor`, which works as an agent input and output
processor.
- `JSON_RENDER_STATE`, a key for sending interface state to the agent.
- Support for streamed `data-spec` message parts.
- Saved interfaces that render again after a page reload.
- Edits to saved interfaces. The processor replays prior interfaces by
message order.
- Validation of each assistant interface against the catalog. The
processor retries the model when the interface fails validation.

Studio rendering is not part of this PR. A later commit removed it. The
README no longer documents the Studio catalog setup or its component
limits.

## Changes by area

**Package (`integrations/json-render`)**
- Adds the package manifest, with ESM and CommonJS entry points.
- Sets the peer dependencies: `@json-render/core` `^0.22.0`,
`@mastra/core` `>=1.83.0-0 <2.0.0-0`, and Zod `>=3.25.0 || >=4.0.0`.
- Adds the build, lint, and test setup: `tsconfig.json`,
`tsconfig.build.json`, `tsdown.config.ts`, `turbo.json`,
`vitest.config.ts`, and `lint-staged.config.js`.
- Re-exports `JSON_RENDER_STATE`, `JsonRenderProcessor`, and the
`JsonRenderProcessorOptions` type from `src/index.ts`.
- Adds `src/processor.ts`, which:
- Converts ` ```spec ` blocks and eligible JSON Patch lines into
`data-spec` parts.
  - Keeps prose in the text stream.
- Accepts patches outside a spec fence only for `/root`, `/elements`,
and `/state`.
  - Rebuilds the latest spec from saved parts and adds it to the prompt.
- Aborts with a retry at output-step completion when the spec has
validation errors, unknown components, invalid props, duplicate repeat
keys, or an unappliable patch.

**Tests**
- `src/processor.test.ts` covers stream splitting, validation and retry,
patch edits, state handling, and conversation context.
- `src/react-chat.test.tsx` is a jsdom suite. It covers rendering from a
streamed response, rendering from saved messages, and sending state with
an action.
- `src/__tests__/test-utils.ts` adds shared catalog, spec, model, and
agent helpers.

**Documentation**
- `README.md` covers installation, processor setup, rendering
`data-spec` parts, sending `JSON_RENDER_STATE`, and calling
`buildSpecFromParts()`.
- `.changeset/json-render-processor.md` adds a minor changeset.
- `CHANGELOG.md` adds a heading for `@mastra/json-render`.

**Example agent (`examples/agent`)**
- Adds `gen-ui-catalog.ts`, which defines `genUICatalog` with eight
components: `Stack`, `Grid`, `Card`, `Heading`, `Text`, `Badge`,
`Metric`, and `Notice`. The catalog has no actions.
- Adds `gen-ui-agent.ts`, which defines `genUIAgent`. The agent uses the
catalog in inline mode with patch edits, the `openai/gpt-5.4-mini`
model, the JSON-render processors, two retries, and memory.
- Registers `genUIAgent` in `src/mastra/index.ts`.
- Adds the `@json-render/core` and `@json-render/react` dependencies at
`^0.22.0`, and `@mastra/json-render` at `latest`. Adds a pnpm override
that links `@mastra/json-render` to `../../integrations/json-render`.
- Updates `README.md` to require `pnpm setup` from the repository root
before installing dependencies.

## Validation

The author reports these results. They are not verified in this summary.

- 41 of 41 json-render tests pass.
- 59 of 59 playground-ui `message-row` tests pass.
- TypeScript and oxlint report no errors.

The author reports one open CI check: "New packages exist on npm." This
check needs an npm admin to reserve the `@mastra/json-render` name.
Completed CI results for the current head are not available.

## Scope

The diff has 22 changed files, with 1658 lines added and 3 removed.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: mastracode <284800079+mastra-platform[bot]@users.noreply.github.com>
History 2026-11-16 09:04:48 +01:00
..
agent feat(json-render): add @mastra/json-render so agents can compose json-render interfaces (#29914) 2026-11-16 09:04:48 +01:00
agent-builder chore(deps): update better-auth monorepo to v1.7.22 (#30464) 2026-11-15 17:48:36 -08:00
durable-agents chore(deps): update better-auth monorepo to v1.7.22 (#30464) 2026-11-15 17:48:36 -08:00
evals-with-memory chore(deps): update better-auth monorepo to v1.7.22 (#30464) 2026-11-15 17:48:36 -08:00
inngest chore(security): Vanta 2026-10-30 - zod ^4.6.7, @hono/node-server 2.1.5 (direct bumps) (#28983) 2026-10-30 15:30:35 -04:00
mcp-events chore(deps): lock file maintenance (#27013) 2026-10-21 09:25:38 +02:00
oracledb chore(deps): update better-auth monorepo to v1.7.22 (#30464) 2026-11-15 17:48:36 -08:00
sandbox-deployer chore(deps): update better-auth monorepo to v1.7.22 (#30464) 2026-11-15 17:48:36 -08:00
voice fix(auth): transparent server-side session refresh to eliminate 401 cascade (#15819) 2026-04-28 08:38:11 -07:00
voice-agent chore(deps): update better-auth monorepo to v1.7.22 (#30464) 2026-11-15 17:48:36 -08:00
AGENTS.md docs: clarify example dev command (#17095) 2026-05-27 16:19:54 -04:00
README.md docs: fix onboarding quickstart, pnpm version, and template metadata (#23754) 2026-09-15 09:40:58 +02:00

How to run the examples

Navigate to the example directory you want to run. For example:

cd examples/agent

Install the packages:

pnpm install --ignore-workspace

The examples have a separate package.json file and are not part of the Mastra workspace. Most examples can use npm install. If an example links local workspace packages, use pnpm install --ignore-workspace from that example directory instead.

Run the appropriate CLI command in your terminal (may vary by example). For example for the agent example:

pnpm mastra:dev