kentcdodds

Remix 3 MCP Demo

Community kentcdodds
Updated

Remix 3 MCP Demo

This project demonstrates how to build interactive MCP (Model Context Protocol)widgets that run on Cloudflare Workers and can be embedded in AI chat interfaceslike ChatGPT. It showcases the power of combining MCP with modern webtechnologies to create rich, stateful experiences within AI conversations.

Demo Video

See the calculator widget in action with ChatGPT, including the hidden TRONeaster egg:

https://github.com/user-attachments/assets/5df110d8-f40b-4c6a-8820-c2dbf3ff79c8

Watch the demo on X/Twitter

How the Demo Works

Architecture Overview

This demo implements a calculator widget as an MCP tool that can be invokedby AI assistants. The architecture consists of several key components:

  1. MCP Server - A Cloudflare Durable Object that implements the ModelContext Protocol
  2. Widget System - Interactive UI components built with Remix 3 that can beembedded in AI chats
  3. Two-way Communication - Widgets can both receive initial state from theAI and send messages back
  4. Static Assets - Widget bundles served from Cloudflare's CDN

The Calculator Widget

The calculator is a fully functional, beautifully styled calculator with aretro-futuristic aesthetic inspired by Tron. Here's what makes it special:

Initial State Configuration

When an AI assistant invokes the calculator tool, it can pass initial stateparameters:

  • display - The initial display value
  • previousValue - A value already entered (e.g., "I want to add 5 to anumber")
  • operation - The pending operation (+, -, *, /)
  • waitingForNewValue - Whether the calculator is ready for new input
  • errorState - Whether to start in an error state

This means the AI can pre-configure the calculator based on the user's request.For example, if a user says "I want to add 5 to something," the AI can invokethe calculator with previousValue: 5, operation: '+', andwaitingForNewValue: true.

Interactive UI

The calculator widget is a fully interactive Remix application that:

  • Renders using JSX/TSX with CSS-in-JS styling
  • Supports keyboard shortcuts (Enter, Escape, number keys, operators, etc.)
  • Features a Tron-style initialization sequence with animated loading messages
  • Updates in real-time as users interact with it
  • Uses Remix 3's experimental DOM renderer for efficient updates
The Easter Egg: The Master Control Program

There's a hidden feature in the calculator: when the result equals 1982 (theyear the original Tron film was released), the calculator sends an MCP promptmessage to the AI assistant, instructing it to adopt the persona of the MasterControl Program (MCP) from Tron.

This demonstrates the widget's ability to dynamically influence theconversation by sending messages back to the AI.

Technical Implementation

MCP Server with Durable Objects

The MathMCP class extends McpAgent and uses Cloudflare's Durable Objects tomaintain state:

export class MathMCP extends McpAgent<Env, State, Props> {
	server = new McpServer(
		{
			name: 'MathMCP',
			version: '1.0.0',
		},
		{
			instructions: `Use this server to solve math problems reliably and accurately.`,
		},
	)
	async init() {
		await registerTools(this)
		await registerWidgets(this)
	}
}

The server registers two types of capabilities:

  1. Tools - A do_math tool that performs arithmetic operations server-side
  2. Widgets - Interactive UI resources that can be embedded in the chat
Widget Registration

Widgets are registered as both MCP resources (for the HTML/JS bundle) and MCPtools (for invocation). The registration includes:

  • Input Schema - Zod schemas defining what parameters the widget accepts
  • Output Schema - Zod schemas defining what the widget can return
  • HTML Bundle - The rendered HTML with script references
  • OpenAI Metadata - Special metadata that tells ChatGPT how to display thewidget
agent.server.registerResource(name, uri, {}, async () => ({
	contents: [
		createUIResource({
			content: {
				type: 'rawHtml',
				htmlString: await widget.getHtml(),
			},
			metadata: {
				'openai/widgetDescription': widget.description,
				'openai/widgetCSP': {
					connect_domains: [],
					resource_domains: [baseUrl],
				},
			},
		}).resource,
	],
}))
Separate Build Process

The project uses two separate build processes:

  1. Widget Build (Vite) - Builds the calculator UI into standalone JavaScriptbundles

    • Input: worker/widgets/calculator/index.tsx
    • Output: dist/public/widgets/calculator.js
    • Format: ES modules with all dependencies bundled
  2. Worker Build (Wrangler) - Builds the Cloudflare Worker with MCP server

    • Input: worker/index.tsx
    • Output: Worker bundle deployed to Cloudflare
    • Includes: MCP protocol handlers, tool registration, widget serving
Communication Protocol

