(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>
10 KiB
Mastra Agent Examples
This directory contains example agents demonstrating various Mastra features.
Getting Started
-
The example links the repository's packages, so build them first from the
mastrarepository root:pnpm setup -
Change into this example directory and install dependencies:
cd examples/agent pnpm install --ignore-workspace -
Set up environment variables:
cp .env.example .env # Edit .env with your API keys -
Run the example:
pnpm start
Available Scripts
pnpm start- Run the agent examplespnpm mastra:dev- Start Mastra development serverpnpm mastra:studio- Open Mastra Studio UIpnpm mastra:build- Build for productionpnpm mastra:start- Start production server
Computer-use agent
The computer-use-agent controls a remote Linux desktop through workspace screenshot, mouse, keyboard, and shell tools. It uses Daytona by default:
DAYTONA_API_KEY=your-daytona-api-key
To use E2B Desktop instead, set:
COMPUTER_USE_PROVIDER=e2b-desktop
E2B_API_KEY=your-e2b-api-key
Then start the linked workspace version of Mastra:
pnpm mastra dev
Open Computer Use Agent in Studio and try:
Take a screenshot and report the screen dimensions. Open a terminal through the desktop UI, create
/tmp/computer-use-demo.txtcontaining a unique marker, then use the shell tool to read the file and verify that the GUI and shell are operating on the same machine.
Only COMPUTER_USE_PROVIDER=e2b-desktop selects E2B Desktop; any other value uses Daytona. The selected provider's API key is required when the agent first uses a computer or shell tool.
Computer actions can create billable cloud sandboxes. Stop or destroy test sandboxes when you're finished, and don't share authenticated desktop stream URLs.
Request Context Presets
This example includes a demonstration of Mastra's Request Context Presets feature, which allows you to define named configurations that can be easily switched between in the Studio UI.
What are Request Context Presets?
Request context presets are predefined JSON configurations that can be selected from a dropdown in the Mastra Studio Playground. This feature enables you to quickly switch between different environments, user roles, or scenarios without manually editing JSON each time.
Using Request Context Presets
1. Running with Presets in Dev Mode
mastra dev --request-context-presets ./request-context-presets.json
2. Running with Presets in Studio Mode
mastra studio --request-context-presets ./request-context-presets.json
3. Using the Presets Dropdown
Once you start Mastra with the --request-context-presets flag:
- Open the Mastra Studio in your browser
- Navigate to an agent's page
- Look for the Request Context section
- You'll see a dropdown with available presets
- Select a preset to automatically populate the JSON editor with that configuration
- Click "Save" to apply the context to your agent interactions
The dropdown includes a "Custom" option that is automatically selected when you manually edit the JSON.
Available Presets in This Example
This example includes the following presets in request-context-presets.json:
Environment Presets
-
development: Development environment with debug logging
- API endpoint:
https://dev-api.example.com - Debug mode: enabled
- Log level: debug
- API endpoint:
-
production: Production environment with minimal logging
- API endpoint:
https://api.example.com - Debug mode: disabled
- Log level: error
- API endpoint:
-
staging: Staging environment for testing
- API endpoint:
https://staging-api.example.com - Debug mode: enabled
- Log level: info
- API endpoint:
Role-Based Presets
-
admin-user: Full administrative access
- Permissions: read, write, delete, manage
- Advanced tools: enabled
- Analytics: enabled
-
guest-user: Limited read-only access
- Permissions: read only
- Advanced tools: disabled
- Analytics: disabled
Request Context Demo Agent
The requestContextDemoAgent demonstrates how agents can dynamically adapt their behavior based on the request context:
Dynamic Agent Behavior
-
Instructions: Vary by environment and role
- Development mode includes verbose debugging instructions
- Production mode provides optimized, concise guidance
- Log level affects response detail
-
Model Selection: Automatically chooses appropriate model
- Production:
gpt-5(higher quality) - Development/Staging:
gpt-5-mini(faster iteration)
- Production:
-
Tool Availability: Conditionally provides tools based on permissions
apiRequestTool: Available to all users, uses environment-specific endpointsadminActionTool: Only available with "manage" permissionanalyticsTool: Only available whenfeatures.analyticsis enabled
Testing Different Presets
Try switching between presets to see how the agent behaves differently:
-
Select the development preset and ask: "Make an API request to fetch user data"
- Agent will use the dev API endpoint with debug logging
-
Select the admin-user preset and ask: "Show me analytics for the platform"
- Agent will have access to analytics tools
-
Select the guest-user preset and ask the same question
- Agent will explain it doesn't have permission for analytics
Creating Your Own Presets File
You can create custom presets for your own use cases:
{
"preset-name": {
"customField": "value",
"nested": {
"data": "example"
}
},
"another-preset": {
"userId": "user-123",
"tenant": "acme-corp"
}
}
Requirements:
- The file must contain a valid JSON object
- Each preset must be an object (not a string, number, or array)
- Preset values can contain any valid JSON structure
Benefits
- Faster Testing: Switch between configurations instantly
- Consistency: Ensure the same configuration is used across team members
- Documentation: Preset names serve as documentation of supported scenarios
- No Manual Editing: Reduce errors from typing JSON manually
- Environment Parity: Test production configurations in development
Dynamic Workflow Demo — daily-standup-digest
This example seeds a workflow at boot from a JSON DynamicWorkflowGraph, without ever calling createWorkflow(...). The workflow shows up in Studio like any other workflow because mastra.addDynamicWorkflow(...) persists it to WorkflowDefinitionsStorage and live-registers it in one shot.
What it demonstrates
- Declarative
tool/agent/mapping/foreach/conditional/workflowentry types round-tripping from JSON. - The three-scope template model:
${initData.teamName}and${stepResults.normalize-each-note}in amappingstep, with the array of per-note outputs JSON-encoded automatically. foreach(agent)withconcurrency, rehydrated from JSON.- A
conditionalstep with declarative predicates that picks between two nested dynamic sub-workflows (daily-standup-plainwhen there are no blockers,daily-standup-with-escalationwhen there are). Theconditional's output is{ markdown: string }regardless of branch, which becomes the parent workflow's terminal output. - Nested dynamic workflows as a first-class step type — the parent JSON references sub-workflows by id, they live in their own JSON files, and each can be inspected, run, or edited independently in Studio.
- Restart survival: kill
pnpm mastra dev, restart, and all three workflows are still there becauseLibSQLStore'sworkflowDefinitionsdomain persists them.
Files
src/mastra/dynamic-workflows/daily-standup-digest.json— the top-levelDynamicWorkflowGraph(normalize → detect blockers → conditional → nested sub-workflow).src/mastra/dynamic-workflows/daily-standup-plain.json— sub-workflow used when there are no blockers.src/mastra/dynamic-workflows/daily-standup-with-escalation.json— sub-workflow used when there are blockers; also drafts a tech-lead escalation message.src/mastra/dynamic-workflows/daily-standup-agents.ts— the three agents referenced byagentId.src/mastra/dynamic-workflows/daily-standup-tools.ts— the four tools referenced bytoolId.src/mastra/index.ts— imports the JSON files and seeds all three viamastra.addDynamicWorkflow(...)after theMastrainstance is constructed. The two sub-workflows are seeded before the parent socollectRefscan resolve their ids.
Try it
pnpm mastra dev
Then in Studio:
- Open Workflows →
daily-standup-digest. - Run with an input that has at least one real blocker to hit the escalation branch:
{ "teamName": "Platform", "notes": [ { "author": "Alex", "text": "yesterday shipped the auth fix. today wiring up the retry queue. blocked on staging creds." }, { "author": "Sam", "text": "finished the migration script. moving on to the dashboard rewrite. no blockers." } ] } - Or run with all-clear notes to hit the plain-digest branch:
{ "teamName": "Platform", "notes": [ { "author": "Alex", "text": "shipped auth fix. today: retry queue. no blockers." }, { "author": "Sam", "text": "migration done. today: dashboard rewrite. no blockers." } ] } - Confirm the run produces a
markdownoutput with a dated# Platform — Daily Standup (...)header. The blocker input additionally includes a## Escalationsection drafted by thestandup-escalationagent.
Proof of restart survival
- Run
pnpm mastra devonce so the workflow is upserted intomastra.db. - Stop the process.
- Delete
src/mastra/dynamic-workflows/daily-standup-digest.json(temporarily). - Restart
pnpm mastra dev— the workflow still appears in Studio because it was loaded from storage on boot, not from the JSON file. - Restore the JSON file when done.