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 MCP servers with tools, resources, and prompts 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: mcp-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### 🔁 Testing from the Terminal (Agent Feedback Loops)193**When:** You want to verify a tool or widget *without* the inspector UI — the canonical flow for AI agents iterating on MCP servers.194195- **`mcp-use client`** — drives MCP servers from the terminal. Auto-runs OAuth on 401, persists saved servers under a short name, and one-shot subcommands exit cleanly so they're safe to spawn from harnesses.196197```bash198npx mcp-use client connect dev http://localhost:3000/mcp199npx mcp-use client dev tools list200npx mcp-use client dev tools call get-weather city=Tokyo --screenshot201```202203Every per-server command takes the saved name as its first positional arg (`mcp-use client <name> <scope> <action>`) — there is no "active session". Args use `key=value` (with `key:='<json>'` for nested values) or a single JSON object. When a tool renders a widget, pass `--screenshot` to also save a PNG (`./<view>-<timestamp>.png` by default, or override with `--screenshot-output <path>`).204205- **`mcp-use client screenshot`** — headless render of a widget tool to a PNG. Use this when you want to visually verify a widget change without opening the inspector, especially in loops where you call a tool, screenshot, eyeball the output, and edit. Two forms:206207```bash208# Saved-server form — reuses the auth from `mcp-use client connect`209npx mcp-use client dev screenshot --tool get-weather city=Tokyo \210--width 800 --height 600 --theme light \211--output ./weather.png212213# Ad-hoc form — connect inline (use -H for headers on authenticated servers)214npx mcp-use client screenshot --mcp http://localhost:3000/mcp \215--tool get-weather city=Tokyo216```217218Add `--device-scale-factor 2` for Retina output, or `--cdp-url <ws>` plus `--inspector <publicly-reachable-url>` to drive a remote Chromium (e.g. Notte) from a sandbox without a local Chrome install.219220Both commands are documented in full at [docs/typescript/client/cli](https://docs.mcp-use.com/typescript/client/cli).221222---223224## Decision Tree225226```227What do you need?228229├─ New project from scratch230│ └─> quickstart.md (scaffolding + setup)231│232├─ OAuth / user authentication233│ └─> authentication/overview.md → provider-specific guide234│235├─ Simple backend action (no UI)236│ └─> Use Tool: server/tools.md237│238├─ Read-only data for clients239│ └─> Use Resource: server/resources.md240│241├─ Reusable prompt template242│ └─> Use Prompt: server/prompts.md243│244├─ Cross-cutting logic (logging, auth checks, rate limiting, tool filtering)245│ └─> Use Middleware: architecture.md#mcp-middleware246│247├─ Visual/interactive UI248│ └─> Use Widget: widgets/basics.md249│250├─ Keep model aware of what user is seeing in widget251│ └─> widgets/model-context.md252├─ Upload/download files in a widget253│ └─> widgets/files.md (ChatGPT Apps SDK only)254│255├─ Verify a tool or widget from the terminal (agent feedback loop)256│ └─> See "Testing from the Terminal" above — `mcp-use client` for tool runs,257│ `mcp-use client <server> screenshot --tool <tool>` for headless widget PNGs258│259└─ Deploy to production260└─> deployment.md (cloud deploy, self-hosting, Docker)261```262263---264265## Core Principles2662671. **Tools for actions** - Backend operations with input/output2682. **Resources for data** - Read-only data clients can fetch2693. **Prompts for templates** - Reusable message templates2704. **Widgets for UI** - Visual interfaces when helpful2715. **Mock data first** - Prototype quickly, connect APIs later272273---274275## ❌ Common Mistakes276277Avoid these anti-patterns found in production MCP servers:278279### Tool Definition280- ❌ Returning raw objects instead of using response helpers281- ✅ Use `text()`, `object()`, `widget()`, `error()` helpers282- ❌ Skipping Zod schema `.describe()` on every field283- ✅ Add descriptions to all schema fields for better AI understanding284- ❌ No input validation or sanitization285- ✅ Validate inputs with Zod, sanitize user-provided data286- ❌ Throwing errors instead of returning `error()` helper287- ✅ Use `error("message")` for graceful error responses288289### Widget Development290- ❌ Accessing `props` without checking `isPending`291- ✅ Always check `if (isPending) return <Loading/>`292- ❌ Widget handles server state (filters, selections)293- ✅ Widgets manage their own UI state with `useState`294- ❌ Missing `McpUseProvider` wrapper or `autoSize`295- ✅ Wrap root component: `<McpUseProvider autoSize>`296- ❌ Inline styles without theme awareness297- ✅ Use `useWidgetTheme()` for light/dark mode support298299### Security & Production300- ❌ Hardcoded API keys or secrets in code301- ✅ Use `process.env.API_KEY`, document in `.env.example`302- ❌ No error handling in tool handlers303- ✅ Wrap in try/catch, return `error()` on failure304- ❌ Expensive operations without caching305- ✅ Cache API calls, computations with TTL306- ❌ Missing CORS configuration307- ✅ Configure CORS for production deployments308309---310311## 🔒 Golden Rules312313**Opinionated architectural guidelines:**314315### 1. One Tool = One Capability316Split broad actions into focused tools:317- ❌ `manage-users` (too vague)318- ✅ `create-user`, `delete-user`, `list-users`319320### 2. Return Complete Data Upfront321Tool calls are expensive. Avoid lazy-loading:322- ❌ `list-products` + `get-product-details` (2 calls)323- ✅ `list-products` returns full data including details324325### 3. Widgets Own Their State326UI state lives in the widget, not in separate tools:327- ❌ `select-item` tool, `set-filter` tool328- ✅ Widget manages with `useState` or `setState`329330### 4. `exposeAsTool` Defaults to `false`331Widgets are registered as resources only by default. Use a custom tool (recommended) or set `exposeAsTool: true` to expose a widget to the model:332333```typescript334// ✅ ALL 4 STEPS REQUIRED for proper type inference:335336// Step 1: Define schema separately337const propsSchema = z.object({338title: z.string(),339items: z.array(z.string())340});341342// Step 2: Reference schema variable in metadata343export const widgetMetadata: WidgetMetadata = {344description: "...",345props: propsSchema, // ← NOT inline z.object()346exposeAsTool: false347};348349// Step 3: Infer Props type from schema variable350type Props = z.infer<typeof propsSchema>;351352// Step 4: Use typed Props with useWidget353export default function MyWidget() {354const { props, isPending } = useWidget<Props>(); // ← Add <Props>355// ...356}357```358359⚠️ **Common mistake:** Only doing steps 1-2 but skipping 3-4 (loses type safety)360361### 5. Validate at Boundaries Only362- Trust internal code and framework guarantees363- Validate user input, external API responses364- Don't add error handling for scenarios that can't happen365366### 6. Prefer Widgets for Browsing/Comparing367When in doubt, add a widget. Visual UI improves:368- Browsing multiple items369- Comparing data side-by-side370- Interactive selection workflows371372---373374## Quick Reference375376### Minimal Server377```typescript378import { MCPServer, text } from "mcp-use/server";379import { z } from "zod";380381const server = new MCPServer({382name: "my-server",383title: "My Server",384version: "1.0.0"385});386387server.tool(388{389name: "greet",390description: "Greet a user",391schema: z.object({ name: z.string().describe("User's name") })392},393async ({ name }) => text("Hello " + name + "!"),394);395396server.listen();397```398399---400401## Response Helpers402403| Helper | Use When | Example |404|--------|----------|---------|405| `text()` | Simple string response | `text("Success!")` |406| `object()` | Structured data | `object({ status: "ok" })` |407| `markdown()` | Formatted text | `markdown("# Title\nContent")` |408| `widget()` | Visual UI | `widget({ props: {...}, output: text(...) })` |409| `mix()` | Multiple contents | `mix(text("Hi"), image(url))` |410| `error()` | Error responses | `error("Failed to fetch data")` |411| `resource()` | Embed resource refs | `resource("docs://guide", "text/markdown")` |412413**Server methods:**414- `server.tool()` - Define executable tool415- `server.resource()` - Define static/dynamic resource416- `server.resourceTemplate()` - Define parameterized resource417- `server.prompt()` - Define prompt template418- `server.proxy()` - Compose/Proxy multiple MCP servers419- `server.uiResource()` - Define widget resource420- `server.listen()` - Start server421- `server.use('mcp:tools/call', fn)` - MCP middleware (tools, resources, prompts, list ops)422- `server.use('mcp:*', fn)` - Catch-all MCP middleware423- `server.use(fn)` - HTTP middleware (Hono)424425426