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 (Auth0, Better Auth, Clerk, WorkOS, Supabase, Keycloak, or any other provider)
overview.md
- When: First time adding auth, understanding
ctx.auth, or choosing a provider / integration mode
- Covers: Remote auth vs OAuth proxy,
oauth config, ctx.auth shape, provider comparison, common mistakes
auth0.md
- When: Using Auth0 — DCR (Early Access) or a standard Regular Web App via
oauthProxy
- Covers: Setup for both modes,
extraAuthorizeParams.audience, permissions via rfc9068_profile_authz
better-auth.md
- When: Using Better Auth with the
@better-auth/oauth-provider plugin (self-hosted OAuth 2.1)
- Covers:
oauthBetterAuthProvider, auth URL / metadata routes, login and consent flows
clerk.md
- When: Using Clerk (DCR-based OAuth)
- Covers:
oauthClerkProvider, enabling DCR, Frontend API URL, organization context
workos.md
- When: Using WorkOS AuthKit (DCR only)
- Covers: Setup, env vars, roles/permissions, multi-tenant org filtering, WorkOS API calls
supabase.md
- When: Using Supabase's OAuth 2.1 server
- Covers: Setup, publishable keys, ES256 vs HS256, hosting the consent UI, RLS-aware SDK calls
keycloak.md
- When: Using Keycloak via native DCR
- Covers: DCR trusted hosts + web origins, audience enforcement, realm vs resource roles, userinfo
custom.md
- When: Any other provider — DCR-capable via
oauthCustomProvider, or pre-registered (Google, GitHub, Okta, Azure AD) via oauthProxy
- Covers:
oauthCustomProvider, oauthProxy + jwksVerifier, provider examples, opaque-token verification
🔧 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()
proxy.md
- When: Composing multiple MCP servers into one unified aggregator server
- Covers:
server.proxy(), config API, explicit sessions, sampling routing
architecture.md
- When: Adding cross-cutting logic (logging, auth checks, rate limiting, tool filtering) that spans multiple tools/resources
- Covers:
server.use('mcp:...') middleware, MiddlewareContext (method, params, auth, state), pattern matching, HTTP vs MCP middleware
🎨 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
model-context.md
- When: Keeping the AI model aware of what the user is currently seeing (active tab, hovered item, selected product) without requiring tool calls
- Covers:
<ModelContext> component, modelContext.set/remove imperative API, nesting, tree serialization, lifecycle rules
files.md
- When: Uploading or downloading files from within a widget (ChatGPT Apps SDK only)
- Covers:
useFiles() hook, isSupported guard, model visibility (modelVisible), storing fileId, temporary download URLs
📚 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
🔁 Testing from the Terminal (Agent Feedback Loops)
When: You want to verify a tool or widget without the inspector UI — the canonical flow for AI agents iterating on MCP servers.
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.
npx mcp-use client connect dev http://localhost:3000/mcp
npx mcp-use client dev tools list
npx mcp-use client dev tools call get-weather city=Tokyo --screenshot
Every 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>).
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:
# Saved-server form — reuses the auth from `mcp-use client connect`
npx mcp-use client dev screenshot --tool get-weather city=Tokyo \
--width 800 --height 600 --theme light \
--output ./weather.png
# Ad-hoc form — connect inline (use -H for headers on authenticated servers)
npx mcp-use client screenshot --mcp http://localhost:3000/mcp \
--tool get-weather city=Tokyo
Add --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.
Both commands are documented in full at docs/typescript/client/cli.
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
│
├─ Cross-cutting logic (logging, auth checks, rate limiting, tool filtering)
│ └─> Use Middleware: architecture.md#mcp-middleware
│
├─ Visual/interactive UI
│ └─> Use Widget: widgets/basics.md
│
├─ Keep model aware of what user is seeing in widget
│ └─> widgets/model-context.md
├─ Upload/download files in a widget
│ └─> widgets/files.md (ChatGPT Apps SDK only)
│
├─ Verify a tool or widget from the terminal (agent feedback loop)
│ └─> See "Testing from the Terminal" above — `mcp-use client` for tool runs,
│ `mcp-use client <server> screenshot --tool <tool>` for headless widget PNGs
│
└─ 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") |
Server methods:
server.tool() - Define executable tool
server.resource() - Define static/dynamic resource
server.resourceTemplate() - Define parameterized resource
server.prompt() - Define prompt template
server.proxy() - Compose/Proxy multiple MCP servers
server.uiResource() - Define widget resource
server.listen() - Start server
server.use('mcp:tools/call', fn) - MCP middleware (tools, resources, prompts, list ops)
server.use('mcp:*', fn) - Catch-all MCP middleware
server.use(fn) - HTTP middleware (Hono)
1---2name: mcp-apps-builder3description: **MANDATORY for ALL MCP server work** - mcp-use framework best practices and patterns. **READ THIS FIRST** before any MCP server work, including: - Creating new MCP servers - Modifying existing MCP servers (adding/updating tools, resources, prompts, widgets) - Debugging MCP server issues or errors - Reviewing MCP server code for quality, security, or performance - Answering questions about MCP development or mcp-use patterns - Making ANY changes to server.tool(), server.resource(), server.prompt(), or widgets This skill contains critical architecture decisions, security patterns, and common pitfalls. Always consult the relevant reference files BEFORE implementing MCP features.4---5
6# IMPORTANT: How to Use This Skill
7
8This file provides a NAVIGATION GUIDE ONLY. Before implementing any MCP server features, you MUST:
9
101. Read this overview to understand which reference files are relevant
112. **ALWAYS read the specific reference file(s)** for the features you're implementing
123. Apply the detailed patterns from those files to your implementation
13
14**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.
15
16---
17
18# MCP Server Best Practices
19
20Comprehensive guide for building production-ready MCP servers with tools, resources, prompts, and widgets using mcp-use.
21
22## ⚠️ FIRST: New Project or Existing Project?
23
24**Before doing anything else, determine whether you are inside an existing mcp-use project.**
25
26**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"`.
27
28```
29├─ mcp-use project FOUND → Do NOT scaffold. You are already in a project.
30│ └─ Skip to "Quick Navigation" below to add features.
31│
32├─ NO mcp-use project (empty dir, unrelated project, or greenfield)
33│ └─ Scaffold first with npx create-mcp-use-app, then add features.
34│ See "Scaffolding a New Project" below.
35│
36└─ Inside an UNRELATED project (e.g. Next.js app) and user wants an MCP server
37 └─ Ask the user where to create it, then scaffold in that directory.
38 Do NOT scaffold inside an existing unrelated project root.
39```
40
41**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.
42
43---
44
45### Scaffolding a New Project
46
47```bash
48npx create-mcp-use-app my-server
49cd my-server
50npm run dev
51```
52
53For full scaffolding details and CLI flags, see **[quickstart.md](references/foundations/quickstart.md)**.
54
55---
56
57## Quick Navigation
58
59**Choose your path based on what you're building:**
60
61### 🚀 Foundations
62**When:** ALWAYS read these first when starting MCP work in a new conversation. Reference later for architecture/concept clarification.
63
641. **[concepts.md](references/foundations/concepts.md)** - MCP primitives (Tool, Resource, Prompt, Widget) and when to use each
652. **[architecture.md](references/foundations/architecture.md)** - Server structure (Hono-based), middleware system, server.use() vs server.app
663. **[quickstart.md](references/foundations/quickstart.md)** - Scaffolding, setup, and first tool example
674. **[deployment.md](references/foundations/deployment.md)** - Deploying to Manufact Cloud, self-hosting, Docker, managing deployments
68
69Load these before diving into tools/resources/widgets sections.
70
71---
72
73### 🔐 Adding Authentication?
74**When:** Protecting your server with OAuth (Auth0, Better Auth, Clerk, WorkOS, Supabase, Keycloak, or any other provider)
75
76- **[overview.md](references/authentication/overview.md)**
77 - When: First time adding auth, understanding `ctx.auth`, or choosing a provider / integration mode
78 - Covers: Remote auth vs OAuth proxy, `oauth` config, `ctx.auth` shape, provider comparison, common mistakes
79
80- **[auth0.md](references/authentication/auth0.md)**
81 - When: Using Auth0 — DCR (Early Access) or a standard Regular Web App via `oauthProxy`
82 - Covers: Setup for both modes, `extraAuthorizeParams.audience`, permissions via `rfc9068_profile_authz`
83
84- **[better-auth.md](references/authentication/better-auth.md)**
85 - When: Using Better Auth with the `@better-auth/oauth-provider` plugin (self-hosted OAuth 2.1)
86 - Covers: `oauthBetterAuthProvider`, auth URL / metadata routes, login and consent flows
87
88- **[clerk.md](references/authentication/clerk.md)**
89 - When: Using Clerk (DCR-based OAuth)
90 - Covers: `oauthClerkProvider`, enabling DCR, Frontend API URL, organization context
91
92- **[workos.md](references/authentication/workos.md)**
93 - When: Using WorkOS AuthKit (DCR only)
94 - Covers: Setup, env vars, roles/permissions, multi-tenant org filtering, WorkOS API calls
95
96- **[supabase.md](references/authentication/supabase.md)**
97 - When: Using Supabase's OAuth 2.1 server
98 - Covers: Setup, publishable keys, ES256 vs HS256, hosting the consent UI, RLS-aware SDK calls
99
100- **[keycloak.md](references/authentication/keycloak.md)**
101 - When: Using Keycloak via native DCR
102 - Covers: DCR trusted hosts + web origins, audience enforcement, realm vs resource roles, userinfo
103
104- **[custom.md](references/authentication/custom.md)**
105 - When: Any other provider — DCR-capable via `oauthCustomProvider`, or pre-registered (Google, GitHub, Okta, Azure AD) via `oauthProxy`
106 - Covers: `oauthCustomProvider`, `oauthProxy` + `jwksVerifier`, provider examples, opaque-token verification
107
108---
109
110### 🔧 Building Server Backend (No UI)?
111**When:** Implementing MCP features (actions, data, templates). Read the specific file for the primitive you're building.
112
113- **[tools.md](references/server/tools.md)**
114 - When: Creating backend actions the AI can call (send-email, fetch-data, create-user)
115 - Covers: Tool definition, schemas, annotations, context, error handling
116
117- **[resources.md](references/server/resources.md)**
118 - When: Exposing read-only data clients can fetch (config, user profiles, documentation)
119 - Covers: Static resources, dynamic resources, parameterized resource templates, URI completion
120
121- **[prompts.md](references/server/prompts.md)**
122 - When: Creating reusable message templates for AI interactions (code-review, summarize)
123 - Covers: Prompt definition, parameterization, argument completion, prompt best practices
124
125- **[response-helpers.md](references/server/response-helpers.md)**
126 - When: Formatting responses from tools/resources (text, JSON, markdown, images, errors)
127 - Covers: `text()`, `object()`, `markdown()`, `image()`, `error()`, `mix()`
128
129- **[proxy.md](references/server/proxy.md)**
130 - When: Composing multiple MCP servers into one unified aggregator server
131 - Covers: `server.proxy()`, config API, explicit sessions, sampling routing
132
133- **[architecture.md](references/foundations/architecture.md)**
134 - When: Adding cross-cutting logic (logging, auth checks, rate limiting, tool filtering) that spans multiple tools/resources
135 - Covers: `server.use('mcp:...')` middleware, `MiddlewareContext` (method, params, auth, state), pattern matching, HTTP vs MCP middleware
136
137---
138
139### 🎨 Building Visual Widgets (Interactive UI)?
140**When:** Creating React-based visual interfaces for browsing, comparing, or selecting data
141
142- **[basics.md](references/widgets/basics.md)**
143 - When: Creating your first widget or adding UI to an existing tool
144 - Covers: Widget setup, `useWidget()` hook, `isPending` checks, props handling
145
146- **[state.md](references/widgets/state.md)**
147 - When: Managing UI state (selections, filters, tabs) within widgets
148 - Covers: `useState`, `setState`, state persistence, when to use tool vs widget state
149
150- **[interactivity.md](references/widgets/interactivity.md)**
151 - When: Adding buttons, forms, or calling tools from within widgets
152 - Covers: `useCallTool()`, form handling, action buttons, optimistic updates
153
154- **[ui-guidelines.md](references/widgets/ui-guidelines.md)**
155 - When: Styling widgets to support themes, responsive layouts, or accessibility
156 - Covers: `useWidgetTheme()`, light/dark mode, `autoSize`, layout patterns, CSS best practices
157
158- **[advanced.md](references/widgets/advanced.md)**
159 - When: Building complex widgets with async data, error boundaries, or performance optimizations
160 - Covers: Loading states, error handling, memoization, code splitting
161
162- **[model-context.md](references/widgets/model-context.md)**
163 - When: Keeping the AI model aware of what the user is currently seeing (active tab, hovered item, selected product) without requiring tool calls
164 - Covers: `<ModelContext>` component, `modelContext.set/remove` imperative API, nesting, tree serialization, lifecycle rules
165- **[files.md](references/widgets/files.md)**
166 - When: Uploading or downloading files from within a widget (ChatGPT Apps SDK only)
167 - Covers: `useFiles()` hook, `isSupported` guard, model visibility (`modelVisible`), storing `fileId`, temporary download URLs
168
169---
170
171### 📚 Need Complete Examples?
172**When:** You want to see full implementations of common use cases
173
174- **[common-patterns.md](references/patterns/common-patterns.md)**
175 - End-to-end examples: weather app, todo list, recipe browser
176 - Shows: Server code + widget code + best practices in context
177
178---
179
180### 🔁 Testing from the Terminal (Agent Feedback Loops)
181**When:** You want to verify a tool or widget *without* the inspector UI — the canonical flow for AI agents iterating on MCP servers.
182
183- **`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.
184
185 ```bash
186 npx mcp-use client connect dev http://localhost:3000/mcp
187 npx mcp-use client dev tools list
188 npx mcp-use client dev tools call get-weather city=Tokyo --screenshot
189 ```
190
191 Every 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>`).
192
193- **`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:
194
195 ```bash
196 # Saved-server form — reuses the auth from `mcp-use client connect`
197 npx mcp-use client dev screenshot --tool get-weather city=Tokyo \
198 --width 800 --height 600 --theme light \
199 --output ./weather.png
200
201 # Ad-hoc form — connect inline (use -H for headers on authenticated servers)
202 npx mcp-use client screenshot --mcp http://localhost:3000/mcp \
203 --tool get-weather city=Tokyo
204 ```
205
206 Add `--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.
207
208Both commands are documented in full at [docs/typescript/client/cli](https://docs.mcp-use.com/typescript/client/cli).
209
210---
211
212## Decision Tree
213
214```
215What do you need?
216
217├─ New project from scratch
218│ └─> quickstart.md (scaffolding + setup)
219│
220├─ OAuth / user authentication
221│ └─> authentication/overview.md → provider-specific guide
222│
223├─ Simple backend action (no UI)
224│ └─> Use Tool: server/tools.md
225│
226├─ Read-only data for clients
227│ └─> Use Resource: server/resources.md
228│
229├─ Reusable prompt template
230│ └─> Use Prompt: server/prompts.md
231│
232├─ Cross-cutting logic (logging, auth checks, rate limiting, tool filtering)
233│ └─> Use Middleware: architecture.md#mcp-middleware
234│
235├─ Visual/interactive UI
236│ └─> Use Widget: widgets/basics.md
237│
238├─ Keep model aware of what user is seeing in widget
239│ └─> widgets/model-context.md
240├─ Upload/download files in a widget
241│ └─> widgets/files.md (ChatGPT Apps SDK only)
242│
243├─ Verify a tool or widget from the terminal (agent feedback loop)
244│ └─> See "Testing from the Terminal" above — `mcp-use client` for tool runs,
245│ `mcp-use client <server> screenshot --tool <tool>` for headless widget PNGs
246│
247└─ Deploy to production
248 └─> deployment.md (cloud deploy, self-hosting, Docker)
249```
250
251---
252
253## Core Principles
254
2551. **Tools for actions** - Backend operations with input/output
2562. **Resources for data** - Read-only data clients can fetch
2573. **Prompts for templates** - Reusable message templates
2584. **Widgets for UI** - Visual interfaces when helpful
2595. **Mock data first** - Prototype quickly, connect APIs later
260
261---
262
263## ❌ Common Mistakes
264
265Avoid these anti-patterns found in production MCP servers:
266
267### Tool Definition
268- ❌ Returning raw objects instead of using response helpers
269 - ✅ Use `text()`, `object()`, `widget()`, `error()` helpers
270- ❌ Skipping Zod schema `.describe()` on every field
271 - ✅ Add descriptions to all schema fields for better AI understanding
272- ❌ No input validation or sanitization
273 - ✅ Validate inputs with Zod, sanitize user-provided data
274- ❌ Throwing errors instead of returning `error()` helper
275 - ✅ Use `error("message")` for graceful error responses
276
277### Widget Development
278- ❌ Accessing `props` without checking `isPending`
279 - ✅ Always check `if (isPending) return <Loading/>`
280- ❌ Widget handles server state (filters, selections)
281 - ✅ Widgets manage their own UI state with `useState`
282- ❌ Missing `McpUseProvider` wrapper or `autoSize`
283 - ✅ Wrap root component: `<McpUseProvider autoSize>`
284- ❌ Inline styles without theme awareness
285 - ✅ Use `useWidgetTheme()` for light/dark mode support
286
287### Security & Production
288- ❌ Hardcoded API keys or secrets in code
289 - ✅ Use `process.env.API_KEY`, document in `.env.example`
290- ❌ No error handling in tool handlers
291 - ✅ Wrap in try/catch, return `error()` on failure
292- ❌ Expensive operations without caching
293 - ✅ Cache API calls, computations with TTL
294- ❌ Missing CORS configuration
295 - ✅ Configure CORS for production deployments
296
297---
298
299## 🔒 Golden Rules
300
301**Opinionated architectural guidelines:**
302
303### 1. One Tool = One Capability
304Split broad actions into focused tools:
305- ❌ `manage-users` (too vague)
306- ✅ `create-user`, `delete-user`, `list-users`
307
308### 2. Return Complete Data Upfront
309Tool calls are expensive. Avoid lazy-loading:
310- ❌ `list-products` + `get-product-details` (2 calls)
311- ✅ `list-products` returns full data including details
312
313### 3. Widgets Own Their State
314UI state lives in the widget, not in separate tools:
315- ❌ `select-item` tool, `set-filter` tool
316- ✅ Widget manages with `useState` or `setState`
317
318### 4. `exposeAsTool` Defaults to `false`
319Widgets are registered as resources only by default. Use a custom tool (recommended) or set `exposeAsTool: true` to expose a widget to the model:
320
321```typescript
322// ✅ ALL 4 STEPS REQUIRED for proper type inference:
323
324// Step 1: Define schema separately
325const propsSchema = z.object({
326 title: z.string(),
327 items: z.array(z.string())
328});
329
330// Step 2: Reference schema variable in metadata
331export const widgetMetadata: WidgetMetadata = {
332 description: "...",
333 props: propsSchema, // ← NOT inline z.object()
334 exposeAsTool: false
335};
336
337// Step 3: Infer Props type from schema variable
338type Props = z.infer<typeof propsSchema>;
339
340// Step 4: Use typed Props with useWidget
341export default function MyWidget() {
342 const { props, isPending } = useWidget<Props>(); // ← Add <Props>
343 // ...
344}
345```
346
347⚠️ **Common mistake:** Only doing steps 1-2 but skipping 3-4 (loses type safety)
348
349### 5. Validate at Boundaries Only
350- Trust internal code and framework guarantees
351- Validate user input, external API responses
352- Don't add error handling for scenarios that can't happen
353
354### 6. Prefer Widgets for Browsing/Comparing
355When in doubt, add a widget. Visual UI improves:
356- Browsing multiple items
357- Comparing data side-by-side
358- Interactive selection workflows
359
360---
361
362## Quick Reference
363
364### Minimal Server
365```typescript
366import { MCPServer, text } from "mcp-use/server";
367import { z } from "zod";
368
369const server = new MCPServer({
370 name: "my-server",
371 title: "My Server",
372 version: "1.0.0"
373});
374
375server.tool(
376 {
377 name: "greet",
378 description: "Greet a user",
379 schema: z.object({ name: z.string().describe("User's name") })
380 },
381 async ({ name }) => text("Hello " + name + "!"),
382);
383
384server.listen();
385```
386
387---
388
389## Response Helpers
390
391| Helper | Use When | Example |
392|--------|----------|---------|
393| `text()` | Simple string response | `text("Success!")` |
394| `object()` | Structured data | `object({ status: "ok" })` |
395| `markdown()` | Formatted text | `markdown("# Title\nContent")` |
396| `widget()` | Visual UI | `widget({ props: {...}, output: text(...) })` |
397| `mix()` | Multiple contents | `mix(text("Hi"), image(url))` |
398| `error()` | Error responses | `error("Failed to fetch data")` |
399| `resource()` | Embed resource refs | `resource("docs://guide", "text/markdown")` |
400
401**Server methods:**
402- `server.tool()` - Define executable tool
403- `server.resource()` - Define static/dynamic resource
404- `server.resourceTemplate()` - Define parameterized resource
405- `server.prompt()` - Define prompt template
406- `server.proxy()` - Compose/Proxy multiple MCP servers
407- `server.uiResource()` - Define widget resource
408- `server.listen()` - Start server
409- `server.use('mcp:tools/call', fn)` - MCP middleware (tools, resources, prompts, list ops)
410- `server.use('mcp:*', fn)` - Catch-all MCP middleware
411- `server.use(fn)` - HTTP middleware (Hono)
412
413