π The fast, Pythonic way to build MCP servers and clients.
Add FormInput provider, bump prefab-ui to 0.15.0 (#3687)
Jeremiah Lowin2c08edecec98
diff --git a/docs/apps/images/app-form.png b/docs/apps/images/app-form.pngnew file mode 100644index 000000000..30567e37eBinary files /dev/null and b/docs/apps/images/app-form.png differdiff --git a/docs/apps/providers/form.mdx b/docs/apps/providers/form.mdxnew file mode 100644index 000000000..ea8aa8a8d--- /dev/null+++ b/docs/apps/providers/form.mdx@@ -0,0 +1,103 @@+---+title: Form Input+sidebarTitle: Form Input+description: Collect structured data from users via Pydantic models+icon: rectangle-list+tag: NEW+---++import { VersionBadge } from '/snippets/version-badge.mdx'++<VersionBadge version="3.2.0" />++`FormInput` generates a validated form from a Pydantic model. The user fills it out, and the submission is validated against the model before being returned. Structured elicitation that can't be hallucinated.++<Frame>+ <img src="/apps/images/app-form.png" alt="The FormInput provider shown in Goose, with a bug report form" />+</Frame>++```python+from pydantic import BaseModel, Field+from fastmcp import FastMCP+from fastmcp.apps.form import FormInput++class BugReport(BaseModel):+ title: str = Field(description="Brief summary")+ severity: Literal["low", "medium", "high", "critical"]+ description: str = Field(+ description="Detailed description",+ json_schema_extra={"ui": {"type": "textarea"}},+ )++mcp = FastMCP("My Server")+mcp.add_provider(FormInput(model=BugReport))+```++This registers two tools:++| Tool | Visibility | Purpose |+|------|-----------|---------|+| `collect_bugreport` | Model | Opens the form UI |+| `submit_form` | App only | Validates and processes the submission |++The tool name is derived from the model: `collect_{ModelName.lower()}`. The LLM calls it with a prompt explaining what it needs, and the user gets a form with fields matching the model.++## Field Mapping++`FormInput` uses Prefab's `Form.from_model()`, which maps Pydantic types to form components:++| Python type | Form component |+|------------|---------------|+| `str` | Text input |+| `int`, `float` | Number input |+| `bool` | Checkbox |+| `datetime.date` | Date picker |+| `Literal[...]` | Select dropdown |+| `SecretStr` | Password input |++Use `Field()` metadata to control labels (`title`), placeholders (`description`), and validation (`min_length`, `max_length`, `ge`, `le`). Use `json_schema_extra={"ui": {"type": "textarea"}}` for multiline text.++## Callback++By default, the validated model is returned as JSON. Provide an `on_submit` callback to process the data server-side:++```python+def save_report(report: BugReport) -> str:+ db.insert(report.model_dump())+ return f"Bug #{db.last_id} filed: {report.title}"++mcp.add_provider(FormInput(model=BugReport, on_submit=save_report))+```++The callback receives a validated model instance and returns a string that becomes the tool result.++## Configuration++```python+FormInput(+ model=BugReport, # Required: the Pydantic model+ name="BugTracker", # App name (default: model name)+ title="File a Bug", # Card heading (default: model name)+ tool_name="file_bug", # Tool name (default: collect_{model})+ submit_text="Submit Report", # Button label (default: "Submit")+ on_submit=save_report, # Optional callback+ send_message=True, # Push result as a chat message+)+```++Set `send_message=True` to push the result back into the conversation via `SendMessage`, triggering the LLM's next turn. Without it, the result is just the tool return value.++## Multiple Forms++Add multiple providers for different models β each gets its own tool:++```python+mcp = FastMCP(+ "My Server",+ providers=[+ FormInput(model=ShippingAddress),+ FormInput(model=BugReport),+ FormInput(model=ContactInfo),+ ],+)+```diff --git a/docs/docs.json b/docs/docs.jsonindex 40988ad9e..37075f0c5 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -216,6 +216,7 @@"apps/providers/approval","apps/providers/choice","apps/providers/file-upload",+ "apps/providers/form","apps/providers/generative"],"tag": "NEW"diff --git a/examples/apps/form/form_server.py b/examples/apps/form/form_server.pynew file mode 100644index 000000000..bfa2ab27e--- /dev/null+++ b/examples/apps/form/form_server.py@@ -0,0 +1,41 @@+"""Form input β collect structured data from users via Pydantic models.++Usage:+ uv run python form_server.py+"""++from typing import Literal++from pydantic import BaseModel, Field++from fastmcp import FastMCP+from fastmcp.apps.form import FormInput+++class ShippingAddress(BaseModel):+ name: str = Field(description="Full name")+ street: str = Field(description="Street address")+ city: str+ state: str = Field(description="Two-letter state code")+ zip_code: str = Field(description="5-digit ZIP")+++class BugReport(BaseModel):+ title: str = Field(description="Brief summary")+ severity: Literal["low", "medium", "high", "critical"]+ description: str = Field(+ description="Detailed description",+ json_schema_extra={"ui": {"type": "textarea"}},+ )+++mcp = FastMCP(+ "Form Demo",+ providers=[+ FormInput(model=ShippingAddress),+ FormInput(model=BugReport),+ ],+)++if __name__ == "__main__":+ mcp.run()diff --git a/pyproject.toml b/pyproject.tomlindex 262dad985..f882748b6 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -53,7 +53,7 @@ classifiers = [[project.optional-dependencies]anthropic = ["anthropic>=0.48.0"]-apps = ["prefab-ui>=0.14.0"]+apps = ["prefab-ui>=0.15.0"]# PyJWT floor: transitive via msal; CVE-2026-32597 affects <= 2.11.0azure = ["azure-identity>=1.16.0", "PyJWT>=2.12.0"]code-mode = ["pydantic-monty==0.0.8"]diff --git a/src/fastmcp/apps/form.py b/src/fastmcp/apps/form.pynew file mode 100644index 000000000..1d6f67b5a--- /dev/null+++ b/src/fastmcp/apps/form.py@@ -0,0 +1,184 @@+"""FormInput β a Provider that collects structured input from the user.++Define a Pydantic model for the data you need, and ``FormInput``+generates a form UI. The user fills it out, the submission is+validated, and an optional callback processes the result.++Requires ``fastmcp[apps]`` (prefab-ui).++Usage::++ from pydantic import BaseModel+ from fastmcp import FastMCP+ from fastmcp.apps.form import FormInput++ class ShippingAddress(BaseModel):+ street: str+ city: str+ state: str+ zip_code: str++ mcp = FastMCP("My Server")+ mcp.add_provider(FormInput(model=ShippingAddress))+"""++from __future__ import annotations++import json+from collections.abc import Callable+from typing import Any++try:+ from prefab_ui.actions import SetState+ from prefab_ui.actions.mcp import CallTool, SendMessage+ from prefab_ui.app import PrefabApp+ from prefab_ui.components import (+ H3,+ Card,+ CardContent,+ CardFooter,+ CardHeader,+ Column,+ Form,+ Muted,+ )+ from prefab_ui.components.control_flow import If+ from prefab_ui.rx import RESULT, STATE+except ImportError as _exc:+ raise ImportError(+ "FormInput requires prefab-ui. Install with: pip install 'fastmcp[apps]'"+ ) from _exc++import pydantic++from fastmcp.apps.app import FastMCPApp+++class FormInput(FastMCPApp):+ """A Provider that collects structured input via a Pydantic model.++ Define a model for the data you need, and ``FormInput`` generates+ a form from it using ``Form.from_model()``. Field types, labels,+ descriptions, and validation are all derived from the model.++ Optionally provide an ``on_submit`` callback to process the+ validated data. The callback receives a model instance and returns+ a string that goes back to the LLM. Without a callback, the+ validated JSON is sent directly.++ Example::++ from pydantic import BaseModel+ from fastmcp import FastMCP+ from fastmcp.apps.form import FormInput++ class Contact(BaseModel):+ name: str+ email: str++ mcp = FastMCP("My Server")+ mcp.add_provider(FormInput(model=Contact))++ With a callback::++ def save_contact(contact: Contact) -> str:+ db.insert(contact.model_dump())+ return f"Saved {contact.name}"++ mcp.add_provider(FormInput(model=Contact, on_submit=save_contact))+ """++ def __init__(+ self,+ model: type[pydantic.BaseModel],+ *,+ name: str | None = None,+ title: str | None = None,+ submit_text: str = "Submit",+ tool_name: str | None = None,+ on_submit: Callable[..., str] | None = None,+ send_message: bool = False,+ ) -> None:+ app_name = name or model.__name__+ super().__init__(app_name)+ self._model = model+ self._title = title or model.__name__+ self._submit_text = submit_text+ self._tool_name = tool_name or f"collect_{model.__name__.lower()}"+ self._on_submit = on_submit+ self._send_message = send_message+ self._register_tools()++ def __repr__(self) -> str:+ return f"FormInput({self._model.__name__!r})"++ def _register_tools(self) -> None:+ provider = self+ model = self._model++ @self.tool()+ def submit_form(data: dict[str, Any]) -> str:+ """Validate and process form submission."""+ validated = model.model_validate(data)+ if provider._on_submit is not None:+ return provider._on_submit(validated)+ return json.dumps(validated.model_dump(mode="json"))++ @self.ui(+ name=provider._tool_name,+ description=(+ f"Collect {model.__name__} information from the user via a form. "+ f"Call this tool when you need the user to provide "+ f"{model.__name__} data. The user will see a validated form. "+ f"After calling this tool, STOP and wait for the user to submit."+ ),+ )+ def collect_input(+ prompt: str,+ title: str | None = None,+ submit_text: str | None = None,+ ) -> PrefabApp:+ """Collect structured input from the user.++ Args:+ prompt: Tell the user what you need and why.+ title: Optional heading for the form card.+ submit_text: Optional label for the submit button.+ """+ _title = title or provider._title+ _submit = submit_text or provider._submit_text++ with Card(css_class="max-w-lg mx-auto") as view:+ with CardHeader():+ H3(_title)++ with CardContent(), Column(gap=4):+ Muted(prompt)++ on_success_actions: list[Any] = [+ SetState("submitted", True),+ ]+ if provider._send_message:+ on_success_actions.insert(+ 0,+ SendMessage(RESULT), # ty:ignore[invalid-argument-type]+ )++ Form.from_model(+ model,+ submit_label=_submit,+ on_submit=[+ CallTool(+ "submit_form",+ on_success=on_success_actions,+ ),+ ],+ )++ with CardFooter(), If(STATE.submitted):+ Muted("Submitted.")++ return PrefabApp(+ view=view,+ state={"submitted": False},+ )diff --git a/tests/apps/test_form.py b/tests/apps/test_form.pynew file mode 100644index 000000000..d4db5fcd2--- /dev/null+++ b/tests/apps/test_form.py@@ -0,0 +1,101 @@+"""Tests for the FormInput provider."""++import json++import pydantic++from fastmcp import FastMCP+from fastmcp.apps.form import FormInput+++class Contact(pydantic.BaseModel):+ name: str+ email: str+ phone: str | None = None+++class TestFormInputProvider:+ async def test_collect_returns_structured_content(self):+ server = FastMCP("test", providers=[FormInput(model=Contact)])++ result = await server.call_tool(+ "collect_contact",+ {"prompt": "Enter your details"},+ )+ assert result.structured_content is not None++ async def test_tool_name_derived_from_model(self):+ server = FastMCP("test", providers=[FormInput(model=Contact)])++ tools = await server.list_tools()+ tool_names = [t.name for t in tools]+ assert "collect_contact" in tool_names++ async def test_custom_tool_name(self):+ server = FastMCP(+ "test",+ providers=[FormInput(model=Contact, tool_name="new_contact")],+ )++ tools = await server.list_tools()+ tool_names = [t.name for t in tools]+ assert "new_contact" in tool_names++ async def test_submit_validates_and_returns_json(self):+ server = FastMCP("test", providers=[FormInput(model=Contact)])++ result = await server.call_tool(+ "Contact___submit_form",+ {"data": {"name": "Alice", "email": "[email protected]"}},+ )+ text = result.content[0].text # type: ignore[union-attr] # ty:ignore[unresolved-attribute]+ parsed = json.loads(text)+ assert parsed["name"] == "Alice"+ assert parsed["email"] == "[email protected]"+ assert parsed["phone"] is None++ async def test_submit_with_callback(self):+ saved: list[Contact] = []++ def on_submit(contact: Contact) -> str:+ saved.append(contact)+ return f"Saved {contact.name}"++ server = FastMCP(+ "test",+ providers=[FormInput(model=Contact, on_submit=on_submit)],+ )++ result = await server.call_tool(+ "Contact___submit_form",+ {"data": {"name": "Bob", "email": "[email protected]"}},+ )+ text = result.content[0].text # type: ignore[union-attr] # ty:ignore[unresolved-attribute]+ assert "Saved Bob" in text+ assert len(saved) == 1+ assert saved[0].name == "Bob"++ async def test_backend_tool_hidden(self):+ server = FastMCP("test", providers=[FormInput(model=Contact)])++ tools = await server.list_tools()+ tool_names = [t.name for t in tools]+ assert "_submit_form" not in tool_names++ async def test_multiple_models(self):+ class Address(pydantic.BaseModel):+ street: str+ city: str++ server = FastMCP(+ "test",+ providers=[+ FormInput(model=Contact),+ FormInput(model=Address),+ ],+ )++ tools = await server.list_tools()+ tool_names = [t.name for t in tools]+ assert "collect_contact" in tool_names+ assert "collect_address" in tool_namesdiff --git a/uv.lock b/uv.lockindex 94a7be821..597c33d3a 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.14.0" },+ { name = "prefab-ui", marker = "extra == 'apps'", specifier = ">=0.15.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,16 @@ wheels = [[[package]]name = "prefab-ui"-version = "0.14.1"+version = "0.15.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "cyclopts" },{ name = "pydantic" },{ name = "rich" },]-sdist = { url = "https://files.pythonhosted.org/packages/99/23/8739e3bbb8e525167888341fdb53e7c2f9d58016dbc602fe93ff3a0635d3/prefab_ui-0.14.1.tar.gz", hash = "sha256:7e2f23ccc7b8b7c1fb9d972de3a672c24b41d531764fea82ef7502fb8ac256f2", size = 3897953, upload-time = "2026-03-27T18:56:42.839Z" }+sdist = { url = "https://files.pythonhosted.org/packages/ab/1a/f915a7b2b97392e723f3aaada7438e615cbf119bd01b78f8869dd24dbc33/prefab_ui-0.15.0.tar.gz", hash = "sha256:9fa6ef0b997a1322a7103daf92c340a3badb394ba8ea043249b247f27f65976d", size = 3202919, upload-time = "2026-03-29T00:59:23.185Z" }wheels = [- { url = "https://files.pythonhosted.org/packages/4c/4b/94891c521b06ed186e00e3b2fbc5b0b421ccf61af8e690722e546beba118/prefab_ui-0.14.1-py3-none-any.whl", hash = "sha256:a883fb9ddce9942dd0e1665d6b6c5dee6aab80ecf2447b30c3ab628ecbfcc304", size = 1741779, upload-time = "2026-03-27T18:56:44.261Z" },+ { url = "https://files.pythonhosted.org/packages/a1/d8/2a3d73a3efc50e5fb7fcbe4f6516943b9506f930b23362990bed30a921c7/prefab_ui-0.15.0-py3-none-any.whl", hash = "sha256:b8cd787332ab77b808bdc5f21b1305b0bd749c07f4bf1a97dba97302383850da", size = 1044677, upload-time = "2026-03-29T00:59:21.649Z" },][[package]]