fastmcp/examples/apps/explorer/explorer_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

590 lines
17 KiB
Python

"""Data explorer — a FastMCPApp example with tables, charts, and filtering.
Demonstrates the full FastMCPApp stack:
- @app.ui() entry point with a tabbed data exploration interface
- @app.tool() backend tools for analysis, summaries, and filtering
- DataTable with sorting, search, and pagination
- BarChart and PieChart for data visualization
- Metric cards for summary statistics
- Select-driven filtering with CallTool
- State management with PrefabApp state dict and Rx()
Usage:
uv run python explorer_server.py # HTTP (default)
uv run python explorer_server.py --stdio # stdio for MCP clients
"""
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,
Column,
DataTable,
DataTableColumn,
Grid,
Heading,
Metric,
Muted,
Row,
Select,
SelectOption,
Separator,
Tab,
Tabs,
Text,
)
from prefab_ui.components.charts import BarChart, ChartSeries, PieChart
from prefab_ui.rx import ERROR, RESULT, STATE, Rx
from fastmcp import FastMCP, FastMCPApp
# ---------------------------------------------------------------------------
# Sample data
# ---------------------------------------------------------------------------
SALES_DATA: list[dict] = [
{
"date": "2025-01-05",
"product": "Widget A",
"region": "North",
"amount": 1200,
"quantity": 10,
},
{
"date": "2025-01-12",
"product": "Widget B",
"region": "South",
"amount": 850,
"quantity": 7,
},
{
"date": "2025-01-18",
"product": "Gadget X",
"region": "East",
"amount": 2300,
"quantity": 15,
},
{
"date": "2025-01-25",
"product": "Gadget Y",
"region": "West",
"amount": 1750,
"quantity": 12,
},
{
"date": "2025-02-02",
"product": "Widget A",
"region": "East",
"amount": 1400,
"quantity": 11,
},
{
"date": "2025-02-09",
"product": "Widget B",
"region": "North",
"amount": 920,
"quantity": 8,
},
{
"date": "2025-02-15",
"product": "Gadget X",
"region": "South",
"amount": 2100,
"quantity": 14,
},
{
"date": "2025-02-22",
"product": "Gadget Y",
"region": "West",
"amount": 1600,
"quantity": 11,
},
{
"date": "2025-03-01",
"product": "Widget A",
"region": "South",
"amount": 1350,
"quantity": 10,
},
{
"date": "2025-03-08",
"product": "Widget B",
"region": "West",
"amount": 780,
"quantity": 6,
},
{
"date": "2025-03-14",
"product": "Gadget X",
"region": "North",
"amount": 2500,
"quantity": 17,
},
{
"date": "2025-03-21",
"product": "Gadget Y",
"region": "East",
"amount": 1900,
"quantity": 13,
},
{
"date": "2025-04-03",
"product": "Widget A",
"region": "West",
"amount": 1100,
"quantity": 9,
},
{
"date": "2025-04-10",
"product": "Widget B",
"region": "East",
"amount": 960,
"quantity": 8,
},
{
"date": "2025-04-17",
"product": "Gadget X",
"region": "South",
"amount": 2400,
"quantity": 16,
},
{
"date": "2025-04-24",
"product": "Gadget Y",
"region": "North",
"amount": 1850,
"quantity": 12,
},
{
"date": "2025-05-01",
"product": "Widget A",
"region": "North",
"amount": 1500,
"quantity": 12,
},
{
"date": "2025-05-08",
"product": "Widget B",
"region": "South",
"amount": 890,
"quantity": 7,
},
{
"date": "2025-05-15",
"product": "Gadget X",
"region": "West",
"amount": 2200,
"quantity": 15,
},
{
"date": "2025-05-22",
"product": "Gadget Y",
"region": "East",
"amount": 1700,
"quantity": 11,
},
{
"date": "2025-06-05",
"product": "Widget A",
"region": "East",
"amount": 1300,
"quantity": 10,
},
{
"date": "2025-06-12",
"product": "Widget B",
"region": "North",
"amount": 1050,
"quantity": 9,
},
{
"date": "2025-06-19",
"product": "Gadget X",
"region": "North",
"amount": 2600,
"quantity": 18,
},
{
"date": "2025-06-26",
"product": "Gadget Y",
"region": "South",
"amount": 1650,
"quantity": 11,
},
{
"date": "2025-07-03",
"product": "Widget A",
"region": "South",
"amount": 1450,
"quantity": 11,
},
{
"date": "2025-07-10",
"product": "Widget B",
"region": "West",
"amount": 830,
"quantity": 7,
},
{
"date": "2025-07-17",
"product": "Gadget X",
"region": "East",
"amount": 2350,
"quantity": 16,
},
{
"date": "2025-07-24",
"product": "Gadget Y",
"region": "West",
"amount": 1800,
"quantity": 12,
},
{
"date": "2025-08-01",
"product": "Widget A",
"region": "West",
"amount": 1250,
"quantity": 10,
},
{
"date": "2025-08-08",
"product": "Widget B",
"region": "East",
"amount": 970,
"quantity": 8,
},
{
"date": "2025-08-15",
"product": "Gadget X",
"region": "South",
"amount": 2450,
"quantity": 16,
},
{
"date": "2025-08-22",
"product": "Gadget Y",
"region": "North",
"amount": 1950,
"quantity": 13,
},
]
REGIONS = ["All", "North", "South", "East", "West"]
PRODUCTS = ["All", "Widget A", "Widget B", "Gadget X", "Gadget Y"]
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _filter_rows(
rows: list[dict],
region: str = "All",
product: str = "All",
) -> list[dict]:
filtered = rows
if region != "All":
filtered = [r for r in filtered if r["region"] == region]
if product != "All":
filtered = [r for r in filtered if r["product"] == product]
return filtered
def _compute_summary(rows: list[dict]) -> dict:
if not rows:
return {
"count": 0,
"total_amount": 0,
"avg_amount": 0,
"min_amount": 0,
"max_amount": 0,
"total_quantity": 0,
}
amounts = [r["amount"] for r in rows]
return {
"count": len(rows),
"total_amount": sum(amounts),
"avg_amount": round(sum(amounts) / len(amounts)),
"min_amount": min(amounts),
"max_amount": max(amounts),
"total_quantity": sum(r["quantity"] for r in rows),
}
def _aggregate_by(rows: list[dict], key: str) -> list[dict]:
totals: dict[str, int] = {}
for row in rows:
label = row[key]
totals[label] = totals.get(label, 0) + row["amount"]
return [{key: label, "amount": total} for label, total in sorted(totals.items())]
# ---------------------------------------------------------------------------
# App
# ---------------------------------------------------------------------------
app = FastMCPApp("Data Explorer")
@app.tool()
def analyze_data(region: str = "All", product: str = "All") -> dict:
"""Filter and analyze sales data. Returns rows, summary, and chart data."""
filtered = _filter_rows(SALES_DATA, region, product)
return {
"rows": filtered,
"summary": _compute_summary(filtered),
"by_region": _aggregate_by(filtered, "region"),
"by_product": _aggregate_by(filtered, "product"),
}
@app.tool(model=True)
def get_summary() -> dict:
"""Return summary statistics for the full dataset."""
return _compute_summary(SALES_DATA)
@app.tool()
def filter_data(region: str = "All", product: str = "All") -> list[dict]:
"""Filter sales data by region and/or product."""
return _filter_rows(SALES_DATA, region, product)
@app.ui()
def data_explorer() -> PrefabApp:
"""Open the data explorer. Browse, filter, and visualize sales data."""
initial = analyze_data()
with Column(gap=6, css_class="p-6") as view:
Heading("Sales Data Explorer")
Muted(f"{len(SALES_DATA)} records loaded")
Separator()
# ----- Filters -----
with Row(gap=4, align="center"):
Text("Filters", css_class="font-semibold")
with Select(
name="selected_region",
placeholder="Region",
value="All",
on_change=[
SetState("loading", True),
CallTool(
analyze_data,
arguments={
"region": STATE.selected_region,
"product": STATE.selected_product,
},
on_success=[
SetState("rows", RESULT.rows),
SetState("summary", RESULT.summary),
SetState("by_region", RESULT.by_region),
SetState("by_product", RESULT.by_product),
SetState("loading", False),
ShowToast("Data updated", variant="success"),
],
on_error=[
SetState("loading", False),
ShowToast(ERROR, variant="error"),
],
),
],
):
for region in REGIONS:
SelectOption(value=region, label=region)
with Select(
name="selected_product",
placeholder="Product",
value="All",
on_change=[
SetState("loading", True),
CallTool(
analyze_data,
arguments={
"region": STATE.selected_region,
"product": STATE.selected_product,
},
on_success=[
SetState("rows", RESULT.rows),
SetState("summary", RESULT.summary),
SetState("by_region", RESULT.by_region),
SetState("by_product", RESULT.by_product),
SetState("loading", False),
ShowToast("Data updated", variant="success"),
],
on_error=[
SetState("loading", False),
ShowToast(ERROR, variant="error"),
],
),
],
):
for product in PRODUCTS:
SelectOption(value=product, label=product)
Button(
Rx("loading").then("Loading...", "Reset"),
disabled=Rx("loading"),
on_click=[
SetState("selected_region", "All"),
SetState("selected_product", "All"),
SetState("loading", True),
CallTool(
analyze_data,
arguments={"region": "All", "product": "All"},
on_success=[
SetState("rows", RESULT.rows),
SetState("summary", RESULT.summary),
SetState("by_region", RESULT.by_region),
SetState("by_product", RESULT.by_product),
SetState("loading", False),
],
on_error=[
SetState("loading", False),
ShowToast(ERROR, variant="error"),
],
),
],
)
Separator()
# ----- Tabs -----
with Tabs():
# ---- Summary ----
with Tab("Summary"):
with Grid(columns=3, gap=4):
with Card():
with CardContent():
Metric(
label="Total Revenue",
value=Rx("summary.total_amount"),
)
with Card():
with CardContent():
Metric(
label="Average Sale",
value=Rx("summary.avg_amount"),
)
with Card():
with CardContent():
Metric(
label="Total Quantity",
value=Rx("summary.total_quantity"),
)
with Grid(columns=3, gap=4, css_class="mt-4"):
with Card():
with CardContent():
Metric(
label="Transactions",
value=Rx("summary.count"),
)
with Card():
with CardContent():
Metric(
label="Min Sale",
value=Rx("summary.min_amount"),
)
with Card():
with CardContent():
Metric(
label="Max Sale",
value=Rx("summary.max_amount"),
)
with Row(gap=2, css_class="mt-4"):
Badge(f"Region: {STATE.selected_region}")
Badge(f"Product: {STATE.selected_product}")
# ---- Table ----
with Tab("Table"):
DataTable(
columns=[
DataTableColumn(key="date", header="Date", sortable=True),
DataTableColumn(key="product", header="Product", sortable=True),
DataTableColumn(key="region", header="Region", sortable=True),
DataTableColumn(
key="amount", header="Amount ($)", sortable=True
),
DataTableColumn(key="quantity", header="Qty", sortable=True),
],
rows="{{ rows }}",
search=True,
paginated=True,
page_size=10,
)
# ---- Charts ----
with Tab("Charts"):
with Grid(columns=2, gap=6):
with Column(gap=2):
Heading("Revenue by Region", level=3)
BarChart(
data=Rx("by_region"),
series=[ChartSeries(data_key="amount", label="Revenue")],
x_axis="region",
show_legend=True,
)
with Column(gap=2):
Heading("Revenue by Product", level=3)
BarChart(
data=Rx("by_product"),
series=[ChartSeries(data_key="amount", label="Revenue")],
x_axis="product",
show_legend=True,
)
Separator(css_class="my-4")
with Grid(columns=2, gap=6):
with Column(gap=2):
Heading("Region Breakdown", level=3)
PieChart(
data=Rx("by_region"),
data_key="amount",
name_key="region",
show_legend=True,
inner_radius=60,
)
with Column(gap=2):
Heading("Product Breakdown", level=3)
PieChart(
data=Rx("by_product"),
data_key="amount",
name_key="product",
show_legend=True,
inner_radius=60,
)
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])
if __name__ == "__main__":
mcp.run(transport="http")