The MCPServer class is the main entry point for creating MCP servers. It handles automatic service discovery, tool/prompt/resource registration, and provides the underlying MCP SDK server instance.
Constructor
new MCPServer ( options : MCPServerConstructorOptions )
Creates a new MCPServer instance with automatic service discovery and initialization.
Parameters
options
MCPServerConstructorOptions
required
Server configuration options Show MCPServerConstructorOptions
Server name (displayed in MCP clients)
Server version (semantic versioning recommended)
Enable detailed debug logs (requires logging: true)
Enable automatic service discovery from the mcp/ directory
Custom path to the MCP services directory (default: ./mcp)
serviceFactories
Record<string, () => any>
Dependency injection factories for service classes
HTTP server port (used with createHTTPServer)
cors
boolean | { origin?: string | string[]; credentials?: boolean }
CORS configuration for HTTP server
Session timeout in milliseconds
Enable stateless mode for Lambda/serverless deployments
Serve dashboard UI at / and /mcp GET endpoints
OAuth/Auth configuration (MCP authorization spec)
Example
import { MCPServer } from '@leanmcp/core' ;
const server = new MCPServer ({
name: 'my-mcp-server' ,
version: '1.0.0' ,
logging: true ,
debug: true ,
autoDiscover: true ,
mcpDir: './mcp' ,
});
Methods
registerService()
Manually register a service instance with decorated methods.
server . registerService ( instance : any ): void
Service class instance with @Tool, @Prompt, or @Resource decorated methods
Example
import { MCPServer , Tool } from '@leanmcp/core' ;
class MyService {
@ Tool ({ description: 'Get current time' })
async getCurrentTime () {
return new Date (). toISOString ();
}
}
const server = new MCPServer ({
name: 'my-server' ,
version: '1.0.0' ,
autoDiscover: false ,
});
server . registerService ( new MyService ());
autoRegisterServices()
Automatically discover and register services from a directory.
await server . autoRegisterServices (
mcpDir : string ,
serviceFactories ?: Record < string , () => any >
): Promise < void >
Path to directory containing service files (looks for index.ts or index.js files)
serviceFactories
Record<string, () => any>
Optional map of service class names to factory functions for dependency injection
Example
// Auto-register services with no dependencies
await server . autoRegisterServices ( './mcp' );
// Auto-register with dependency injection
await server . autoRegisterServices ( './mcp' , {
SlackService : () => new SlackService ( process . env . SLACK_TOKEN ),
AuthService : () => new AuthService ( authProvider ),
});
getServer()
Get the underlying MCP SDK Server instance.
server . getServer (): Server
The underlying @modelcontextprotocol/sdk Server instance
Example
const mcpServer = server . getServer ();
// Use with stdio transport
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js' ;
const transport = new StdioServerTransport ();
await mcpServer . connect ( transport );
waitForInit()
Wait for initialization to complete (auto-discovery, UI manifest loading).
await server . waitForInit (): Promise < void >
This method is called internally by createHTTPServer and typically doesn’t need to be called manually.
close()
Clean up all registered services, watchers, and resources. Critical for stateless mode to prevent memory leaks.
Example
// In stateless Lambda handler
const server = new MCPServer ({ name: 'my-server' , version: '1.0.0' });
try {
// ... handle request
} finally {
server . close (); // Clean up resources
}
cleanup()
Asynchronous cleanup of resources (alias for close with async support).
await server . cleanup (): Promise < void >
Service Discovery
The MCPServer automatically discovers services from the mcp/ directory:
Scans for index.ts or index.js files recursively
Imports all exported classes
Instantiates classes with factory functions (if provided) or no-args constructors
Registers all @Tool, @Prompt, and @Resource decorated methods
Directory Structure
project/
├── mcp/
│ ├── weather/
│ │ └── index.ts # WeatherService
│ ├── slack/
│ │ └── index.ts # SlackService
│ └── github/
│ └── index.ts # GitHubService
└── index.ts # Main server
Disabling Auto-Discovery
const server = new MCPServer ({
name: 'my-server' ,
version: '1.0.0' ,
autoDiscover: false , // Disable automatic discovery
});
// Manually register services
server . registerService ( new WeatherService ());
server . registerService ( new SlackService ());
Stateless vs Stateful Mode
Stateless Mode (Default)
Optimized for Lambda/serverless deployments:
Fresh server instance per request
No session persistence
Automatic cleanup after each request
No file watchers or background processes
const server = new MCPServer ({
name: 'my-server' ,
version: '1.0.0' ,
stateless: true , // Default
});
Stateful Mode
Long-running servers with session support:
Single server instance
Session persistence with optional DynamoDB backend
File watchers for hot-reload
SSE support for streaming
const server = new MCPServer ({
name: 'my-server' ,
version: '1.0.0' ,
stateless: false ,
});