API Reference
This document provides a complete reference for the mcp-use/server API, including all classes, methods, and type definitions.
Server Creation
MCPServer Class
Creates a new MCP server instance with built-in HTTP routing and MCP transport support.
class MCPServer {
constructor(config: ServerConfig): McpServerInstance
}
Parameters:
config (ServerConfig) - Server configuration object (name is required in config)
Returns: McpServerInstance - Server instance with MCP server methods plus route/middleware helpers
Example:
// Basic usage
const server = new MCPServer({
name: 'my-server',
version: '1.0.0',
description: 'My MCP server'
})
// With custom host (e.g., for Docker or remote access)
const server = new MCPServer({
name: 'my-server',
version: '1.0.0',
host: '0.0.0.0' // or 'myserver.com'
})
// With full base URL (e.g., behind a proxy or custom domain)
const server = new MCPServer({
name: 'my-server',
version: '1.0.0',
baseUrl: 'https://myserver.com' // or process.env.MCP_URL
})
// Production with explicit allowed origins
const server = new MCPServer({
name: 'my-server',
version: '1.0.0',
allowedOrigins: [
'https://myapp.com',
'https://app.myapp.com'
]
})
// With server metadata (title, icons, website)
const server = new MCPServer({
name: 'my-server',
title: 'My Server', // display name
version: '1.0.0',
description: 'My awesome MCP server',
baseUrl: process.env.MCP_URL || 'http://localhost:3000',
websiteUrl: 'https://mcp-use.com',
favicon: 'favicon.ico',
icons: [
{
src: 'icon.svg',
mimeType: 'image/svg+xml',
sizes: ['512x512']
}
]
})
Note: The createMCPServer() factory function is still available for backward compatibility, but the class constructor is recommended for new code.
Server Metadata: When you use create-mcp-use-app, these fields are automatically configured with your project name and mcp-use branding icons. The icons[].src paths are automatically converted to absolute URLs using your baseUrl.
Server Configuration
ServerConfig
Configuration object for server initialization.
interface ServerConfig {
name: string // Server identifier (e.g., 'my-server')
version: string // Server version (semver format)
description?: string // Server description
title?: string // display name - Human-readable title shown in MCP clients and Inspector
websiteUrl?: string // Website URL for documentation/homepage
icons?: Array<{ // Server icons for branding (displayed in Inspector and clients)
src: string // Icon URL or relative path (e.g., 'icon.svg')
mimeType?: string // MIME type (e.g., 'image/svg+xml', 'image/png')
sizes?: string[] // Icon sizes (e.g., ['512x512', '256x256'])
theme?: 'light' | 'dark' // Icon theme variant
}>
favicon?: string // Favicon path relative to public/ directory (e.g., 'favicon.ico')
host?: string // Hostname for widget URLs and server endpoints (defaults to 'localhost')
baseUrl?: string // Full base URL (e.g., 'https://myserver.com') - overrides host:port for widget URLs
cors?: {
// Hono CORS middleware options
origin?: string | string[] | ((origin: string, c: unknown) => string | null | Promise<string | null>)
allowMethods?: string[]
allowHeaders?: string[]
exposeHeaders?: string[]
maxAge?: number
credentials?: boolean
}
allowedOrigins?: string[] // Allowed origin values (normalized to hostnames for global Host validation)
sessionIdleTimeoutMs?: number // Idle timeout for sessions in milliseconds (default: 86400000 = 1 day)
autoCreateSessionOnInvalidId?: boolean // @deprecated Will be removed in a future version. Use sessionStore for persistent sessions.
}
allowedOrigins Configuration:
The allowedOrigins option controls DNS rebinding host validation:
-
Default behavior (
allowedOrigins not set):
- Host validation is disabled
- All
Host values are accepted
-
When
allowedOrigins is set:
- Values are normalized to hostnames and used as the Host allow list
- Validation applies across the whole server
-
When
allowedOrigins is empty:
- Host validation remains disabled
Example:
// Default behavior: host validation disabled
const server = new MCPServer({
name: 'my-server',
version: '1.0.0'
})
// Production: explicit allow list
const server = new MCPServer({
name: 'my-server',
version: '1.0.0',
allowedOrigins: [
'https://myapp.com',
'https://app.myapp.com'
]
})
Core Server Methods
Registers a tool that clients can invoke.
tool(definition: ToolDefinition): this
Parameters:
definition (ToolDefinition) - Tool configuration and handler
Returns: Server instance for method chaining
Example:
server.tool({
name: 'calculate',
description: 'Perform calculations',
schema: z.object({ expression: z.string().describe('The expression to evaluate') }),
}, async ({ expression }) => {
const result = eval(expression) // Note: Use safe evaluation in production
return text(`Result: ${result}`);
})
server.resource()
Registers a static resource that clients can read.
resource(definition: ResourceDefinition): this
Parameters:
definition (ResourceDefinition) - Resource configuration and content
Returns: Server instance for method chaining
Example:
server.resource({
name: 'config',
uri: 'config://settings',
title: 'Configuration',
mimeType: 'application/json',
description: 'Server configuration',
annotations: {
audience: ['user', 'assistant'],
priority: 0.8
},
readCallback: async () => ({
contents: [{
uri: 'config://settings',
mimeType: 'application/json',
text: JSON.stringify({ theme: 'dark' })
}]
})
})
server.resourceTemplate()
Registers a dynamic resource template with parameters.
resourceTemplate(definition: ResourceTemplateDefinition): this
Parameters:
definition (ResourceTemplateDefinition) - Template configuration
Returns: Server instance for method chaining
Example:
server.resourceTemplate({
name: 'user_profile',
resourceTemplate: {
uriTemplate: 'user://{userId}/profile',
name: 'User Profile',
mimeType: 'application/json',
description: 'User profile data'
},
readCallback: async (uri, params) => ({
contents: [{
uri: uri.toString(),
mimeType: 'application/json',
text: JSON.stringify({
userId: params.userId,
name: 'John Doe'
})
}]
})
})
server.prompt()
Registers a prompt template for AI models.
prompt(definition: PromptDefinition): this
Parameters:
definition (PromptDefinition) - Prompt configuration and generator
Returns: Server instance for method chaining
Example:
server.prompt({
name: 'code_review',
description: 'Generate code review prompt',
args: [
{ name: 'language', type: 'string', required: true },
{ name: 'focus', type: 'string', required: false }
],
cb: async ({ language, focus = 'general' }) => ({
messages: [
{
role: 'system',
content: 'You are a code reviewer.'
},
{
role: 'user',
content: `Review this ${language} code focusing on ${focus}.`
}
]
})
})
server.uiResource()
Registers a UI widget as both a tool and resource.
uiResource(definition: UIResourceDefinition): this
Parameters:
definition (UIResourceDefinition) - UI widget configuration
Returns: Server instance for method chaining
Example:
server.uiResource({
type: 'externalUrl',
name: 'dashboard',
widget: 'analytics-dashboard',
title: 'Analytics Dashboard',
description: 'Interactive analytics visualization',
props: z.object({
timeRange: z.string().describe('Time range for data').optional().default('7d')
}),
size: ['800px', '600px']
})
server.listen()
Starts the HTTP server with MCP endpoints.
listen(port?: number): Promise<void>
Parameters:
port (number, optional) - Port to listen on (default: 3000)
Returns: Promise that resolves when server is listening
Example:
await server.listen(8080)
console.log('Server running on port 8080')
Type Definitions
Configuration for tools.
interface ToolDefinition {
name: string // Unique tool identifier
title?: string // Display title
description?: string // Tool description
inputs?: InputDefinition[] // Input parameters
cb: ToolCallback // Handler function
annotations?: ToolAnnotations // Optional annotations
_meta?: Record<string, unknown> // Metadata (e.g., Apps SDK)
}
type ToolCallback = (params: Record<string, any>) => Promise<CallToolResult>
ResourceDefinition
Configuration for static resources.
interface ResourceDefinition {
name: string // Resource identifier
uri: string // Resource URI
title?: string // Display title
description?: string // Resource description
mimeType: string // MIME type
annotations?: ResourceAnnotations // Optional annotations
readCallback: ReadResourceCallback // Content provider
}
type ReadResourceCallback = () => Promise<{
contents: Array<{
uri: string
mimeType: string
text?: string
blob?: string
}>
}>
ResourceTemplateDefinition
Configuration for dynamic resource templates.
interface ResourceTemplateDefinition {
name: string // Template identifier
title?: string // Display title
description?: string // Template description
annotations?: ResourceAnnotations // Optional annotations
resourceTemplate: ResourceTemplateConfig // Template configuration
readCallback: ReadResourceTemplateCallback // Dynamic content provider
}
interface ResourceTemplateConfig {
uriTemplate: string // URI template with {params}
name?: string // Template name
description?: string // Template description
mimeType?: string // MIME type
}
type ReadResourceTemplateCallback = (
uri: URL,
params: Record<string, string>
) => Promise<ReadResourceResult>
PromptDefinition
Configuration for prompt templates.
interface PromptDefinition {
name: string // Prompt identifier
title?: string // Display title
description?: string // Prompt description
args?: InputDefinition[] // Arguments
cb: PromptCallback // Prompt generator
}
type PromptCallback = (args: Record<string, any>) => Promise<{
messages: Array<{
role: 'system' | 'user' | 'assistant'
content: string
}>
}>
UIResourceDefinition
Configuration for UI widgets.
interface UIResourceDefinition {
// Resource identification
name: string // Resource name
title?: string // Display title
description?: string // Description
// UI type configuration
type: 'externalUrl' | 'rawHtml' | 'remoteDom' | 'appsSdk'
// Widget-specific fields
widget?: string // Widget identifier (for externalUrl)
htmlTemplate?: string // HTML template (for appsSdk)
htmlString?: string // Raw HTML (for rawHtml)
remoteDomFramework?: RemoteDomFramework // For remoteDom
remoteDomCode?: string // JavaScript code (for remoteDom)
// Configuration
props?: WidgetProps // Widget properties
size?: [string, string] // [width, height]
annotations?: ResourceAnnotations
// Apps SDK specific
appsSdkMetadata?: AppsSdkMetadata
}
Parameter definition for tools and prompts.
interface InputDefinition {
name: string // Parameter name
type: 'string' | 'number' | 'boolean' | 'object' | 'array'
description?: string // Parameter description
required?: boolean // Is required (default: false)
default?: any // Default value
}
ResourceAnnotations
Metadata annotations for resources.
interface ResourceAnnotations {
audience?: ('user' | 'assistant')[] // Target audience
priority?: number // 0.0 to 1.0
lastModified?: string // ISO 8601 timestamp
}
Property definitions for UI widgets.
type WidgetProps = Record<string, {
type: 'string' | 'number' | 'boolean' | 'object' | 'array'
description?: string
required?: boolean
default?: any
}>
OpenAI Apps SDK metadata for widgets.
interface AppsSdkMetadata {
'openai/widgetDescription'?: string
'openai/widgetCSP'?: {
connect_domains?: string[]
resource_domains?: string[]
}
'openai/toolInvocation/invoking'?: string
'openai/toolInvocation/invoked'?: string
'openai/widgetAccessible'?: boolean
'openai/resultCanProduceWidget'?: boolean
[key: string]: unknown
}
HTTP Route Integration
The server instance supports adding custom HTTP routes and middleware alongside MCP endpoints.
Common Route Methods
// HTTP route handlers
server.get(path, ...handlers)
server.post(path, ...handlers)
server.put(path, ...handlers)
server.delete(path, ...handlers)
server.patch(path, ...handlers)
// Middleware
server.use(...middleware)
// Route-scoped middleware
server.use('/api/*', async (c, next) => {
await next()
})
Route + Middleware Example
import { MCPServer } from 'mcp-use/server'
const server = new MCPServer({
name: 'my-server',
version: '1.0.0',
})
// Custom middleware
server.use('/api/*', async (c, next) => {
console.log(`${c.req.method} ${c.req.path}`)
await next()
})
// API routes
server.get('/api/status', (c) => {
return c.json({ status: 'ok' })
})
Express Middleware Support
mcp-use automatically detects and adapts Express middleware. You can use Express middleware packages directly:
import morgan from 'morgan'
import rateLimit from 'express-rate-limit'
// Express middleware - automatically adapted
server.use(morgan('combined'))
server.use('/api', rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
}))
// Mix Express and Hono middleware
server.use(async (c, next) => {
// Hono middleware
await next()
})
Express middleware is detected by function signature (3-4 parameters) and pattern matching for Express-specific code patterns (e.g., res.send, req.body). Both Express and Hono middleware can be used together in the same application.
Return Types
Tool execution result.
interface CallToolResult {
content: Array<{
type: 'text' | 'image' | 'resource'
text?: string
data?: string
mimeType?: string
}>
_meta?: Record<string, unknown>
}
ReadResourceResult
Resource read result.
interface ReadResourceResult {
contents: Array<{
uri: string
mimeType: string
text?: string
blob?: string
}>
}
PromptResult
Prompt generation result.
interface PromptResult {
messages: Array<{
role: 'system' | 'user' | 'assistant'
content: string
}>
}
Utility Functions
UI Resource Helpers
The framework provides utility functions for creating UI resources:
import {
buildWidgetUrl,
createExternalUrlResource,
createRawHtmlResource,
createRemoteDomResource,
createUIResourceFromDefinition
} from 'mcp-use/server'
// Build widget URL with parameters
const url = buildWidgetUrl('dashboard',
{ timeRange: '7d' },
{ baseUrl: 'http://localhost', port: 3000 }
)
// Create UI resource objects
const externalResource = createExternalUrlResource(
'ui://widget/dashboard',
'http://localhost:3000/widgets/dashboard',
'text'
)
Error Handling
The framework handles errors gracefully:
server.tool({
name: 'risky_operation',
cb: async (params) => {
try {
// Perform operation
const result = await riskyOperation(params)
return {
content: [{
type: 'text',
text: `Success: ${result}`
}]
}
} catch (error) {
// Return error as text content
return {
content: [{
type: 'text',
text: `Error: ${error.message}`
}]
}
}
}
})
Best Practices
- Use TypeScript - Leverage type safety for better development experience
- Handle Errors - Always handle errors gracefully in callbacks
- Validate Input - Validate parameters in tool callbacks
- Use Annotations - Provide metadata for better client integration
- Chain Methods - Use fluent API for cleaner code
- Document Tools - Provide clear descriptions for all tools and resources
React Components & Hooks
The mcp-use/react package provides React components and hooks for building OpenAI Apps SDK widgets.
Components
McpUseProvider
Unified provider component that combines all common React setup.
import { McpUseProvider } from 'mcp-use/react';
<McpUseProvider
debugger={boolean}
viewControls={boolean | "pip" | "fullscreen"}
autoSize={boolean}
>
{children}
</McpUseProvider>
See McpUseProvider documentation for details.
Wrapper component that adds control buttons for widget debugging and view controls.
import { WidgetControls } from 'mcp-use/react';
<WidgetControls
debugger={boolean}
viewControls={boolean | "pip" | "fullscreen"}
position="top-right"
>
{children}
</WidgetControls>
See WidgetControls documentation for details.
ErrorBoundary
Error boundary component for graceful error handling. Supports custom fallback UI and error callbacks.
import { ErrorBoundary } from 'mcp-use/react';
<ErrorBoundary
fallback={(error) => <div>Error: {error.message}</div>}
onError={(error) => console.error(error)}
>
{children}
</ErrorBoundary>
See ErrorBoundary documentation for details.
Image
Image component that handles both data URLs and public file paths.
import { Image } from 'mcp-use/react';
<Image src="/fruits/apple.png" alt="Apple" />
See Image documentation for details.
ThemeProvider
Theme provider for consistent theme management.
import { ThemeProvider } from 'mcp-use/react';
<ThemeProvider>
{children}
</ThemeProvider>
See ThemeProvider documentation for details.
Hooks
Main hook providing type-safe access to all widget capabilities.
import { useWidget } from 'mcp-use/react';
const {
props,
output,
metadata,
state,
setState,
theme,
displayMode,
callTool,
sendFollowUpMessage,
openExternal,
requestDisplayMode,
notifyIntrinsicHeight,
isAvailable,
} = useWidget<TProps, TOutput, TMetadata, TState>();
See useWidget documentation for complete API reference.
Get only the widget props.
import { useWidgetProps } from 'mcp-use/react';
const props = useWidgetProps<{ city: string }>();
Get only the theme value.
import { useWidgetTheme } from 'mcp-use/react';
const theme = useWidgetTheme(); // 'light' | 'dark'
Get state management (state and setState).
import { useWidgetState } from 'mcp-use/react';
const [state, setState] = useWidgetState<string[]>([]);
Type Exports
import type {
UseMcpOptions,
UseMcpResult,
UseWidgetResult,
Theme,
DisplayMode,
SafeArea,
UserAgent,
CallToolResponse,
} from 'mcp-use/react';
Next Steps