Skip to content
This repository was archived by the owner on May 21, 2026. It is now read-only.

Commit 388f890

Browse files
committed
chore: docstrings
1 parent 1bd1866 commit 388f890

1 file changed

Lines changed: 218 additions & 13 deletions

File tree

packages/mcp-use/src/server/mcp-server.ts

Lines changed: 218 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,16 @@ export class McpServer {
1818
private inspectorMounted = false
1919
private serverPort?: number
2020

21+
/**
22+
* Creates a new MCP server instance with Express integration
23+
*
24+
* Initializes the server with the provided configuration, sets up CORS headers,
25+
* configures widget serving routes, and creates a proxy that allows direct
26+
* access to Express methods while preserving MCP server functionality.
27+
*
28+
* @param config - Server configuration including name, version, and description
29+
* @returns A proxied McpServer instance that supports both MCP and Express methods
30+
*/
2131
constructor(config: ServerConfig) {
2232
this.config = config
2333
this.server = new OfficialMcpServer({
@@ -52,6 +62,27 @@ export class McpServer {
5262

5363
/**
5464
* Define a static resource that can be accessed by clients
65+
*
66+
* Registers a resource with the MCP server that clients can access via HTTP.
67+
* Resources are static content like files, data, or pre-computed results that
68+
* can be retrieved by clients without requiring parameters.
69+
*
70+
* @param resourceDefinition - Configuration object containing resource metadata and handler function
71+
* @param resourceDefinition.name - Unique identifier for the resource
72+
* @param resourceDefinition.uri - URI pattern for accessing the resource
73+
* @param resourceDefinition.resource - Resource metadata (mime type, description, etc.)
74+
* @param resourceDefinition.fn - Async function that returns the resource content
75+
* @returns The server instance for method chaining
76+
*
77+
* @example
78+
* ```typescript
79+
* server.resource({
80+
* name: 'config',
81+
* uri: 'config://app-settings',
82+
* resource: { mimeType: 'application/json' },
83+
* fn: async () => ({ theme: 'dark', language: 'en' })
84+
* })
85+
* ```
5586
*/
5687
resource(resourceDefinition: ResourceDefinition): this {
5788
this.server.resource(
@@ -82,6 +113,33 @@ export class McpServer {
82113

83114
/**
84115
* Define a tool that can be called by clients
116+
*
117+
* Registers a tool with the MCP server that clients can invoke with parameters.
118+
* Tools are functions that perform actions, computations, or operations and
119+
* return results. They accept structured input parameters and return structured output.
120+
*
121+
* @param toolDefinition - Configuration object containing tool metadata and handler function
122+
* @param toolDefinition.name - Unique identifier for the tool
123+
* @param toolDefinition.description - Human-readable description of what the tool does
124+
* @param toolDefinition.inputs - Array of input parameter definitions with types and validation
125+
* @param toolDefinition.fn - Async function that executes the tool logic with provided parameters
126+
* @returns The server instance for method chaining
127+
*
128+
* @example
129+
* ```typescript
130+
* server.tool({
131+
* name: 'calculate',
132+
* description: 'Performs mathematical calculations',
133+
* inputs: [
134+
* { name: 'expression', type: 'string', required: true },
135+
* { name: 'precision', type: 'number', required: false }
136+
* ],
137+
* fn: async ({ expression, precision = 2 }) => {
138+
* const result = eval(expression)
139+
* return { result: Number(result.toFixed(precision)) }
140+
* }
141+
* })
142+
* ```
85143
*/
86144
tool(toolDefinition: ToolDefinition): this {
87145
const inputSchema = this.createToolInputSchema(toolDefinition.inputs || [])
@@ -98,6 +156,37 @@ export class McpServer {
98156

99157
/**
100158
* Define a prompt template
159+
*
160+
* Registers a prompt template with the MCP server that clients can use to generate
161+
* structured prompts for AI models. Prompt templates accept parameters and return
162+
* formatted text that can be used as input to language models or other AI systems.
163+
*
164+
* @param promptDefinition - Configuration object containing prompt metadata and handler function
165+
* @param promptDefinition.name - Unique identifier for the prompt template
166+
* @param promptDefinition.description - Human-readable description of the prompt's purpose
167+
* @param promptDefinition.args - Array of argument definitions with types and validation
168+
* @param promptDefinition.fn - Async function that generates the prompt from provided arguments
169+
* @returns The server instance for method chaining
170+
*
171+
* @example
172+
* ```typescript
173+
* server.prompt({
174+
* name: 'code-review',
175+
* description: 'Generates a code review prompt',
176+
* args: [
177+
* { name: 'language', type: 'string', required: true },
178+
* { name: 'focus', type: 'string', required: false }
179+
* ],
180+
* fn: async ({ language, focus = 'general' }) => {
181+
* return {
182+
* messages: [{
183+
* role: 'user',
184+
* content: `Please review this ${language} code with focus on ${focus}...`
185+
* }]
186+
* }
187+
* }
188+
* })
189+
* ```
101190
*/
102191
prompt(promptDefinition: PromptDefinition): this {
103192
const argsSchema = this.createPromptArgsSchema(promptDefinition.args || [])
@@ -114,6 +203,22 @@ export class McpServer {
114203

115204
/**
116205
* Mount MCP server endpoints at /mcp
206+
*
207+
* Sets up the HTTP transport layer for the MCP server, creating endpoints for
208+
* Server-Sent Events (SSE) streaming, POST message handling, and DELETE session cleanup.
209+
* Uses stateless mode for session management, making it suitable for stateless deployments.
210+
*
211+
* This method is called automatically when the server starts listening and ensures
212+
* that MCP clients can communicate with the server over HTTP.
213+
*
214+
* @private
215+
* @returns Promise that resolves when MCP endpoints are successfully mounted
216+
*
217+
* @example
218+
* Endpoints created:
219+
* - GET /mcp - SSE streaming endpoint for real-time communication
220+
* - POST /mcp - Message handling endpoint for MCP protocol messages
221+
* - DELETE /mcp - Session cleanup endpoint
117222
*/
118223
private async mountMcp(): Promise<void> {
119224
if (this.mcpMounted) return
@@ -154,7 +259,24 @@ export class McpServer {
154259

155260
/**
156261
* Start the Express server with MCP endpoints
157-
* @param port - Port to listen on (defaults to 3001)
262+
*
263+
* Initiates the server startup process by mounting MCP endpoints, configuring
264+
* the inspector UI (if available), and starting the Express server to listen
265+
* for incoming connections. This is the main entry point for running the server.
266+
*
267+
* The server will be accessible at the specified port with MCP endpoints at /mcp
268+
* and inspector UI at /inspector (if the inspector package is installed).
269+
*
270+
* @param port - Port number to listen on (defaults to 3001 if not specified)
271+
* @returns Promise that resolves when the server is successfully listening
272+
*
273+
* @example
274+
* ```typescript
275+
* await server.listen(8080)
276+
* // Server now running at http://localhost:8080
277+
* // MCP endpoints: http://localhost:8080/mcp
278+
* // Inspector UI: http://localhost:8080/inspector
279+
* ```
158280
*/
159281
async listen(port?: number): Promise<void> {
160282
await this.mountMcp()
@@ -171,6 +293,25 @@ export class McpServer {
171293

172294
/**
173295
* Mount MCP Inspector UI at /inspector
296+
*
297+
* Dynamically loads and mounts the MCP Inspector UI package if available, providing
298+
* a web-based interface for testing and debugging MCP servers. The inspector
299+
* automatically connects to the local MCP server endpoints.
300+
*
301+
* This method gracefully handles cases where the inspector package is not installed,
302+
* allowing the server to function without the inspector in production environments.
303+
*
304+
* @private
305+
* @returns void
306+
*
307+
* @example
308+
* If @mcp-use/inspector is installed:
309+
* - Inspector UI available at http://localhost:PORT/inspector
310+
* - Automatically connects to http://localhost:PORT/mcp
311+
*
312+
* If not installed:
313+
* - Server continues to function normally
314+
* - No inspector UI available
174315
*/
175316
private mountInspector(): void {
176317
if (this.inspectorMounted) return
@@ -193,6 +334,24 @@ export class McpServer {
193334

194335
/**
195336
* Setup default widget serving routes
337+
*
338+
* Configures Express routes to serve MCP UI widgets and their static assets.
339+
* Widgets are served from the dist/resources/mcp-use/widgets directory and can
340+
* be accessed via HTTP endpoints for embedding in web applications.
341+
*
342+
* Routes created:
343+
* - GET /mcp-use/widgets/:widget - Serves widget's index.html
344+
* - GET /mcp-use/widgets/:widget/assets/* - Serves widget-specific assets
345+
* - GET /mcp-use/widgets/assets/* - Fallback asset serving with auto-discovery
346+
*
347+
* @private
348+
* @returns void
349+
*
350+
* @example
351+
* Widget routes:
352+
* - http://localhost:3001/mcp-use/widgets/kanban-board
353+
* - http://localhost:3001/mcp-use/widgets/todo-list/assets/style.css
354+
* - http://localhost:3001/mcp-use/widgets/assets/script.js (auto-discovered)
196355
*/
197356
private setupWidgetRoutes(): void {
198357
// Serve static assets (JS, CSS) from the assets directory
@@ -234,6 +393,19 @@ export class McpServer {
234393

235394
/**
236395
* Create input schema for resource templates
396+
*
397+
* Parses a URI template string to extract parameter names and generates a Zod
398+
* validation schema for those parameters. Used internally for validating resource
399+
* template parameters before processing requests.
400+
*
401+
* @param uriTemplate - URI template string with parameter placeholders (e.g., "/users/{id}/posts/{postId}")
402+
* @returns Object mapping parameter names to Zod string schemas
403+
*
404+
* @example
405+
* ```typescript
406+
* const schema = this.createInputSchema("/users/{id}/posts/{postId}")
407+
* // Returns: { id: z.string(), postId: z.string() }
408+
* ```
237409
*/
238410
private createInputSchema(uriTemplate: string): Record<string, z.ZodSchema> {
239411
const params = this.extractTemplateParams(uriTemplate)
@@ -248,6 +420,22 @@ export class McpServer {
248420

249421
/**
250422
* Create input schema for tools
423+
*
424+
* Converts tool input definitions into Zod validation schemas for runtime validation.
425+
* Supports common data types (string, number, boolean, object, array) and optional
426+
* parameters. Used internally when registering tools with the MCP server.
427+
*
428+
* @param inputs - Array of input parameter definitions with name, type, and optional flag
429+
* @returns Object mapping parameter names to Zod validation schemas
430+
*
431+
* @example
432+
* ```typescript
433+
* const schema = this.createToolInputSchema([
434+
* { name: 'query', type: 'string', required: true },
435+
* { name: 'limit', type: 'number', required: false }
436+
* ])
437+
* // Returns: { query: z.string(), limit: z.number().optional() }
438+
* ```
251439
*/
252440
private createToolInputSchema(inputs: Array<{ name: string, type: string, required?: boolean }>): Record<string, z.ZodSchema> {
253441
const schema: Record<string, z.ZodSchema> = {}
@@ -286,6 +474,22 @@ export class McpServer {
286474

287475
/**
288476
* Create arguments schema for prompts
477+
*
478+
* Converts prompt argument definitions into Zod validation schemas for runtime validation.
479+
* Supports common data types (string, number, boolean, object, array) and optional
480+
* parameters. Used internally when registering prompt templates with the MCP server.
481+
*
482+
* @param inputs - Array of argument definitions with name, type, and optional flag
483+
* @returns Object mapping argument names to Zod validation schemas
484+
*
485+
* @example
486+
* ```typescript
487+
* const schema = this.createPromptArgsSchema([
488+
* { name: 'topic', type: 'string', required: true },
489+
* { name: 'style', type: 'string', required: false }
490+
* ])
491+
* // Returns: { topic: z.string(), style: z.string().optional() }
492+
* ```
289493
*/
290494
private createPromptArgsSchema(inputs: Array<{ name: string, type: string, required?: boolean }>): Record<string, z.ZodSchema> {
291495
const schema: Record<string, z.ZodSchema> = {}
@@ -324,6 +528,19 @@ export class McpServer {
324528

325529
/**
326530
* Extract parameter names from URI template
531+
*
532+
* Parses a URI template string to extract parameter names enclosed in curly braces.
533+
* Used internally to identify dynamic parameters in resource templates and generate
534+
* appropriate validation schemas.
535+
*
536+
* @param uriTemplate - URI template string with parameter placeholders (e.g., "/users/{id}/posts/{postId}")
537+
* @returns Array of parameter names found in the template
538+
*
539+
* @example
540+
* ```typescript
541+
* const params = this.extractTemplateParams("/users/{id}/posts/{postId}")
542+
* // Returns: ["id", "postId"]
543+
* ```
327544
*/
328545
private extractTemplateParams(uriTemplate: string): string[] {
329546
const matches = uriTemplate.match(/\{([^}]+)\}/g)
@@ -332,15 +549,3 @@ export class McpServer {
332549
}
333550

334551
export type McpServerInstance = Omit<McpServer, keyof Express> & Express
335-
336-
/**
337-
* Create a new MCP server instance
338-
*/
339-
export function createMCPServer(name: string, config: Partial<ServerConfig> = {}): McpServerInstance {
340-
const instance = new McpServer({
341-
name,
342-
version: config.version || '1.0.0',
343-
description: config.description,
344-
})
345-
return instance as unknown as McpServerInstance
346-
}

0 commit comments

Comments
 (0)