fastmcp/examples/apps/approvals/approvals_server.py
Jeremiah Lowin 3a9717e6be
Publish docs for v3.2.0 (#3713)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Jeremiah Lowin <jlowin@users.noreply.github.com>
Co-authored-by: Marvin Context Protocol <41898282+Marvin Context Protocol@users.noreply.github.com>
Co-authored-by: voidborne-d <voidborne-d@users.noreply.github.com>
Co-authored-by: marvin-context-protocol[bot] <225465937+marvin-context-protocol[bot]@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: d 🔹 <258577966+voidborne-d@users.noreply.github.com>
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
Co-authored-by: nightcityblade <nightcityblade@gmail.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Bill Easton <strawgate@users.noreply.github.com>
Co-authored-by: Sumanshu Nankana <sumanshunankana@gmail.com>
Co-authored-by: Eric Robinson <ericrobinson@indeed.com>
Co-authored-by: Martim Santos <martimfasantos@gmail.com>
Co-authored-by: d 🔹 <liusway405@gmail.com>
Co-authored-by: Matthieu B <66959271+mtthidoteu@users.noreply.github.com>
Co-authored-by: Sascha Buehrle <47737812+saschabuehrle@users.noreply.github.com>
Co-authored-by: Hakancan <142545736+hkc5@users.noreply.github.com>
Co-authored-by: nightcityblade <jackchen@haloailabs.com>
Co-authored-by: Matt Hallowell <17804673+mhallo@users.noreply.github.com>
Co-authored-by: nate nowack <thrast36@gmail.com>
Co-authored-by: Bill Easton <williamseaston@gmail.com>
Co-authored-by: Marcus Shu <46469249+shulkx@users.noreply.github.com>
Co-authored-by: Rushabh Doshi <radoshi@gmail.com>
Co-authored-by: AIKAWA Shigechika <shige@aikawa.jp>
Co-authored-by: Jeremy Simon <simonjer805@gmail.com>
Co-authored-by: Miguel Miranda Dias <7780875+pandego@users.noreply.github.com>
Co-authored-by: Anthony James Padavano <padavano.anthony@gmail.com>
Co-authored-by: Mostafa Kamal <hiremostafa@gmail.com>
Fix auto-close MRE script posting comment without closing (#3386)
Fix WorkOS token scope verification bypass 🤖 Generated with Codex (#3407)
Fix initialize McpError fallthrough 🤖 Generated with Codex (#3413)
Fix transform arg collisions with passthrough params (#3431)
Fix get_* returning None when latest version is disabled (#3439)
Fix get_* returning None when latest version is disabled (#3421)
Fix server lifespan overlap teardown (#3415)
Fix $ref output schema object detection regression (#3420)
resolved annotations (#3429)
Fix async partial callables rejected by iscoroutinefunction (#3438)
Fix async partial callables rejected by iscoroutinefunction (#3423)
fix: add version to components (#3458)
fix: use intent-based flag for OIDC scope patch in load_access_token (#3465)
Fixes #3461
fix: normalize Google scope shorthands and surface valid_scopes (#3477)
fix: resolve ty 0.0.23 type-checking errors and bump pin (#3481)
fix: shield lifespan teardown from cancellation (#3480)
fix: forward custom_route endpoints from mounted servers (#3462)
fix updates _get_additional_http_routes() to traverse providers,
Fixes #3457
fix: remove hardcoded version from CLI help text (#3456)
fix: monty 0.0.8 compatibility, drop external_functions from constructor (#3468)
fix: task test teardown hanging 5s per test (#3499)
Closes #3498
fix: validate workspace path is a directory before cursor install (#3440)
Fixes #3426
fix: handle re.error from malformed URI templates in build_regex (#3501)
fix: reject empty/OIDC-only required_scopes in AzureProvider (#3503)
fix: restrict $ref resolution to local refs only (SSRF/LFI) (#3502)
fix warnings and timeouts (#3504)
close upgrade check issue when build passes (#3505)
Closes #3484
fix: URL-encode path params to prevent SSRF/path traversal (GHSA-vv7q-7jx5-f767) (#3507)
fix: prevent path traversal in skill download (#3493)
fix: prefer IdP-granted scopes over client-requested scopes in OAuthProxy (#3492)
fix: remove unrelated transform and http.py changes from PR scope
fix: remove forced follow_redirects from httpx_client_factory calls (#3496)
fix: stop passing follow_redirects to httpx_client_factory
fix: restore follow_redirects=True for custom httpx client factories
Closes #3509
fix: CSRF double-submit cookie check in consent flow (#3519)
fix: validate server names in install commands (#3522)
fix: use raw strings for regex in pytest.raises match (#3523)
fix: reject refresh tokens used as Bearer access tokens (#3524)
fix: route ResourcesAsTools/PromptsAsTools through server middleware (#3495)
fix: resolve Pyright "Module is not callable" on @tool, @resource, @prompt decorators (#3540)
fix: filter warnings by message in KEY_PREFIX test (#3549)
fix: suppress output schema for ToolResult subclass annotations (#3548)
fix: increase sleep duration in proxy cache tests (#3567)
fix: store absolute token expiry to prevent stale expires_in on reload (#3572)
fix: preserve tool properties named 'title' during schema compression (#3582)
Fix loopback redirect URI port matching per RFC 8252 §7.3 (#3589)
Fix app tool routing: visibility check and middleware propagation (#3591)
Fix query parameter serialization to respect OpenAPI explode/style settings (#3595)
Fix dev apps form: union types, textarea support, JSON parsing (#3597)
fix(google): replace deprecated /oauth2/v1/tokeninfo with /oauth2/v3/userinfo (#3603)
fix: resolve EntraOBOToken dependency injection through MultiAuth (#3609)
fix(docs): correct misleading stateless_http header (#3622)
fix: filesystem provider import machinery (#3626)
Closes #3625 (issues 2, 3, 6)
fix: recover StdioTransport after subprocess exits (#3630)
fix(server): preserve mounted tool task metadata (#3632)
fix: scope deprecation warning filter to FastMCPDeprecationWarning (#3649)
fix imports, add PrefabAppConfig (#3650)
fix: resolve CurrentFastMCP/ctx.fastmcp to child server in mounted background tasks (#3651)
Fix blocking docs issues: chart imports, Select API, Rx consistency (#3652)
closed by default (#3657)
Fix prompt caching middleware missing wrap/unwrap round-trip (#3666)
fix: serialize object query params per OpenAPI style/explode rules (#3662)
Fixes #2857
fix: HTTP request headers not accessible in background task workers (#3631)
fix: restore HTTP headers in worker execution path for background tasks (#3681)
fix: strip discriminator after dereferencing schemas (#3682)
fix: remove stale ty:ignore directives for ty 0.0.26 (#3684)
Fix docs gaps in app provider pages (#3690)
fix: dev apps log panel UX improvements (#3698)
fix dev server empty string args (#3700)
2026-03-30 16:48:30 -04:00

333 lines
11 KiB
Python

"""Approval workflow — a FastMCPApp example with tabs, status badges, and action chaining.
Demonstrates a multi-step interactive workflow:
- @app.ui() entry point showing a pending approvals dashboard
- @app.tool() backend tools that the UI calls via CallTool
- @app.tool(model=True) for tools accessible from both model and UI
- Tabs with filtered lists and counter badges
- Action chaining: approve → update state → show toast
Usage:
uv run python approvals_server.py
"""
from __future__ import annotations
from prefab_ui.actions import SetState, ShowToast
from prefab_ui.actions.mcp import CallTool
from prefab_ui.app import PrefabApp
from prefab_ui.components import (
Badge,
Button,
Card,
CardContent,
CardHeader,
CardTitle,
Column,
ForEach,
Heading,
If,
Muted,
Row,
Separator,
Tab,
Tabs,
Text,
)
from prefab_ui.rx import ERROR, RESULT, Rx
from fastmcp import FastMCP, FastMCPApp
# ---------------------------------------------------------------------------
# Data
# ---------------------------------------------------------------------------
_requests: list[dict] = [
{
"id": "REQ-001",
"type": "expense",
"title": "Client dinner — Acme Corp",
"submitter": "Alice Chen",
"description": "Business dinner with Acme Corp stakeholders to discuss Q3 partnership.",
"amount": 284.50,
"status": "pending",
"created_at": "2026-03-18",
},
{
"id": "REQ-002",
"type": "access",
"title": "Production database read access",
"submitter": "Bob Martinez",
"description": "Need read access to prod DB for quarterly analytics report.",
"amount": None,
"status": "pending",
"created_at": "2026-03-19",
},
{
"id": "REQ-003",
"type": "time_off",
"title": "Vacation — Apr 7-11",
"submitter": "Carol Johnson",
"description": "Family vacation, all deliverables handed off to David.",
"amount": None,
"status": "approved",
"created_at": "2026-03-15",
},
{
"id": "REQ-004",
"type": "expense",
"title": "Conference registration — PyCon 2026",
"submitter": "David Kim",
"description": "PyCon US 2026 early-bird registration plus tutorial day.",
"amount": 650.00,
"status": "pending",
"created_at": "2026-03-20",
},
{
"id": "REQ-005",
"type": "access",
"title": "AWS staging account access",
"submitter": "Eva Mueller",
"description": "Staging environment access for load testing new API endpoints.",
"amount": None,
"status": "rejected",
"created_at": "2026-03-14",
},
{
"id": "REQ-006",
"type": "expense",
"title": "Team offsite lunch",
"submitter": "Frank Okafor",
"description": "Catering for 12-person engineering offsite planning session.",
"amount": 420.00,
"status": "pending",
"created_at": "2026-03-21",
},
{
"id": "REQ-007",
"type": "time_off",
"title": "Personal day — Mar 28",
"submitter": "Grace Liu",
"description": "Personal appointment, will be available on Slack for emergencies.",
"amount": None,
"status": "pending",
"created_at": "2026-03-20",
},
{
"id": "REQ-008",
"type": "expense",
"title": "Software license — Figma annual",
"submitter": "Hassan Ali",
"description": "Annual Figma Professional license renewal for design team.",
"amount": 144.00,
"status": "approved",
"created_at": "2026-03-12",
},
]
def _by_status(status: str) -> list[dict]:
return [r for r in _requests if r["status"] == status]
def _find_request(request_id: str) -> dict | None:
for r in _requests:
if r["id"] == request_id:
return r
return None
# ---------------------------------------------------------------------------
# App
# ---------------------------------------------------------------------------
app = FastMCPApp("Approvals")
def _all_lists() -> dict[str, list[dict]]:
"""Return state updates for all three status lists."""
return {
"pending_requests": _by_status("pending"),
"approved_requests": _by_status("approved"),
"rejected_requests": _by_status("rejected"),
}
@app.tool()
def approve_request(request_id: str) -> dict[str, list[dict]]:
"""Approve a pending request and return updated lists."""
req = _find_request(request_id)
if req is None:
raise ValueError(f"Request {request_id} not found")
if req["status"] != "pending":
raise ValueError(f"Request {request_id} is already {req['status']}")
req["status"] = "approved"
return _all_lists()
@app.tool()
def reject_request(request_id: str) -> dict[str, list[dict]]:
"""Reject a pending request and return updated lists."""
req = _find_request(request_id)
if req is None:
raise ValueError(f"Request {request_id} not found")
if req["status"] != "pending":
raise ValueError(f"Request {request_id} is already {req['status']}")
req["status"] = "rejected"
return _all_lists()
@app.tool()
def add_comment(request_id: str, comment: str) -> dict:
"""Add a comment to a request. Returns the updated request."""
req = _find_request(request_id)
if req is None:
raise ValueError(f"Request {request_id} not found")
comments = req.setdefault("comments", [])
comments.append(comment)
return req
@app.tool(model=True)
def get_request_details(request_id: str) -> dict:
"""Get full details for a single request. Available to both model and UI."""
req = _find_request(request_id)
if req is None:
raise ValueError(f"Request {request_id} not found")
return req
@app.tool()
def list_requests(status: str | None = None) -> list[dict]:
"""List requests, optionally filtered by status."""
if status is not None:
return _by_status(status)
return list(_requests)
def _update_all_lists() -> list:
"""Actions to update all three status lists from a tool result."""
return [
SetState("pending_requests", RESULT.pending_requests),
SetState("approved_requests", RESULT.approved_requests),
SetState("rejected_requests", RESULT.rejected_requests),
]
def _build_request_card(
item: Rx,
*,
status_variant: str = "warning",
show_actions: bool = False,
) -> None:
"""Build a card for a single request inside a ForEach context."""
request_id = str(item.id)
with Card():
with CardHeader():
with Row(gap=2, align="center", justify="between"):
CardTitle(item.title)
Badge(item.status, variant=status_variant)
with CardContent(css_class="space-y-2"):
with Row(gap=2, align="center"):
Badge(item.type, variant="secondary")
Text(item.submitter, css_class="font-medium")
Muted(item.created_at)
with If(item.amount):
Text(item.amount.currency(), css_class="text-lg font-semibold")
Muted(item.description)
if show_actions:
Separator()
with Row(gap=2):
Button(
"Approve",
variant="default",
on_click=CallTool(
approve_request,
arguments={"request_id": request_id},
on_success=_update_all_lists()
+ [
ShowToast(
"Request approved",
variant="success",
),
],
on_error=ShowToast(
ERROR,
variant="error",
),
),
)
Button(
"Reject",
variant="destructive",
on_click=CallTool(
reject_request,
arguments={"request_id": request_id},
on_success=_update_all_lists()
+ [
ShowToast(
"Request rejected",
variant="warning",
),
],
on_error=ShowToast(
ERROR,
variant="error",
),
),
)
@app.ui()
def approval_dashboard() -> PrefabApp:
"""Open the approval dashboard. The model calls this to launch the app."""
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"):
Heading("Approval Dashboard")
Badge(pending_count, variant="warning")
Muted("pending")
with Tabs(value="pending"):
with Tab(title="Pending"):
with If(pending_count):
with ForEach("pending_requests") as item:
_build_request_card(item, show_actions=True)
with If(~pending_count):
Muted("No pending requests.")
with Tab(title="Approved"):
with If(approved_count):
with ForEach("approved_requests") as item:
_build_request_card(item, status_variant="success")
with If(~approved_count):
Muted("No approved requests.")
with Tab(title="Rejected"):
with If(rejected_count):
with ForEach("rejected_requests") as item:
_build_request_card(item, status_variant="destructive")
with If(~rejected_count):
Muted("No rejected requests.")
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])
if __name__ == "__main__":
mcp.run(transport="http")