Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

Add GenerativeUI provider, bump prefab-ui 0.14.0 (#3647)

Jeremiah Lowince7758e9b30d
diff --git a/docs/apps/components.mdx b/docs/apps/components.mdx
index 22f4b9094..5283a7903 100644
--- a/docs/apps/components.mdx
+++ b/docs/apps/components.mdx
@@ -489,18 +489,18 @@ with Dialog(title="Confirm Delete"):
Multi-page navigation within a single app. `Pages` renders one `Page` at a time, controlled by state. Useful for multi-step workflows and wizards.
```python
-from prefab_ui.app import set_initial_state
from prefab_ui.components import Pages, Page, Text, Button
from prefab_ui.actions import SetState
+from prefab_ui.rx import Rx
-state = set_initial_state(page="welcome")
-
-with Pages(active_page=state.page):
+with Pages(active_page=Rx("page")):
with Page("welcome"):
Text("Welcome!")
Button("Next", on_click=SetState("page", "setup"))
with Page("setup"):
Text("Configure your settings")
+
+# Pass state={"page": "welcome"} to PrefabApp when returning
```
| Prop (Pages) | Type | Description |
@@ -516,18 +516,20 @@ Control flow components conditionally show or iterate over children based on rea
Conditionally render content based on state values. `If` evaluates an `Rx` expression; `Elif` and `Else` follow the same pattern as Python's branching.
```python
-from prefab_ui.app import set_initial_state
from prefab_ui.components import If, Elif, Else, Text, Select
+from prefab_ui.rx import Rx
-state = set_initial_state(role="viewer")
+role = Rx("role")
Select(name="role", options=["viewer", "editor", "admin"])
-with If(state.role == "admin"):
+with If(role == "admin"):
Text("Full access")
-with Elif(state.role == "editor"):
+with Elif(role == "editor"):
Text("Edit access")
with Else():
Text("Read-only access")
+
+# Pass state={"role": "viewer"} to PrefabApp when returning
```
### ForEach
diff --git a/docs/apps/interactive-apps.mdx b/docs/apps/interactive-apps.mdx
index c8f9e2356..bcf82f41a 100644
--- a/docs/apps/interactive-apps.mdx
+++ b/docs/apps/interactive-apps.mdx
@@ -244,17 +244,16 @@ Button(
A common pattern: show a loading indicator while a server call is in flight.
```python
-from prefab_ui.app import set_initial_state
from prefab_ui.actions import SetState, ShowToast
from prefab_ui.actions.mcp import CallTool
from prefab_ui.components import Button
-from prefab_ui.rx import RESULT
+from prefab_ui.rx import RESULT, Rx
-state = set_initial_state(saving=False)
+saving = Rx("saving")
Button(
- state.saving.then("Saving...", "Save"),
- disabled=state.saving,
+ saving.then("Saving...", "Save"),
+ disabled=saving,
on_click=[
SetState("saving", True),
CallTool(
@@ -271,6 +270,8 @@ Button(
),
],
)
+
+# Pass state={"saving": False} to PrefabApp when returning
```
## Forms
diff --git a/docs/apps/patterns.mdx b/docs/apps/patterns.mdx
index 9822ccc1f..b2b0eeade 100644
--- a/docs/apps/patterns.mdx
+++ b/docs/apps/patterns.mdx
@@ -224,8 +224,9 @@ These patterns use state and `Rx()` for client-side interactivity β€” no server
### Feature Toggles
```python
-from prefab_ui.app import PrefabApp, set_initial_state
+from prefab_ui.app import PrefabApp
from prefab_ui.components import Column, Heading, Switch, Alert, If, Separator
+from prefab_ui.rx import Rx
from fastmcp import FastMCP
mcp = FastMCP("Flags")
@@ -234,23 +235,21 @@ mcp = FastMCP("Flags")
@mcp.tool(app=True)
def feature_flags() -> PrefabApp:
"""Toggle feature flags with live preview."""
- state = set_initial_state(dark_mode=False, beta=False)
-
with Column(gap=4, css_class="p-6") as view:
Heading("Feature Flags")
Switch(name="dark_mode", label="Dark Mode")
Switch(name="beta", label="Beta Features")
Separator()
- with If(state.dark_mode):
+ with If(Rx("dark_mode")):
Alert(title="Dark mode enabled", description="UI will use dark theme.")
- with If(state.beta):
+ with If(Rx("beta")):
Alert(
title="Beta features active",
description="Experimental features are now visible.",
variant="warning",
)
- return PrefabApp(view=view)
+ return PrefabApp(view=view, state={"dark_mode": False, "beta": False})
```
### Tabs
diff --git a/docs/apps/prefab.mdx b/docs/apps/prefab.mdx
index 28dd95e9e..50a44a8c8 100644
--- a/docs/apps/prefab.mdx
+++ b/docs/apps/prefab.mdx
@@ -106,11 +106,12 @@ Display tools can be interactive without calling the server. The key is **state*
### Declaring State
-Use `set_initial_state()` to declare state and get a typed proxy for referencing it:
+Pass a `state` dict to `PrefabApp` to declare initial state, then use `Rx("key")` to create reactive references:
```python
-from prefab_ui.app import PrefabApp, set_initial_state
+from prefab_ui.app import PrefabApp
from prefab_ui.components import Column, Heading, Switch, Alert, If
+from prefab_ui.rx import Rx
from fastmcp import FastMCP
mcp = FastMCP("Flags")
@@ -119,32 +120,30 @@ mcp = FastMCP("Flags")
@mcp.tool(app=True)
def feature_flags() -> PrefabApp:
"""Toggle feature flags with live preview."""
- state = set_initial_state(dark_mode=False, beta=False)
-
with Column(gap=4, css_class="p-6") as view:
Heading("Feature Flags")
Switch(name="dark_mode", label="Dark Mode")
Switch(name="beta", label="Beta Features")
- with If(state.dark_mode):
+ with If(Rx("dark_mode")):
Alert(title="Dark mode enabled")
- with If(state.beta):
+ with If(Rx("beta")):
Alert(title="Beta features active", variant="warning")
- return PrefabApp(view=view)
+ return PrefabApp(view=view, state={"dark_mode": False, "beta": False})
```
Three things to notice here:
-`set_initial_state()` declares the keys and their starting values, and returns a proxy object. Accessing `state.dark_mode` gives you a reactive reference (an `Rx` object) that compiles to `{{ dark_mode }}` in the wire protocol. A typo like `state.drk_mode` raises an `AttributeError` immediately.
+The `state` dict on `PrefabApp` declares the keys and their starting values. `Rx("dark_mode")` creates a reactive reference that compiles to `{{ dark_mode }}` in the wire protocol.
-Interactive components with a `name` prop automatically bind to state. The `Switch(name="dark_mode")` syncs its on/off value to `state["dark_mode"]` on every toggle β€” no event wiring needed.
+Interactive components with a `name` prop automatically bind to state. The `Switch(name="dark_mode")` syncs its on/off value to the `dark_mode` state key on every toggle β€” no event wiring needed.
-`If(state.dark_mode)` shows its children only when the state key is truthy. When the switch flips, the condition re-evaluates instantly in the browser.
+`If(Rx("dark_mode"))` shows its children only when the state key is truthy. When the switch flips, the condition re-evaluates instantly in the browser.
### Reactive References with Rx
-The `Rx` class is how you reference state in component props. When you write `state.dark_mode`, you get an `Rx("dark_mode")` object. You can also create them directly:
+The `Rx` class is how you reference state in component props:
```python
from prefab_ui.rx import Rx
@@ -155,8 +154,9 @@ count = Rx("count")
Rx objects support arithmetic, comparisons, and formatting β€” they compile to expressions the renderer evaluates at render time:
```python
-from prefab_ui.app import PrefabApp, set_initial_state
+from prefab_ui.app import PrefabApp
from prefab_ui.components import Column, Text, Slider
+from prefab_ui.rx import Rx
from fastmcp import FastMCP
mcp = FastMCP("Calculator")
@@ -165,10 +165,11 @@ mcp = FastMCP("Calculator")
@mcp.tool(app=True)
def tip_calculator() -> PrefabApp:
"""Calculate tip with a slider."""
- state = set_initial_state(bill=50.00, tip_pct=18)
+ tip_pct = Rx("tip_pct")
+ bill = Rx("bill")
- tip_amount = state.tip_pct / 100 * state.bill
- total = state.bill + tip_amount
+ tip_amount = tip_pct / 100 * bill
+ total = bill + tip_amount
with Column(gap=4, css_class="p-6") as view:
Slider(name="bill", label="Bill Amount", min=0, max=500, step=0.5)
@@ -176,23 +177,27 @@ def tip_calculator() -> PrefabApp:
Text(f"Tip: {tip_amount.currency()}")
Text(f"Total: {total.currency()}")
- return PrefabApp(view=view)
+ return PrefabApp(view=view, state={"bill": 50.00, "tip_pct": 18})
```
-`state.tip_pct / 100 * state.bill` builds a compound expression β€” it doesn't do the math in Python. The renderer evaluates it live as the sliders move. The `.currency()` pipe formats the result as currency.
+`Rx("tip_pct") / 100 * Rx("bill")` builds a compound expression β€” it doesn't do the math in Python. The renderer evaluates it live as the sliders move. The `.currency()` pipe formats the result as currency.
#### Pipes
Rx objects support formatting pipes that transform values at render time:
```python
-state = set_initial_state(price=42.50, ratio=0.85, name="alice")
+from prefab_ui.rx import Rx
-state.price.currency() # $42.50
-state.price.currency("EUR") # EUR format
-state.ratio.percent() # 85%
-state.name.upper() # ALICE
-state.name.truncate(10) # alice (or truncated if longer)
+price = Rx("price")
+ratio = Rx("ratio")
+name = Rx("name")
+
+price.currency() # $42.50
+price.currency("EUR") # EUR format
+ratio.percent() # 85%
+name.upper() # ALICE
+name.truncate(10) # alice (or truncated if longer)
```
Number pipes include `currency`, `percent`, `number`, `compact`, `round`, and `abs`. String pipes include `upper`, `lower`, and `truncate`. See the [Prefab expression docs](https://prefab.prefect.io/docs/concepts/expressions) for the full list.
@@ -202,11 +207,13 @@ Number pipes include `currency`, `percent`, `number`, `compact`, `round`, and `a
The `.then()` method creates ternary expressions:
```python
-state = set_initial_state(connected=True)
+from prefab_ui.rx import Rx
+
+connected = Rx("connected")
Badge(
- state.connected.then("Online", "Offline"),
- variant=state.connected.then("success", "destructive"),
+ connected.then("Online", "Offline"),
+ variant=connected.then("success", "destructive"),
)
```
@@ -215,7 +222,7 @@ Badge(
Python `for` loops generate static content at build time. When you need to iterate over state that can change β€” a list that grows, items that get filtered β€” use `ForEach`:
```python
-from prefab_ui.app import PrefabApp, set_initial_state
+from prefab_ui.app import PrefabApp
from prefab_ui.components import Column, Heading, ForEach, Row, Text, Badge
from fastmcp import FastMCP
@@ -247,10 +254,11 @@ def team_list() -> PrefabApp:
`If`, `Elif`, and `Else` control what's visible based on state:
```python
-from prefab_ui.app import PrefabApp, set_initial_state
+from prefab_ui.app import PrefabApp
from prefab_ui.components import Column, Select, If, Elif, Else, Text
+from prefab_ui.rx import Rx
-state = set_initial_state(tier="free")
+tier = Rx("tier")
with Column(gap=4) as view:
Select(
@@ -258,12 +266,14 @@ with Column(gap=4) as view:
label="Plan",
options=["free", "pro", "enterprise"],
)
- with If(state.tier == "enterprise"):
+ with If(tier == "enterprise"):
Text("Full access to all features")
- with Elif(state.tier == "pro"):
+ with Elif(tier == "pro"):
Text("Advanced features unlocked")
with Else():
Text("Basic features only")
+
+# Pass state={"tier": "free"} to PrefabApp when returning
```
Changes are instant β€” switching the dropdown re-evaluates the conditions in the browser.
@@ -285,20 +295,13 @@ def status() -> Column:
### PrefabApp
-When you need initial state or other configuration, return a `PrefabApp` explicitly. If you've called `set_initial_state()` during the tool, PrefabApp picks up that state automatically:
+When you need initial state or other configuration, return a `PrefabApp` explicitly with a `state` dict:
```python
@mcp.tool(app=True)
def dashboard() -> PrefabApp:
- state = set_initial_state(tab="overview")
# ... build view ...
- return PrefabApp(view=view)
-```
-
-You can also pass state directly:
-
-```python
-return PrefabApp(view=view, state={"tab": "overview"})
+ return PrefabApp(view=view, state={"tab": "overview"})
```
### ToolResult
diff --git a/examples/apps/approvals/approvals_server.py b/examples/apps/approvals/approvals_server.py
index 9eec6161a..c9204809b 100644
--- a/examples/apps/approvals/approvals_server.py
+++ b/examples/apps/approvals/approvals_server.py
@@ -15,7 +15,7 @@ from __future__ import annotations
from prefab_ui.actions import SetState, ShowToast
from prefab_ui.actions.mcp import CallTool
-from prefab_ui.app import PrefabApp, set_initial_state
+from prefab_ui.app import PrefabApp
from prefab_ui.components import (
Badge,
Button,
@@ -285,15 +285,9 @@ def _build_request_card(
@app.ui()
def approval_dashboard() -> PrefabApp:
"""Open the approval dashboard. The model calls this to launch the app."""
- state = set_initial_state(
- pending_requests=_by_status("pending"),
- approved_requests=_by_status("approved"),
- rejected_requests=_by_status("rejected"),
- )
-
- pending_count = state.pending_requests.length()
- approved_count = state.approved_requests.length()
- rejected_count = state.rejected_requests.length()
+ pending_count = Rx("pending_requests").length()
+ approved_count = Rx("approved_requests").length()
+ rejected_count = Rx("rejected_requests").length()
with Column(gap=6, css_class="p-6") as view:
with Row(gap=3, align="center"):
@@ -323,7 +317,14 @@ def approval_dashboard() -> PrefabApp:
with If(~rejected_count):
Muted("No rejected requests.")
- return PrefabApp(view=view)
+ return PrefabApp(
+ view=view,
+ state={
+ "pending_requests": _by_status("pending"),
+ "approved_requests": _by_status("approved"),
+ "rejected_requests": _by_status("rejected"),
+ },
+ )
mcp = FastMCP("Approvals Server", providers=[app])
diff --git a/examples/apps/contacts/contacts_server.py b/examples/apps/contacts/contacts_server.py
index 39d225ef0..66c2ba597 100644
--- a/examples/apps/contacts/contacts_server.py
+++ b/examples/apps/contacts/contacts_server.py
@@ -17,7 +17,7 @@ from typing import Literal
from prefab_ui.actions import SetState, ShowToast
from prefab_ui.actions.mcp import CallTool
-from prefab_ui.app import PrefabApp, set_initial_state
+from prefab_ui.app import PrefabApp
from prefab_ui.components import (
Badge,
Button,
@@ -102,8 +102,6 @@ def list_contacts() -> list[dict]:
@app.ui()
def contact_manager() -> PrefabApp:
"""Open the contact manager. The model calls this to launch the app."""
- set_initial_state(contacts=list(_contacts))
-
with Column(gap=6, css_class="p-6") as view:
Heading("Contacts")
@@ -141,7 +139,7 @@ def contact_manager() -> PrefabApp:
Input(name="query", placeholder="Search by name or email...")
Button("Search")
- return PrefabApp(view=view)
+ return PrefabApp(view=view, state={"contacts": list(_contacts)})
mcp = FastMCP("Contacts Server", providers=[app])
diff --git a/examples/apps/explorer/explorer_server.py b/examples/apps/explorer/explorer_server.py
index b156e3393..41896f211 100644
--- a/examples/apps/explorer/explorer_server.py
+++ b/examples/apps/explorer/explorer_server.py
@@ -7,7 +7,7 @@ Demonstrates the full FastMCPApp stack:
- BarChart and PieChart for data visualization
- Metric cards for summary statistics
- Select-driven filtering with CallTool
-- State management with set_initial_state() and Rx()
+- State management with PrefabApp state dict and Rx()
Usage:
uv run python explorer_server.py # HTTP (default)
@@ -18,7 +18,7 @@ from __future__ import annotations
from prefab_ui.actions import SetState, ShowToast
from prefab_ui.actions.mcp import CallTool
-from prefab_ui.app import PrefabApp, set_initial_state
+from prefab_ui.app import PrefabApp
from prefab_ui.components import (
Badge,
Button,
@@ -40,7 +40,7 @@ from prefab_ui.components import (
Text,
)
from prefab_ui.components.charts import BarChart, ChartSeries, PieChart
-from prefab_ui.rx import ERROR, RESULT, STATE
+from prefab_ui.rx import ERROR, RESULT, STATE, Rx
from fastmcp import FastMCP, FastMCPApp
@@ -362,15 +362,6 @@ def data_explorer() -> PrefabApp:
"""Open the data explorer. Browse, filter, and visualize sales data."""
initial = analyze_data()
- state = set_initial_state(
- rows=initial["rows"],
- summary=initial["summary"],
- by_region=initial["by_region"],
- by_product=initial["by_product"],
- selected_region="All",
- selected_product="All",
- loading=False,
- )
with Column(gap=6, css_class="p-6") as view:
Heading("Sales Data Explorer")
@@ -443,8 +434,8 @@ def data_explorer() -> PrefabApp:
SelectOption(value=product, label=product)
Button(
- state.loading.then("Loading...", "Reset"),
- disabled=state.loading,
+ Rx("loading").then("Loading...", "Reset"),
+ disabled=Rx("loading"),
on_click=[
SetState("selected_region", "All"),
SetState("selected_product", "All"),
@@ -478,19 +469,19 @@ def data_explorer() -> PrefabApp:
with CardContent():
Metric(
label="Total Revenue",
- value=state.summary.total_amount,
+ value=Rx("summary.total_amount"),
)
with Card():
with CardContent():
Metric(
label="Average Sale",
- value=state.summary.avg_amount,
+ value=Rx("summary.avg_amount"),
)
with Card():
with CardContent():
Metric(
label="Total Quantity",
- value=state.summary.total_quantity,
+ value=Rx("summary.total_quantity"),
)
with Grid(columns=3, gap=4, css_class="mt-4"):
@@ -498,19 +489,19 @@ def data_explorer() -> PrefabApp:
with CardContent():
Metric(
label="Transactions",
- value=state.summary.count,
+ value=Rx("summary.count"),
)
with Card():
with CardContent():
Metric(
label="Min Sale",
- value=state.summary.min_amount,
+ value=Rx("summary.min_amount"),
)
with Card():
with CardContent():
Metric(
label="Max Sale",
- value=state.summary.max_amount,
+ value=Rx("summary.max_amount"),
)
with Row(gap=2, css_class="mt-4"):
@@ -541,7 +532,7 @@ def data_explorer() -> PrefabApp:
with Column(gap=2):
Heading("Revenue by Region", level=3)
BarChart(
- data=state.by_region,
+ data=Rx("by_region"),
series=[ChartSeries(data_key="amount", label="Revenue")],
x_axis="region",
show_legend=True,
@@ -550,7 +541,7 @@ def data_explorer() -> PrefabApp:
with Column(gap=2):
Heading("Revenue by Product", level=3)
BarChart(
- data=state.by_product,
+ data=Rx("by_product"),
series=[ChartSeries(data_key="amount", label="Revenue")],
x_axis="product",
show_legend=True,
@@ -562,7 +553,7 @@ def data_explorer() -> PrefabApp:
with Column(gap=2):
Heading("Region Breakdown", level=3)
PieChart(
- data=state.by_region,
+ data=Rx("by_region"),
data_key="amount",
name_key="region",
show_legend=True,
@@ -572,14 +563,25 @@ def data_explorer() -> PrefabApp:
with Column(gap=2):
Heading("Product Breakdown", level=3)
PieChart(
- data=state.by_product,
+ data=Rx("by_product"),
data_key="amount",
name_key="product",
show_legend=True,
inner_radius=60,
)
- return PrefabApp(view=view)
+ return PrefabApp(
+ view=view,
+ state={
+ "rows": initial["rows"],
+ "summary": initial["summary"],
+ "by_region": initial["by_region"],
+ "by_product": initial["by_product"],
+ "selected_region": "All",
+ "selected_product": "All",
+ "loading": False,
+ },
+ )
mcp = FastMCP("Data Explorer", providers=[app])
diff --git a/examples/apps/generative_ui.py b/examples/apps/generative_ui.py
new file mode 100644
index 000000000..e03f6ed85
--- /dev/null
+++ b/examples/apps/generative_ui.py
@@ -0,0 +1,22 @@
+"""Generative UI β€” let the LLM build custom Prefab UIs on the fly.
+
+The GenerativeUI provider registers two tools:
+- generate_prefab_ui: the LLM writes Prefab Python code, it runs in a sandbox, the result renders
+- search_prefab_components: the LLM searches the Prefab component library
+
+The generative renderer supports streaming: as the LLM writes code into
+the `code` argument, the host forwards partial arguments to the app via
+ontoolinputpartial, and the user watches the UI build up in real time.
+
+Usage:
+ uv run python generative_ui.py
+"""
+
+from fastmcp import FastMCP
+from fastmcp.apps.generative import GenerativeUI
+
+mcp = FastMCP("Prefab Studio")
+mcp.add_provider(GenerativeUI())
+
+if __name__ == "__main__":
+ mcp.run()
diff --git a/examples/apps/inventory/inventory_server.py b/examples/apps/inventory/inventory_server.py
index d0ce358af..f00862006 100644
--- a/examples/apps/inventory/inventory_server.py
+++ b/examples/apps/inventory/inventory_server.py
@@ -6,7 +6,7 @@ Demonstrates the full FastMCPApp stack:
- DataTable with sortable columns and built-in search
- Form.from_model() for auto-generated Pydantic model forms
- Tabs, Select filtering, ForEach results, and Toast notifications
-- State management with set_initial_state() and Rx()
+- State management with PrefabApp state dict and Rx()
Usage:
uv run python inventory_server.py # HTTP (default)
@@ -20,7 +20,7 @@ from typing import Literal
from prefab_ui.actions import SetState, ShowToast
from prefab_ui.actions.mcp import CallTool
-from prefab_ui.app import PrefabApp, set_initial_state
+from prefab_ui.app import PrefabApp
from prefab_ui.components import (
Badge,
Button,
@@ -385,16 +385,6 @@ def _build_actions_section() -> None:
@app.ui()
def inventory_manager() -> PrefabApp:
"""Open the inventory manager. The model calls this to launch the app."""
- set_initial_state(
- search_results=[],
- filtered_items=list(_inventory),
- recent_additions=[],
- selected_category="All",
- adjust_id="",
- delete_id="",
- query="",
- )
-
with Column(gap=6, css_class="p-6") as view:
with Row(gap=3, align="center"):
Heading("Inventory Tracker")
@@ -431,7 +421,18 @@ def inventory_manager() -> PrefabApp:
with Tab("Actions"):
_build_actions_section()
- return PrefabApp(view=view)
+ return PrefabApp(
+ view=view,
+ state={
+ "search_results": [],
+ "filtered_items": list(_inventory),
+ "recent_additions": [],
+ "selected_category": "All",
+ "adjust_id": "",
+ "delete_id": "",
+ "query": "",
+ },
+ )
# ---------------------------------------------------------------------------
diff --git a/examples/apps/patterns_server.py b/examples/apps/patterns_server.py
index 7e15b3bb9..abf888c1c 100644
--- a/examples/apps/patterns_server.py
+++ b/examples/apps/patterns_server.py
@@ -13,7 +13,7 @@ from __future__ import annotations
from prefab_ui.actions import ShowToast
from prefab_ui.actions.mcp import CallTool
-from prefab_ui.app import PrefabApp, set_initial_state
+from prefab_ui.app import PrefabApp
from prefab_ui.components import (
Accordion,
AccordionItem,
@@ -43,7 +43,7 @@ from prefab_ui.components import (
Textarea,
)
from prefab_ui.components.charts import AreaChart, BarChart, ChartSeries, PieChart
-from prefab_ui.rx import ERROR
+from prefab_ui.rx import ERROR, Rx
from fastmcp import FastMCP
@@ -311,8 +311,6 @@ def employee_directory() -> PrefabApp:
@mcp.tool(app=True)
def contact_form() -> PrefabApp:
"""Show a form to create a new contact, with a live contact list below."""
- set_initial_state(contacts=list(_contacts))
-
with Column(gap=6, css_class="p-6") as view:
Heading("Contacts")
@@ -343,7 +341,7 @@ def contact_form() -> PrefabApp:
Textarea(name="notes", label="Notes", placeholder="Optional notes...")
Button("Save Contact")
- return PrefabApp(view=view)
+ return PrefabApp(view=view, state={"contacts": list(_contacts)})
@mcp.tool
@@ -403,8 +401,6 @@ def system_status() -> PrefabApp:
@mcp.tool(app=True)
def feature_flags() -> PrefabApp:
"""Toggle feature flags with live preview."""
- state = set_initial_state(dark_mode=False, beta_features=False)
-
with Column(gap=4, css_class="p-6") as view:
Heading("Feature Flags")
@@ -413,16 +409,16 @@ def feature_flags() -> PrefabApp:
Separator()
- with If(state.dark_mode):
+ with If(Rx("dark_mode")):
Alert(title="Dark mode enabled", description="UI will use dark theme.")
- with If(state.beta_features):
+ with If(Rx("beta_features")):
Alert(
title="Beta features active",
description="Experimental features are now visible.",
variant="warning",
)
- return PrefabApp(view=view)
+ return PrefabApp(view=view, state={"dark_mode": False, "beta_features": False})
# ---------------------------------------------------------------------------
@@ -433,8 +429,6 @@ def feature_flags() -> PrefabApp:
@mcp.tool(app=True)
def project_overview() -> PrefabApp:
"""Show project details organized in tabs."""
- set_initial_state(activity=PROJECT["activity"])
-
with Column(gap=4, css_class="p-6") as view:
Heading(PROJECT["name"])
@@ -460,7 +454,7 @@ def project_overview() -> PrefabApp:
Muted(item.timestamp)
Text(item.message)
- return PrefabApp(view=view)
+ return PrefabApp(view=view, state={"activity": PROJECT["activity"]})
# ---------------------------------------------------------------------------
diff --git a/pyproject.toml b/pyproject.toml
index 0c58949f2..034d52134 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -53,7 +53,7 @@ classifiers = [
[project.optional-dependencies]
anthropic = ["anthropic>=0.48.0"]
-apps = ["prefab-ui>=0.13.0"]
+apps = ["prefab-ui>=0.14.0"]
# PyJWT floor: transitive via msal; CVE-2026-32597 affects <= 2.11.0
azure = ["azure-identity>=1.16.0", "PyJWT>=2.12.0"]
code-mode = ["pydantic-monty==0.0.8"]
diff --git a/src/fastmcp/apps/generative.py b/src/fastmcp/apps/generative.py
new file mode 100644
index 000000000..b3cbe3c33
--- /dev/null
+++ b/src/fastmcp/apps/generative.py
@@ -0,0 +1,199 @@
+"""GenerativeUI β€” a Provider that adds LLM-generated UI capabilities.
+
+Registers tools and resources from ``prefab_ui.generative`` so that an
+LLM can write Prefab Python code, execute it in a sandbox, and render
+the result as a streaming interactive UI.
+
+Requires ``fastmcp[apps]`` (prefab-ui).
+
+Usage::
+
+ from fastmcp import FastMCP
+ from fastmcp.apps.generative import GenerativeUI
+
+ mcp = FastMCP("My Server")
+ mcp.add_provider(GenerativeUI())
+"""
+
+try:
+ import prefab_ui.generative as _gen
+ from prefab_ui.renderer import (
+ get_generative_renderer_csp,
+ get_generative_renderer_html,
+ )
+except ImportError as _exc:
+ raise ImportError(
+ "GenerativeUI requires prefab-ui. Install with: pip install 'fastmcp[apps]'"
+ ) from _exc
+
+import json
+from collections.abc import AsyncIterator, Sequence
+from contextlib import asynccontextmanager
+from typing import Any
+
+from fastmcp.apps.config import AppConfig, ResourceCSP, app_config_to_meta_dict
+from fastmcp.server.providers.base import Provider
+from fastmcp.server.providers.local_provider import LocalProvider
+from fastmcp.tools.base import Tool
+from fastmcp.utilities.logging import get_logger
+from fastmcp.utilities.mime import UI_MIME_TYPE
+
+logger = get_logger(__name__)
+
+
+def _build_csp() -> ResourceCSP:
+ """Build CSP from the generative renderer's declared requirements."""
+ csp = get_generative_renderer_csp()
+ return ResourceCSP(
+ resource_domains=csp.get("resource_domains"),
+ connect_domains=csp.get("connect_domains"),
+ )
+
+
+class GenerativeUI(Provider):
+ """A Provider that adds generative UI capabilities to a server.
+
+ Registers:
+
+ - A ``generate_ui`` tool that accepts Prefab Python code, executes
+ it in a Pyodide sandbox, and returns the rendered PrefabApp.
+ Supports streaming via ``ontoolinputpartial``.
+ - A ``components`` tool that searches the Prefab component library.
+ - The generative renderer resource with CSP for Pyodide CDN access.
+
+ Example::
+
+ from fastmcp import FastMCP
+ from fastmcp.apps.generative import GenerativeUI
+
+ mcp = FastMCP("My Server")
+ mcp.add_provider(GenerativeUI())
+ """
+
+ def __init__(
+ self,
+ *,
+ tool_name: str = "generate_prefab_ui",
+ include_components_tool: bool = True,
+ components_tool_name: str = "search_prefab_components",
+ ) -> None:
+ super().__init__()
+ self._tool_name = tool_name
+ self._components_tool_name = components_tool_name
+ self._include_components_tool = include_components_tool
+ self._local = LocalProvider(on_duplicate="error")
+ self._sandbox: Any = None
+ self._setup_done = False
+
+ def __repr__(self) -> str:
+ return f"GenerativeUI(tool_name={self._tool_name!r})"
+
+ def _get_sandbox(self) -> Any:
+ """Lazily create the Pyodide sandbox."""
+ if self._sandbox is None:
+ from prefab_ui.sandbox import Sandbox
+
+ self._sandbox = Sandbox()
+ return self._sandbox
+
+ def _ensure_setup(self) -> None:
+ """Lazily register tools and resources on first access."""
+ if self._setup_done:
+ return
+
+ csp = _build_csp()
+ app_config = AppConfig(resource_uri=_gen.RESOURCE_URI, csp=csp)
+
+ # -- generate_ui tool --
+ # Wraps prefab_ui.generative.execute with sandbox lifecycle management.
+
+ from prefab_ui.app import PrefabApp
+
+ sandbox_ref = self # capture for closure
+
+ async def generate_ui(
+ code: str,
+ data: str | dict[str, Any] | None = None,
+ ) -> PrefabApp:
+ parsed_data: dict[str, Any] | None
+ if isinstance(data, str):
+ parsed_data = json.loads(data) if data.strip() else None
+ else:
+ parsed_data = data
+ return await _gen.execute(
+ code,
+ data=parsed_data,
+ sandbox=sandbox_ref._get_sandbox(),
+ )
+
+ tool = Tool.from_function(
+ generate_ui,
+ name=self._tool_name,
+ description=_gen.execute.__doc__ or "",
+ meta={"ui": app_config_to_meta_dict(app_config)},
+ )
+ self._local._add_component(tool)
+
+ # -- components tool --
+
+ if self._include_components_tool:
+ components_tool = Tool.from_function(
+ _gen.search_components,
+ name=self._components_tool_name,
+ description=_gen.search_components.__doc__ or "",
+ )
+ self._local._add_component(components_tool)
+
+ # -- generative renderer resource --
+
+ from fastmcp.resources.types import TextResource
+
+ resource_config = AppConfig(csp=csp)
+ resource = TextResource(
+ uri=_gen.RESOURCE_URI, # type: ignore[arg-type] # ty:ignore[invalid-argument-type]
+ name="Prefab Generative Renderer",
+ text=get_generative_renderer_html(),
+ mime_type=UI_MIME_TYPE,
+ meta={"ui": app_config_to_meta_dict(resource_config)},
+ )
+ self._local._add_component(resource)
+
+ self._setup_done = True
+
+ # ------------------------------------------------------------------
+ # Provider interface
+ # ------------------------------------------------------------------
+
+ async def _list_tools(self) -> Sequence[Tool]:
+ self._ensure_setup()
+ return await self._local._list_tools()
+
+ async def _get_tool(self, name: str, version: Any = None) -> Tool | None:
+ self._ensure_setup()
+ return await self._local._get_tool(name, version)
+
+ async def _list_resources(self) -> Sequence[Any]:
+ self._ensure_setup()
+ return await self._local._list_resources()
+
+ async def _get_resource(self, uri: str, version: Any = None) -> Any | None:
+ self._ensure_setup()
+ return await self._local._get_resource(uri, version)
+
+ async def _list_resource_templates(self) -> Sequence[Any]:
+ return []
+
+ async def _get_resource_template(self, uri: str, version: Any = None) -> Any | None:
+ return None
+
+ async def _list_prompts(self) -> Sequence[Any]:
+ return []
+
+ async def _get_prompt(self, name: str, version: Any = None) -> Any | None:
+ return None
+
+ @asynccontextmanager
+ async def lifespan(self) -> AsyncIterator[None]:
+ self._ensure_setup()
+ async with self._local.lifespan():
+ yield
diff --git a/tests/test_apps_prefab.py b/tests/test_apps_prefab.py
index d848f4194..8db9a2a97 100644
--- a/tests/test_apps_prefab.py
+++ b/tests/test_apps_prefab.py
@@ -39,9 +39,13 @@ class TestConvertResult:
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "[Rendered Prefab UI]"
assert result.structured_content is not None
- assert result.structured_content["version"] == "0.2"
+ assert result.structured_content["$prefab"]["version"] == "0.2"
assert result.structured_content["state"] == {"name": "Alice"}
- assert result.structured_content["view"]["type"] == "Column"
+ # PrefabApp wraps view in a pf-app-root Div
+ root = result.structured_content["view"]
+ assert root["type"] == "Div"
+ assert root["cssClass"] == "pf-app-root"
+ assert root["children"][0]["type"] == "Column"
def test_bare_component(self):
heading = Heading("World")
@@ -51,8 +55,9 @@ class TestConvertResult:
assert isinstance(result, ToolResult)
assert result.structured_content is not None
- assert result.structured_content["version"] == "0.2"
- assert result.structured_content["view"]["type"] == "Heading"
+ assert result.structured_content["$prefab"]["version"] == "0.2"
+ assert result.structured_content["view"]["type"] == "Div"
+ assert result.structured_content["view"]["children"][0]["type"] == "Heading"
def test_tool_result_with_prefab_structured_content(self):
"""ToolResult with PrefabApp as structured_content preserves custom text."""
@@ -66,8 +71,9 @@ class TestConvertResult:
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "Custom fallback text"
assert result.structured_content is not None
- assert result.structured_content["version"] == "0.2"
- assert result.structured_content["view"]["type"] == "Heading"
+ assert result.structured_content["$prefab"]["version"] == "0.2"
+ assert result.structured_content["view"]["type"] == "Div"
+ assert result.structured_content["view"]["children"][0]["type"] == "Heading"
def test_tool_result_with_component_structured_content(self):
"""ToolResult with bare Component as structured_content."""
@@ -79,8 +85,9 @@ class TestConvertResult:
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "My text"
assert result.structured_content is not None
- assert result.structured_content["version"] == "0.2"
- assert result.structured_content["view"]["type"] == "Heading"
+ assert result.structured_content["$prefab"]["version"] == "0.2"
+ assert result.structured_content["view"]["type"] == "Div"
+ assert result.structured_content["view"]["children"][0]["type"] == "Heading"
def test_tool_result_passthrough(self):
"""ToolResult without prefab structured_content passes through unchanged."""
@@ -378,7 +385,7 @@ class TestIntegration:
result = await client.call_tool("greet", {"name": "Alice"})
assert result.structured_content is not None
- assert result.structured_content["version"] == "0.2"
+ assert result.structured_content["$prefab"]["version"] == "0.2"
assert result.structured_content["state"] == {"name": "Alice"}
async def test_tool_call_with_custom_text(self):
@@ -399,7 +406,7 @@ class TestIntegration:
"Greeting for Alice" in c.text for c in result.content if hasattr(c, "text")
)
assert result.structured_content is not None
- assert result.structured_content["version"] == "0.2"
+ assert result.structured_content["$prefab"]["version"] == "0.2"
async def test_tools_list_includes_app_meta(self):
mcp = FastMCP("test")
diff --git a/uv.lock b/uv.lock
index fd3fa1ff8..94fc36233 100644
--- a/uv.lock
+++ b/uv.lock
@@ -878,7 +878,7 @@ requires-dist = [
{ name = "opentelemetry-api", specifier = ">=1.20.0" },
{ name = "packaging", specifier = ">=24.0" },
{ name = "platformdirs", specifier = ">=4.0.0" },
- { name = "prefab-ui", marker = "extra == 'apps'", specifier = ">=0.13.0" },
+ { name = "prefab-ui", marker = "extra == 'apps'", specifier = ">=0.14.0" },
{ name = "py-key-value-aio", extras = ["filetree", "keyring", "memory"], specifier = ">=0.4.4,<0.5.0" },
{ name = "pydantic", extras = ["email"], specifier = ">=2.11.7" },
{ name = "pydantic-monty", marker = "extra == 'code-mode'", specifier = "==0.0.8" },
@@ -1811,16 +1811,15 @@ wheels = [
[[package]]
name = "prefab-ui"
-version = "0.13.1"
+version = "0.14.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "cyclopts" },
{ name = "pydantic" },
{ name = "rich" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/6e/93/c475023195145a0812935a3c022185018e2808723348a5e8071aa1d4b2fb/prefab_ui-0.13.1.tar.gz", hash = "sha256:15f4b94c6120c723409decff00a9a46860ef0d794b6772f25c8268643465e0b0", size = 3018799, upload-time = "2026-03-22T14:28:02.691Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/d2/22/51dee417a7fcd9dcfe01101b790865965e0477c040f7b4b447c40086c658/prefab_ui-0.13.1-py3-none-any.whl", hash = "sha256:3d4965f4196ea34ded4e73688156ff6bdcf76ff235c77ad33b2956acfcf0492d", size = 888548, upload-time = "2026-03-22T14:28:01.047Z" },
+ { url = "https://files.pythonhosted.org/packages/58/75/a6534b16b7a6a7fbf7afd1901e0c25ead55f33d30c37d494c4e9ea9f2f24/prefab_ui-0.14.0-py3-none-any.whl", hash = "sha256:034a0df692a617a9361b7f88fcfff667bc56eb8f03ace46c46402269c1a8f018", size = 1741233, upload-time = "2026-03-27T02:36:03.86Z" },
]
[[package]]