Skip to main content

API Reference

This document provides a complete reference for the mcp-use/server API, including all classes, methods, and type definitions.

Server Creation

createMCPServer()

Creates a new MCP server instance with Express integration.
function createMCPServer(
  name: string,
  config?: Partial<ServerConfig>
): McpServerInstance
Parameters:
  • name (string) - Unique identifier for your server
  • config (Partial<ServerConfig>) - Optional configuration object
Returns: McpServerInstance - Server instance with both MCP and Express methods Example:
const server = createMCPServer('my-server', {
  version: '1.0.0',
  description: 'My MCP server'
})

Server Configuration

ServerConfig

Configuration object for server initialization.
interface ServerConfig {
  name: string        // Server name
  version: string     // Server version (semver format)
  description?: string // Optional description
}

Core Server Methods

server.tool()

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',
  inputs: [
    { name: 'expression', type: 'string', required: true }
  ],
  cb: async ({ expression }) => {
    const result = eval(expression) // Note: Use safe evaluation in production
    return {
      content: [{
        type: 'text',
        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: {
    timeRange: {
      type: 'string',
      description: 'Time range for data',
      required: false,
      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

ToolDefinition

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
}

InputDefinition

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
}

WidgetProps

Property definitions for UI widgets.
type WidgetProps = Record<string, {
  type: 'string' | 'number' | 'boolean' | 'object' | 'array'
  description?: string
  required?: boolean
  default?: any
}>

AppsSdkMetadata

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
}

Express Integration

The server instance proxies all Express methods, allowing you to use Express functionality directly:

Common Express 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)

// Static files
server.use('/static', express.static('public'))

// Route parameters
server.param(name, callback)

// Settings
server.set(setting, value)
server.get(setting)

Example Express Usage

import express from 'express'

// Body parsing middleware
server.use(express.json())
server.use(express.urlencoded({ extended: true }))

// Custom middleware
server.use((req, res, next) => {
  console.log(`${req.method} ${req.path}`)
  next()
})

// API routes
server.get('/api/status', (req, res) => {
  res.json({ status: 'ok' })
})

// Error handling
server.use((err, req, res, next) => {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})

Return Types

CallToolResult

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

  1. Use TypeScript - Leverage type safety for better development experience
  2. Handle Errors - Always handle errors gracefully in callbacks
  3. Validate Input - Validate parameters in tool callbacks
  4. Use Annotations - Provide metadata for better client integration
  5. Chain Methods - Use fluent API for cleaner code
  6. Document Tools - Provide clear descriptions for all tools and resources

Next Steps