Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
DEPRECATED: Replaced by mcp-app-builder. Previously used to build ChatGPT apps with interactive React widgets via mcp-use.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
SKILL.md
1---2name: chatgpt-app-builder3description: |4**MANDATORY for ALL MCP server work** - mcp-use framework best practices and patterns.56**READ THIS FIRST** before any MCP server work, including:7- Creating new MCP servers8- Modifying existing MCP servers (adding/updating tools, resources, prompts, widgets)9- Debugging MCP server issues or errors10- Reviewing MCP server code for quality, security, or performance11- Answering questions about MCP development or mcp-use patterns12- Making ANY changes to server.tool(), server.resource(), server.prompt(), or widgets1314This skill contains critical architecture decisions, security patterns, and common pitfalls.15Always consult the relevant reference files BEFORE implementing MCP features.16---1718# IMPORTANT: How to Use This Skill1920This file provides a NAVIGATION GUIDE ONLY. Before implementing any MCP server features, you MUST:21221. Read this overview to understand which reference files are relevant232. **ALWAYS read the specific reference file(s)** for the features you're implementing243. Apply the detailed patterns from those files to your implementation2526**Do NOT rely solely on the quick reference examples in this file** - they are minimal examples only. The reference files contain critical best practices, security considerations, and advanced patterns.2728---2930# MCP Server Best Practices3132Comprehensive guide for building production-ready MCP servers with tools, resources, prompts, and widgets using mcp-use.3334## ⚠️ FIRST: New Project or Existing Project?3536**Before doing anything else, determine whether you are inside an existing mcp-use project.**3738**Detection:** Check the workspace for a `package.json` that lists `"mcp-use"` as a dependency, OR any `.ts` file that imports from `"mcp-use/server"`.3940```41├─ mcp-use project FOUND → Do NOT scaffold. You are already in a project.42│ └─ Skip to "Quick Navigation" below to add features.43│44├─ NO mcp-use project (empty dir, unrelated project, or greenfield)45│ └─ Scaffold first with npx create-mcp-use-app, then add features.46│ See "Scaffolding a New Project" below.47│48└─ Inside an UNRELATED project (e.g. Next.js app) and user wants an MCP server49└─ Ask the user where to create it, then scaffold in that directory.50Do NOT scaffold inside an existing unrelated project root.51```5253**NEVER manually create `MCPServer` boilerplate, `package.json`, or project structure by hand.** The CLI sets up TypeScript config, dev scripts, inspector integration, hot reload, and widget compilation that are difficult to replicate manually.5455---5657### Scaffolding a New Project5859```bash60npx create-mcp-use-app my-server61cd my-server62npm run dev63```6465For full scaffolding details and CLI flags, see **[quickstart.md](references/foundations/quickstart.md)**.6667---6869## Quick Navigation7071**Choose your path based on what you're building:**7273### 🚀 Foundations74**When:** ALWAYS read these first when starting MCP work in a new conversation. Reference later for architecture/concept clarification.75761. **[concepts.md](references/foundations/concepts.md)** - MCP primitives (Tool, Resource, Prompt, Widget) and when to use each772. **[architecture.md](references/foundations/architecture.md)** - Server structure (Hono-based), middleware system, server.use() vs server.app783. **[quickstart.md](references/foundations/quickstart.md)** - Scaffolding, setup, and first tool example794. **[deployment.md](references/foundations/deployment.md)** - Deploying to Manufact Cloud, self-hosting, Docker, managing deployments8081Load these before diving into tools/resources/widgets sections.8283---8485### 🔐 Adding Authentication?86**When:** Protecting your server with OAuth (Auth0, Better Auth, Clerk, WorkOS, Supabase, Keycloak, or any other provider)8788- **[overview.md](references/authentication/overview.md)**89- When: First time adding auth, understanding `ctx.auth`, or choosing a provider / integration mode90- Covers: Remote auth vs OAuth proxy, `oauth` config, `ctx.auth` shape, provider comparison, common mistakes9192- **[auth0.md](references/authentication/auth0.md)**93- When: Using Auth0 — DCR (Early Access) or a standard Regular Web App via `oauthProxy`94- Covers: Setup for both modes, `extraAuthorizeParams.audience`, permissions via `rfc9068_profile_authz`9596- **[better-auth.md](references/authentication/better-auth.md)**97- When: Using Better Auth with the `@better-auth/oauth-provider` plugin (self-hosted OAuth 2.1)98- Covers: `oauthBetterAuthProvider`, auth URL / metadata routes, login and consent flows99100- **[clerk.md](references/authentication/clerk.md)**101- When: Using Clerk (DCR-based OAuth)102- Covers: `oauthClerkProvider`, enabling DCR, Frontend API URL, organization context103104- **[workos.md](references/authentication/workos.md)**105- When: Using WorkOS AuthKit (DCR only)106- Covers: Setup, env vars, roles/permissions, multi-tenant org filtering, WorkOS API calls107108- **[supabase.md](references/authentication/supabase.md)**109- When: Using Supabase's OAuth 2.1 server110- Covers: Setup, publishable keys, ES256 vs HS256, hosting the consent UI, RLS-aware SDK calls111112- **[keycloak.md](references/authentication/keycloak.md)**113- When: Using Keycloak via native DCR114- Covers: DCR trusted hosts + web origins, audience enforcement, realm vs resource roles, userinfo115116- **[custom.md](references/authentication/custom.md)**117- When: Any other provider — DCR-capable via `oauthCustomProvider`, or pre-registered (Google, GitHub, Okta, Azure AD) via `oauthProxy`118- Covers: `oauthCustomProvider`, `oauthProxy` + `jwksVerifier`, provider examples, opaque-token verification119120---121122### 🔧 Building Server Backend (No UI)?123**When:** Implementing MCP features (actions, data, templates). Read the specific file for the primitive you're building.124125- **[tools.md](references/server/tools.md)**126- When: Creating backend actions the AI can call (send-email, fetch-data, create-user)127- Covers: Tool definition, schemas, annotations, context, error handling128129- **[resources.md](references/server/resources.md)**130- When: Exposing read-only data clients can fetch (config, user profiles, documentation)131- Covers: Static resources, dynamic resources, parameterized resource templates, URI completion132133- **[prompts.md](references/server/prompts.md)**134- When: Creating reusable message templates for AI interactions (code-review, summarize)135- Covers: Prompt definition, parameterization, argument completion, prompt best practices136137- **[response-helpers.md](references/server/response-helpers.md)**138- When: Formatting responses from tools/resources (text, JSON, markdown, images, errors)139- Covers: `text()`, `object()`, `markdown()`, `image()`, `error()`, `mix()`140141- **[proxy.md](references/server/proxy.md)**142- When: Composing multiple MCP servers into one unified aggregator server143- Covers: `server.proxy()`, config API, explicit sessions, sampling routing144145- **[architecture.md](references/foundations/architecture.md)**146- When: Adding cross-cutting logic (logging, auth checks, rate limiting, tool filtering) that spans multiple tools/resources147- Covers: `server.use('mcp:...')` middleware, `MiddlewareContext` (method, params, auth, state), pattern matching, HTTP vs MCP middleware148149---150151### 🎨 Building Visual Widgets (Interactive UI)?152**When:** Creating React-based visual interfaces for browsing, comparing, or selecting data153154- **[basics.md](references/widgets/basics.md)**155- When: Creating your first widget or adding UI to an existing tool156- Covers: Widget setup, `useWidget()` hook, `isPending` checks, props handling157158- **[state.md](references/widgets/state.md)**159- When: Managing UI state (selections, filters, tabs) within widgets160- Covers: `useState`, `setState`, state persistence, when to use tool vs widget state161162- **[interactivity.md](references/widgets/interactivity.md)**163- When: Adding buttons, forms, or calling tools from within widgets164- Covers: `useCallTool()`, form handling, action buttons, optimistic updates165166- **[ui-guidelines.md](references/widgets/ui-guidelines.md)**167- When: Styling widgets to support themes, responsive layouts, or accessibility168- Covers: `useWidgetTheme()`, light/dark mode, `autoSize`, layout patterns, CSS best practices169170- **[advanced.md](references/widgets/advanced.md)**171- When: Building complex widgets with async data, error boundaries, or performance optimizations172- Covers: Loading states, error handling, memoization, code splitting173174- **[model-context.md](references/widgets/model-context.md)**175- When: Keeping the AI model aware of what the user is currently seeing (active tab, hovered item, selected product) without requiring tool calls176- Covers: `<ModelContext>` component, `modelContext.set/remove` imperative API, nesting, tree serialization, lifecycle rules177- **[files.md](references/widgets/files.md)**178- When: Uploading or downloading files from within a widget (ChatGPT Apps SDK only)179- Covers: `useFiles()` hook, `isSupported` guard, model visibility (`modelVisible`), storing `fileId`, temporary download URLs180181---182183### 📚 Need Complete Examples?184**When:** You want to see full implementations of common use cases185186- **[common-patterns.md](references/patterns/common-patterns.md)**187- End-to-end examples: weather app, todo list, recipe browser188- Shows: Server code + widget code + best practices in context189190---191192## Decision Tree193194```195What do you need?196197├─ New project from scratch198│ └─> quickstart.md (scaffolding + setup)199│200├─ OAuth / user authentication201│ └─> authentication/overview.md → provider-specific guide202│203├─ Simple backend action (no UI)204│ └─> Use Tool: server/tools.md205│206├─ Read-only data for clients207│ └─> Use Resource: server/resources.md208│209├─ Reusable prompt template210│ └─> Use Prompt: server/prompts.md211│212├─ Cross-cutting logic (logging, auth checks, rate limiting, tool filtering)213│ └─> Use Middleware: architecture.md#mcp-middleware214│215├─ Visual/interactive UI216│ └─> Use Widget: widgets/basics.md217│218├─ Keep model aware of what user is seeing in widget219│ └─> widgets/model-context.md220├─ Upload/download files in a widget221│ └─> widgets/files.md (ChatGPT Apps SDK only)222│223└─ Deploy to production224└─> deployment.md (cloud deploy, self-hosting, Docker)225```226227---228229## Core Principles2302311. **Tools for actions** - Backend operations with input/output2322. **Resources for data** - Read-only data clients can fetch2333. **Prompts for templates** - Reusable message templates2344. **Widgets for UI** - Visual interfaces when helpful2355. **Mock data first** - Prototype quickly, connect APIs later236237---238239## ❌ Common Mistakes240241Avoid these anti-patterns found in production MCP servers:242243### Tool Definition244- ❌ Returning raw objects instead of using response helpers245- ✅ Use `text()`, `object()`, `widget()`, `error()` helpers246- ❌ Skipping Zod schema `.describe()` on every field247- ✅ Add descriptions to all schema fields for better AI understanding248- ❌ No input validation or sanitization249- ✅ Validate inputs with Zod, sanitize user-provided data250- ❌ Throwing errors instead of returning `error()` helper251- ✅ Use `error("message")` for graceful error responses252253### Widget Development254- ❌ Accessing `props` without checking `isPending`255- ✅ Always check `if (isPending) return <Loading/>`256- ❌ Widget handles server state (filters, selections)257- ✅ Widgets manage their own UI state with `useState`258- ❌ Missing `McpUseProvider` wrapper or `autoSize`259- ✅ Wrap root component: `<McpUseProvider autoSize>`260- ❌ Inline styles without theme awareness261- ✅ Use `useWidgetTheme()` for light/dark mode support262263### Security & Production264- ❌ Hardcoded API keys or secrets in code265- ✅ Use `process.env.API_KEY`, document in `.env.example`266- ❌ No error handling in tool handlers267- ✅ Wrap in try/catch, return `error()` on failure268- ❌ Expensive operations without caching269- ✅ Cache API calls, computations with TTL270- ❌ Missing CORS configuration271- ✅ Configure CORS for production deployments272273---274275## 🔒 Golden Rules276277**Opinionated architectural guidelines:**278279### 1. One Tool = One Capability280Split broad actions into focused tools:281- ❌ `manage-users` (too vague)282- ✅ `create-user`, `delete-user`, `list-users`283284### 2. Return Complete Data Upfront285Tool calls are expensive. Avoid lazy-loading:286- ❌ `list-products` + `get-product-details` (2 calls)287- ✅ `list-products` returns full data including details288289### 3. Widgets Own Their State290UI state lives in the widget, not in separate tools:291- ❌ `select-item` tool, `set-filter` tool292- ✅ Widget manages with `useState` or `setState`293294### 4. `exposeAsTool` Defaults to `false`295Widgets are registered as resources only by default. Use a custom tool (recommended) or set `exposeAsTool: true` to expose a widget to the model:296297```typescript298// ✅ ALL 4 STEPS REQUIRED for proper type inference:299300// Step 1: Define schema separately301const propsSchema = z.object({302title: z.string(),303items: z.array(z.string())304});305306// Step 2: Reference schema variable in metadata307export const widgetMetadata: WidgetMetadata = {308description: "...",309props: propsSchema, // ← NOT inline z.object()310exposeAsTool: false311};312313// Step 3: Infer Props type from schema variable314type Props = z.infer<typeof propsSchema>;315316// Step 4: Use typed Props with useWidget317export default function MyWidget() {318const { props, isPending } = useWidget<Props>(); // ← Add <Props>319// ...320}321```322323⚠️ **Common mistake:** Only doing steps 1-2 but skipping 3-4 (loses type safety)324325### 5. Validate at Boundaries Only326- Trust internal code and framework guarantees327- Validate user input, external API responses328- Don't add error handling for scenarios that can't happen329330### 6. Prefer Widgets for Browsing/Comparing331When in doubt, add a widget. Visual UI improves:332- Browsing multiple items333- Comparing data side-by-side334- Interactive selection workflows335336---337338## Quick Reference339340### Minimal Server341```typescript342import { MCPServer, text } from "mcp-use/server";343import { z } from "zod";344345const server = new MCPServer({346name: "my-server",347title: "My Server",348version: "1.0.0"349});350351server.tool(352{353name: "greet",354description: "Greet a user",355schema: z.object({ name: z.string().describe("User's name") })356},357async ({ name }) => text("Hello " + name + "!"),358);359360server.listen();361```362363---364365## Response Helpers366367| Helper | Use When | Example |368|--------|----------|---------|369| `text()` | Simple string response | `text("Success!")` |370| `object()` | Structured data | `object({ status: "ok" })` |371| `markdown()` | Formatted text | `markdown("# Title\nContent")` |372| `widget()` | Visual UI | `widget({ props: {...}, output: text(...) })` |373| `mix()` | Multiple contents | `mix(text("Hi"), image(url))` |374| `error()` | Error responses | `error("Failed to fetch data")` |375| `resource()` | Embed resource refs | `resource("docs://guide", "text/markdown")` |376377**Server methods:**378- `server.tool()` - Define executable tool379- `server.resource()` - Define static/dynamic resource380- `server.resourceTemplate()` - Define parameterized resource381- `server.prompt()` - Define prompt template382- `server.proxy()` - Compose/Proxy multiple MCP servers383- `server.uiResource()` - Define widget resource384- `server.listen()` - Start server385- `server.use('mcp:tools/call', fn)` - MCP middleware (tools, resources, prompts, list ops)386- `server.use('mcp:*', fn)` - Catch-all MCP middleware387- `server.use(fn)` - HTTP middleware (Hono)388