IMPORTANT: How to Use This Skill
This file provides a NAVIGATION GUIDE ONLY. Before implementing any MCP server features, you MUST:
- Read this overview to understand which reference files are relevant
- ALWAYS read the specific reference file(s) for the features you're implementing
- Apply the detailed patterns from those files to your implementation
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.
MCP Server Best Practices
Comprehensive guide for building production-ready MCP servers with tools, resources, prompts, and widgets using mcp-use.
⚠️ FIRST: New Project or Existing Project?
Before doing anything else, determine whether you are inside an existing mcp-use project.
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".
├─ mcp-use project FOUND → Do NOT scaffold. You are already in a project.
│ └─ Skip to "Quick Navigation" below to add features.
│
├─ NO mcp-use project (empty dir, unrelated project, or greenfield)
│ └─ Scaffold first with npx create-mcp-use-app, then add features.
│ See "Scaffolding a New Project" below.
│
└─ Inside an UNRELATED project (e.g. Next.js app) and user wants an MCP server
└─ Ask the user where to create it, then scaffold in that directory.
Do NOT scaffold inside an existing unrelated project root.
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.
Scaffolding a New Project
npx create-mcp-use-app my-server
cd my-server
npm run dev
For full scaffolding details and CLI flags, see quickstart.md.
Quick Navigation
Choose your path based on what you're building:
🚀 Foundations
When: ALWAYS read these first when starting MCP work in a new conversation. Reference later for architecture/concept clarification.
- concepts.md - MCP primitives (Tool, Resource, Prompt, Widget) and when to use each
- architecture.md - Server structure (Hono-based), middleware system, server.use() vs server.app
- quickstart.md - Scaffolding, setup, and first tool example
- deployment.md - Deploying to Manufact Cloud, self-hosting, Docker, managing deployments
Load these before diving into tools/resources/widgets sections.
🔐 Adding Authentication?
When: Protecting your server with OAuth (WorkOS, Supabase, or custom)
overview.md
- When: First time adding auth, understanding
ctx.auth, or choosing a provider
- Covers:
oauth config, user context shape, provider comparison, common mistakes
workos.md
- When: Using WorkOS AuthKit for authentication
- Covers: Setup, env vars, DCR vs pre-registered, roles/permissions, WorkOS API calls
supabase.md
- When: Using Supabase for authentication
- Covers: Setup, env vars, HS256 vs ES256, RLS-aware API calls
custom.md
- When: Using any other identity provider (GitHub, Okta, Azure AD, Google, etc.)
- Covers: Custom verification, user info extraction, provider examples
🔧 Building Server Backend (No UI)?
When: Implementing MCP features (actions, data, templates). Read the specific file for the primitive you're building.
tools.md
- When: Creating backend actions the AI can call (send-email, fetch-data, create-user)
- Covers: Tool definition, schemas, annotations, context, error handling
resources.md
- When: Exposing read-only data clients can fetch (config, user profiles, documentation)
- Covers: Static resources, dynamic resources, parameterized resource templates, URI completion
prompts.md
- When: Creating reusable message templates for AI interactions (code-review, summarize)
- Covers: Prompt definition, parameterization, argument completion, prompt best practices
response-helpers.md
- When: Formatting responses from tools/resources (text, JSON, markdown, images, errors)
- Covers:
text(), object(), markdown(), image(), error(), mix()
🎨 Building Visual Widgets (Interactive UI)?
When: Creating React-based visual interfaces for browsing, comparing, or selecting data
basics.md
- When: Creating your first widget or adding UI to an existing tool
- Covers: Widget setup,
useWidget() hook, isPending checks, props handling
state.md
- When: Managing UI state (selections, filters, tabs) within widgets
- Covers:
useState, setState, state persistence, when to use tool vs widget state
interactivity.md
- When: Adding buttons, forms, or calling tools from within widgets
- Covers:
useCallTool(), form handling, action buttons, optimistic updates
ui-guidelines.md
- When: Styling widgets to support themes, responsive layouts, or accessibility
- Covers:
useWidgetTheme(), light/dark mode, autoSize, layout patterns, CSS best practices
advanced.md
- When: Building complex widgets with async data, error boundaries, or performance optimizations
- Covers: Loading states, error handling, memoization, code splitting
📚 Need Complete Examples?
When: You want to see full implementations of common use cases
- common-patterns.md
- End-to-end examples: weather app, todo list, recipe browser
- Shows: Server code + widget code + best practices in context
Decision Tree
What do you need?
├─ New project from scratch
│ └─> quickstart.md (scaffolding + setup)
│
├─ OAuth / user authentication
│ └─> authentication/overview.md → provider-specific guide
│
├─ Simple backend action (no UI)
│ └─> Use Tool: server/tools.md
│
├─ Read-only data for clients
│ └─> Use Resource: server/resources.md
│
├─ Reusable prompt template
│ └─> Use Prompt: server/prompts.md
│
├─ Visual/interactive UI
│ └─> Use Widget: widgets/basics.md
│
└─ Deploy to production
└─> deployment.md (cloud deploy, self-hosting, Docker)
Core Principles
- Tools for actions - Backend operations with input/output
- Resources for data - Read-only data clients can fetch
- Prompts for templates - Reusable message templates
- Widgets for UI - Visual interfaces when helpful
- Mock data first - Prototype quickly, connect APIs later
❌ Common Mistakes
Avoid these anti-patterns found in production MCP servers:
Tool Definition
- ❌ Returning raw objects instead of using response helpers
- ✅ Use
text(), object(), widget(), error() helpers
- ❌ Skipping Zod schema
.describe() on every field
- ✅ Add descriptions to all schema fields for better AI understanding
- ❌ No input validation or sanitization
- ✅ Validate inputs with Zod, sanitize user-provided data
- ❌ Throwing errors instead of returning
error() helper
- ✅ Use
error("message") for graceful error responses
Widget Development
- ❌ Accessing
props without checking isPending
- ✅ Always check
if (isPending) return <Loading/>
- ❌ Widget handles server state (filters, selections)
- ✅ Widgets manage their own UI state with
useState
- ❌ Missing
McpUseProvider wrapper or autoSize
- ✅ Wrap root component:
<McpUseProvider autoSize>
- ❌ Inline styles without theme awareness
- ✅ Use
useWidgetTheme() for light/dark mode support
Security & Production
- ❌ Hardcoded API keys or secrets in code
- ✅ Use
process.env.API_KEY, document in .env.example
- ❌ No error handling in tool handlers
- ✅ Wrap in try/catch, return
error() on failure
- ❌ Expensive operations without caching
- ✅ Cache API calls, computations with TTL
- ❌ Missing CORS configuration
- ✅ Configure CORS for production deployments
🔒 Golden Rules
Opinionated architectural guidelines:
1. One Tool = One Capability
Split broad actions into focused tools:
- ❌
manage-users (too vague)
- ✅
create-user, delete-user, list-users
2. Return Complete Data Upfront
Tool calls are expensive. Avoid lazy-loading:
- ❌
list-products + get-product-details (2 calls)
- ✅
list-products returns full data including details
3. Widgets Own Their State
UI state lives in the widget, not in separate tools:
- ❌
select-item tool, set-filter tool
- ✅ Widget manages with
useState or setState
4. exposeAsTool Defaults to false
Widgets are registered as resources only by default. Use a custom tool (recommended) or set exposeAsTool: true to expose a widget to the model:
// ✅ ALL 4 STEPS REQUIRED for proper type inference:
// Step 1: Define schema separately
const propsSchema = z.object({
title: z.string(),
items: z.array(z.string())
});
// Step 2: Reference schema variable in metadata
export const widgetMetadata: WidgetMetadata = {
description: "...",
props: propsSchema, // ← NOT inline z.object()
exposeAsTool: false
};
// Step 3: Infer Props type from schema variable
type Props = z.infer<typeof propsSchema>;
// Step 4: Use typed Props with useWidget
export default function MyWidget() {
const { props, isPending } = useWidget<Props>(); // ← Add <Props>
// ...
}
⚠️ Common mistake: Only doing steps 1-2 but skipping 3-4 (loses type safety)
5. Validate at Boundaries Only
- Trust internal code and framework guarantees
- Validate user input, external API responses
- Don't add error handling for scenarios that can't happen
6. Prefer Widgets for Browsing/Comparing
When in doubt, add a widget. Visual UI improves:
- Browsing multiple items
- Comparing data side-by-side
- Interactive selection workflows
Quick Reference
Minimal Server
import { MCPServer, text } from "mcp-use/server";
import { z } from "zod";
const server = new MCPServer({
name: "my-server",
title: "My Server",
version: "1.0.0"
});
server.tool(
{
name: "greet",
description: "Greet a user",
schema: z.object({ name: z.string().describe("User's name") })
},
async ({ name }) => text("Hello " + name + "!"),
);
server.listen();
Response Helpers
| Helper |
Use When |
Example |
text() |
Simple string response |
text("Success!") |
object() |
Structured data |
object({ status: "ok" }) |
markdown() |
Formatted text |
markdown("# Title\nContent") |
widget() |
Visual UI |
widget({ props: {...}, output: text(...) }) |
mix() |
Multiple contents |
mix(text("Hi"), image(url)) |
error() |
Error responses |
error("Failed to fetch data") |
resource() |
Embed resource refs |
resource("docs://guide", "text/markdown") |
1---2name: mcp-apps-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 widgets1314 This skill contains critical architecture decisions, security patterns, and common pitfalls.15 Always 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.50 Do 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 (WorkOS, Supabase, or custom)8788- **[overview.md](references/authentication/overview.md)**89 - When: First time adding auth, understanding `ctx.auth`, or choosing a provider90 - Covers: `oauth` config, user context shape, provider comparison, common mistakes9192- **[workos.md](references/authentication/workos.md)**93 - When: Using WorkOS AuthKit for authentication94 - Covers: Setup, env vars, DCR vs pre-registered, roles/permissions, WorkOS API calls9596- **[supabase.md](references/authentication/supabase.md)**97 - When: Using Supabase for authentication98 - Covers: Setup, env vars, HS256 vs ES256, RLS-aware API calls99100- **[custom.md](references/authentication/custom.md)**101 - When: Using any other identity provider (GitHub, Okta, Azure AD, Google, etc.)102 - Covers: Custom verification, user info extraction, provider examples103104---105106### 🔧 Building Server Backend (No UI)?107**When:** Implementing MCP features (actions, data, templates). Read the specific file for the primitive you're building.108109- **[tools.md](references/server/tools.md)**110 - When: Creating backend actions the AI can call (send-email, fetch-data, create-user)111 - Covers: Tool definition, schemas, annotations, context, error handling112113- **[resources.md](references/server/resources.md)**114 - When: Exposing read-only data clients can fetch (config, user profiles, documentation)115 - Covers: Static resources, dynamic resources, parameterized resource templates, URI completion116117- **[prompts.md](references/server/prompts.md)**118 - When: Creating reusable message templates for AI interactions (code-review, summarize)119 - Covers: Prompt definition, parameterization, argument completion, prompt best practices120121- **[response-helpers.md](references/server/response-helpers.md)**122 - When: Formatting responses from tools/resources (text, JSON, markdown, images, errors)123 - Covers: `text()`, `object()`, `markdown()`, `image()`, `error()`, `mix()`124125---126127### 🎨 Building Visual Widgets (Interactive UI)?128**When:** Creating React-based visual interfaces for browsing, comparing, or selecting data129130- **[basics.md](references/widgets/basics.md)**131 - When: Creating your first widget or adding UI to an existing tool132 - Covers: Widget setup, `useWidget()` hook, `isPending` checks, props handling133134- **[state.md](references/widgets/state.md)**135 - When: Managing UI state (selections, filters, tabs) within widgets136 - Covers: `useState`, `setState`, state persistence, when to use tool vs widget state137138- **[interactivity.md](references/widgets/interactivity.md)**139 - When: Adding buttons, forms, or calling tools from within widgets140 - Covers: `useCallTool()`, form handling, action buttons, optimistic updates141142- **[ui-guidelines.md](references/widgets/ui-guidelines.md)**143 - When: Styling widgets to support themes, responsive layouts, or accessibility144 - Covers: `useWidgetTheme()`, light/dark mode, `autoSize`, layout patterns, CSS best practices145146- **[advanced.md](references/widgets/advanced.md)**147 - When: Building complex widgets with async data, error boundaries, or performance optimizations148 - Covers: Loading states, error handling, memoization, code splitting149150---151152### 📚 Need Complete Examples?153**When:** You want to see full implementations of common use cases154155- **[common-patterns.md](references/patterns/common-patterns.md)**156 - End-to-end examples: weather app, todo list, recipe browser157 - Shows: Server code + widget code + best practices in context158159---160161## Decision Tree162163```164What do you need?165166├─ New project from scratch167│ └─> quickstart.md (scaffolding + setup)168│169├─ OAuth / user authentication170│ └─> authentication/overview.md → provider-specific guide171│172├─ Simple backend action (no UI)173│ └─> Use Tool: server/tools.md174│175├─ Read-only data for clients176│ └─> Use Resource: server/resources.md177│178├─ Reusable prompt template179│ └─> Use Prompt: server/prompts.md180│181├─ Visual/interactive UI182│ └─> Use Widget: widgets/basics.md183│184└─ Deploy to production185 └─> deployment.md (cloud deploy, self-hosting, Docker)186```187188---189190## Core Principles1911921. **Tools for actions** - Backend operations with input/output1932. **Resources for data** - Read-only data clients can fetch1943. **Prompts for templates** - Reusable message templates1954. **Widgets for UI** - Visual interfaces when helpful1965. **Mock data first** - Prototype quickly, connect APIs later197198---199200## ❌ Common Mistakes201202Avoid these anti-patterns found in production MCP servers:203204### Tool Definition205- ❌ Returning raw objects instead of using response helpers206 - ✅ Use `text()`, `object()`, `widget()`, `error()` helpers207- ❌ Skipping Zod schema `.describe()` on every field208 - ✅ Add descriptions to all schema fields for better AI understanding209- ❌ No input validation or sanitization210 - ✅ Validate inputs with Zod, sanitize user-provided data211- ❌ Throwing errors instead of returning `error()` helper212 - ✅ Use `error("message")` for graceful error responses213214### Widget Development215- ❌ Accessing `props` without checking `isPending`216 - ✅ Always check `if (isPending) return <Loading/>`217- ❌ Widget handles server state (filters, selections)218 - ✅ Widgets manage their own UI state with `useState`219- ❌ Missing `McpUseProvider` wrapper or `autoSize`220 - ✅ Wrap root component: `<McpUseProvider autoSize>`221- ❌ Inline styles without theme awareness222 - ✅ Use `useWidgetTheme()` for light/dark mode support223224### Security & Production225- ❌ Hardcoded API keys or secrets in code226 - ✅ Use `process.env.API_KEY`, document in `.env.example`227- ❌ No error handling in tool handlers228 - ✅ Wrap in try/catch, return `error()` on failure229- ❌ Expensive operations without caching230 - ✅ Cache API calls, computations with TTL231- ❌ Missing CORS configuration232 - ✅ Configure CORS for production deployments233234---235236## 🔒 Golden Rules237238**Opinionated architectural guidelines:**239240### 1. One Tool = One Capability241Split broad actions into focused tools:242- ❌ `manage-users` (too vague)243- ✅ `create-user`, `delete-user`, `list-users`244245### 2. Return Complete Data Upfront246Tool calls are expensive. Avoid lazy-loading:247- ❌ `list-products` + `get-product-details` (2 calls)248- ✅ `list-products` returns full data including details249250### 3. Widgets Own Their State251UI state lives in the widget, not in separate tools:252- ❌ `select-item` tool, `set-filter` tool253- ✅ Widget manages with `useState` or `setState`254255### 4. `exposeAsTool` Defaults to `false`256Widgets are registered as resources only by default. Use a custom tool (recommended) or set `exposeAsTool: true` to expose a widget to the model:257258```typescript259// ✅ ALL 4 STEPS REQUIRED for proper type inference:260261// Step 1: Define schema separately262const propsSchema = z.object({263 title: z.string(),264 items: z.array(z.string())265});266267// Step 2: Reference schema variable in metadata268export const widgetMetadata: WidgetMetadata = {269 description: "...",270 props: propsSchema, // ← NOT inline z.object()271 exposeAsTool: false272};273274// Step 3: Infer Props type from schema variable275type Props = z.infer<typeof propsSchema>;276277// Step 4: Use typed Props with useWidget278export default function MyWidget() {279 const { props, isPending } = useWidget<Props>(); // ← Add <Props>280 // ...281}282```283284⚠️ **Common mistake:** Only doing steps 1-2 but skipping 3-4 (loses type safety)285286### 5. Validate at Boundaries Only287- Trust internal code and framework guarantees288- Validate user input, external API responses289- Don't add error handling for scenarios that can't happen290291### 6. Prefer Widgets for Browsing/Comparing292When in doubt, add a widget. Visual UI improves:293- Browsing multiple items294- Comparing data side-by-side295- Interactive selection workflows296297---298299## Quick Reference300301### Minimal Server302```typescript303import { MCPServer, text } from "mcp-use/server";304import { z } from "zod";305306const server = new MCPServer({307 name: "my-server",308 title: "My Server",309 version: "1.0.0"310});311312server.tool(313 {314 name: "greet",315 description: "Greet a user",316 schema: z.object({ name: z.string().describe("User's name") })317 },318 async ({ name }) => text("Hello " + name + "!"),319);320321server.listen();322```323324---325326## Response Helpers327328| Helper | Use When | Example |329|--------|----------|---------|330| `text()` | Simple string response | `text("Success!")` |331| `object()` | Structured data | `object({ status: "ok" })` |332| `markdown()` | Formatted text | `markdown("# Title\nContent")` |333| `widget()` | Visual UI | `widget({ props: {...}, output: text(...) })` |334| `mix()` | Multiple contents | `mix(text("Hi"), image(url))` |335| `error()` | Error responses | `error("Failed to fetch data")` |336| `resource()` | Embed resource refs | `resource("docs://guide", "text/markdown")` |337