Widgets communicate with their parent frame (the AI chat interface) usingpostMessage:

  • Initialization - Widget sends ui-lifecycle-iframe-ready when mounted
  • Render Data - Widget receives ui-lifecycle-iframe-render-data withinitial state
  • Tool Calls - Widget can invoke other MCP tools by sending tool messages
  • Prompts - Widget can send new prompts to the AI using prompt messages
  • Links - Widget can open links using link messages
// Widget sends a prompt to the AI
sendMcpMessage('prompt', { prompt: MCP_PROMPT })

// Widget waits for initial render data
const renderData = await waitForRenderData(renderDataSchema)

The User Experience

Here's what happens when a user interacts with this MCP server in ChatGPT:

  1. User asks: "Can I get a calculator?"
  2. ChatGPT invokes the calculator tool via MCP
  3. The server responds with:
    • Text content: "The calculator has been rendered"
    • UI resource: The calculator HTML with initial state
    • Structured content: The current calculator state
  4. ChatGPT renders the calculator widget in an iframe
  5. The widget loads, shows a Tron-style initialization sequence, then displaysthe calculator
  6. User interacts with the calculator (clicking buttons or using keyboard)
  7. If the result is 1982, the widget sends a prompt back to ChatGPT
  8. ChatGPT adopts the MCP persona and responds accordingly

Running on Your Own

Prerequisites

  • Node.js (v18 or later)
  • npm or yarn
  • A Cloudflare account (for deployment)

Local Development

  1. Clone and Install

    npm install
    
  2. Start Development Server

    npm run dev
    

    This runs two processes concurrently:

    • Widget build in watch mode (Vite)
    • Worker with local Durable Objects (Wrangler)
  3. Test the Calculator Widget

    Visit http://localhost:8787/__dev/widgets to see the calculator widget inisolation.

  4. Connect to MCP Inspector

    Use the MCP Inspector to test the MCP server:

    npm run inspect
    

    Then connect to http://localhost:8787/mcp in the inspector.

Deployment

  1. Build for Production

    npm run build
    
  2. Deploy to Cloudflare

    npm run deploy
    
  3. Use with ChatGPT

    Once deployed, you can add this MCP server to ChatGPT by providing thedeployment URL + /mcp endpoint.

Project Structure

├── worker/
│   ├── index.tsx              # Main worker entry point
│   ├── tools.ts               # MCP tool definitions (do_math)
│   ├── widgets.tsx            # Widget registration system
│   ├── utils.ts               # CORS and utility functions
│   └── widgets/
│       ├── utils.ts           # Widget communication utilities
│       └── calculator/
│           ├── index.tsx      # Calculator UI component
│           ├── calculator.ts  # Calculator business logic
│           └── mcp-prompt.ts  # The MCP easter egg prompt
├── dist/
│   └── public/
│       └── widgets/
│           └── calculator.js  # Built calculator bundle
├── vite.config.widgets.ts     # Vite config for widget builds
└── wrangler.jsonc             # Cloudflare Workers config

Key Technologies

Environment & Configuration

The wrangler.jsonc configures:

  • Durable Object binding (MATH_MCP_OBJECT)
  • Assets binding for serving widget bundles
  • Node.js compatibility for MCP SDK
  • Observability for production monitoring

Development Tips

  • Widget Development: Changes to widget code will hot-reload automatically
  • Worker Changes: Wrangler will restart the worker on file changes
  • Type Safety: Run npm run typecheck to validate TypeScript
  • Linting: Run npm run lint to check code style

Credits

This demo showcases cutting-edge web technologies including experimental Remix 3features, MCP widgets, and Cloudflare's edge computing platform. The calculatordesign pays homage to the aesthetic of Tron, with its distinctive orange glowand retro-futuristic style.

MCP Server · Populars

MCP Server · New

    MaxEllis

    OrcaSlicer MCP

    OrcaSlicer MCP — drive OrcaSlicer from Claude or any MCP client: load models, tune settings, slice, analyze

    Community MaxEllis
    kentcdodds

    kody

    Your assistant's home — the memory, keys, code, and automations your AI agent keeps, portable across every MCP host. Built on Cloudflare Workers.

    Community kentcdodds
    open-and-async

    Open and Async — MCP Server

    Model Context Protocol server for the book Open and Async — async-first method tools plus the book's outline, taglines, and summaries. Ships the method, never the manuscript.

    Community open-and-async
    firish

    webfetch

    Own your LLM's web search: a local search->fetch->rank pipeline that replaces hosted web_search tools. Measured: matches hosted accuracy at ~1/3 the cost with 5-8x fewer tokens, plus semantic caching no API offers.

    Community firish
    airas-org

    AIRAS - an open-source project for research automation

    AIRAS - an open-source project for research automation

    Community airas-org