What is MCP?
The Model Context Protocol (MCP) is a specialized framework designed to streamline the process of enabling AI agents to interact with a wide array of tools. This starter template helps you quickly build a Model Context Protocol (MCP) server using TypeScript. It provides a robust foundation that you can easily extend to create advanced MCP tools and seamlessly integrate them with various AI platforms.
Core Components
MCP Servers: These servers act as bridges, exposing APIs, databases, and code libraries to external AI hosts. By implementing an MCP server in TypeScript, developers can share data sources or computational logic in a standardized way using JSON-RPC 2.0.
MCP Clients: These are the consumer-facing side of MCP, communicating with servers to query data or perform actions. MCP clients use TypeScript SDKs, ensuring type-safe interactions and uniform approach to tool usage.
MCP Hosts: Systems such as Claude, Cursor, Windsurf, Cline, and other TypeScript-based platforms coordinate requests between servers and clients, ensuring seamless data flow. A single MCP server can thus be accessed by multiple AI hosts without custom integrations.
TypeScript Implementation
The MCP TypeScript SDK provides core classes for building servers:
By using MCP, developers no longer need complex custom code to integrate new tools or services. Instead, they build an MCP server and make it available to supported hosts.
Prerequisites
Node.js (v18 or later): A modern version of Node.js that takes advantage of the latest JavaScript features and performance improvements.
npm (v7 or later): Ensures compatibility for installing and managing packages.
VS Code with Dev Containers extension: Allows you to quickly spin up a reproducible development environment, making collaboration easier and more efficient.
Project Structure
A typical file layout for the MCP server template may look like this:
The .devcontainer directory streamlines container-based development, while the src/ folder houses the main server logic and examples of custom tools. This structure keeps your project organized and easy to navigate.
Quick Start
Installing via Smithery
To install MCP Server Starter for any supported client:
Clone this template: Retrieve the repository files from your preferred source.
Open in VS Code with Dev Containers: If you have the Dev Containers extension installed, you will be prompted to open this project inside a container.
Install dependencies:
npm installThis command fetches and installs all required packages for the MCP server.
Build the project:
npm run buildThis compiles your TypeScript code into JavaScript, preparing it for runtime.
Development Scripts
Build the project:
npm run buildCompiles your TypeScript source and sets file permissions for the main entry point.
Watch mode:
npm run watchAutomatically recompiles TypeScript files whenever changes are made, ideal for active development.
Run with inspector:
npm run inspectorLaunches the server alongside a debugging tool, enabling you to trace issues, set breakpoints, and inspect variables in real time.
Tool Response Format
MCP tools must return responses in a specific format to ensure proper communication with AI hosts. Here's the structure:
Supported content types include:
text: Plain text contentcode: Code snippets with optional language specificationimage: Base64-encoded images with MIME typefile: File content with MIME typeerror: Error messages (whenisErroris true)
Example response:
Security Best Practices
When developing MCP tools, follow these security guidelines:
Input Validation:
Always validate input parameters using Zod schemas
Implement strict type checking
Sanitize user inputs before processing
Use the
strict()option in schemas to prevent extra properties
Error Handling:
Never expose internal error details to clients
Implement proper error boundaries
Log errors securely
Return user-friendly error messages
Resource Management:
Implement proper cleanup procedures
Handle process termination signals
Close connections and free resources
Implement timeouts for long-running operations
API Security:
Use secure transport protocols
Implement rate limiting
Store sensitive data securely
Use environment variables for configuration
Example secure tool implementation:
Advanced Features
Streaming Responses
MCP supports streaming responses for long-running operations:
Custom Content Types
You can define custom content types for specialized data:
Async Tool Execution
Implement proper async handling:
Testing & Debugging
Unit Testing
Use Jest for testing your tools:
Debugging Tools
MCP Inspector:
npm run inspectorProvides real-time inspection of:
Tool registration
Request/response flow
Error handling
Performance metrics
Logging:
function logMessage(level: 'info' | 'warn' | 'error', message: string) { console.error(`[${level.toUpperCase()}] ${message}`); }Error Tracking:
process.on('uncaughtException', (error: Error) => { logMessage('error', `Uncaught error: ${error.message}`); // Implement error reporting });
Transport Configuration
MCP supports multiple transport protocols:
stdio Transport
WebSocket Transport
Custom Transport
Server Capabilities
Configure server capabilities:
Integration with MCP Hosts
Multi-Client Support
This MCP server template supports multiple AI platforms out of the box:
Claude Desktop:
Provides a chat-based environment
Supports all MCP capabilities
Ideal for conversational AI interactions
Cursor:
AI-powered development environment
Full tool integration support
Perfect for coding assistance
Windsurf:
Modern AI development platform
Complete MCP protocol support
Streamlined workflow integration
Cline:
Command-line AI interface
Tool-focused interactions
Efficient terminal-based usage
TypeScript:
Native TypeScript support
Type-safe tool development
Seamless SDK integration
Each client can be configured using the appropriate Smithery CLI command:
Replace [client-name] with one of: claude, cursor, windsurf, cline, or typescript.
Smithery Integration
A convenient way to run this MCP server is through Smithery, a centralized platform for discovering and publishing MCP servers. Smithery simplifies deployment and ensures your server can be integrated into various AI workflows.
Quick Run
You can immediately execute this server via the Smithery CLI:
Smithery automatically fetches, installs, and runs the server from its latest release, requiring minimal setup from you.
Publishing Your Own Version
If you have developed new tools or made local modifications and wish to share them, consider publishing your customized server:
Create an account on Smithery.
Follow their deployment instructions to bundle and publish your MCP server.
Other users can then run your server through Smithery by referencing your unique package name.
Smithery offers:
A centralized registry to discover and share MCP servers.
Simplified deployment, removing repetitive setup.
A community-driven approach where developers contribute diverse tools.
Easy integration with popular AI hosts.
For additional guidance:
Cursor Integration
Cursor is another AI development environment that supports MCP. To incorporate your server into Cursor:
Build your server:
npm run buildEnsure an executable
index.jsis generated in thebuilddirectory.In Cursor, go to
Settings>Features>MCP: Add a new MCP server.Register your server:
Select
stdioas the transport type.Provide a descriptive
Name.Set the command, for example:
node /path/to/your/mcp-server/build/index.js.
Save your configuration.
Cursor then detects and lists your tools. During AI-assisted coding sessions or prompt-based interactions, it will call your MCP tools whenever relevant. You can also instruct the AI to use a specific tool by name.
Claude Desktop Integration
Claude Desktop provides a chat-based environment where you can leverage MCP tools. To include your server:
Build your server:
npm run buildConfirm that no errors occur and that the main script is generated in
build.Modify
claude_desktop_config.json:{ "mcpServers": { "mcp-server": { "command": "node", "args": [ "/path/to/your/mcp-server/build/index.js" ] } } }Provide the path to your compiled main file along with any additional arguments.
Restart Claude Desktop to load the new configuration.
When you interact with Claude Desktop, it can now invoke the MCP tools you have registered. If a user's request aligns with any of your tool's functionality, Claude will prompt to use that tool.
Development Best Practices
Use TypeScript for better type checking, clearer code organization, and easier maintenance over time.
Adopt consistent patterns for implementing tools:
Keep each tool in its own file
Use descriptive schemas with proper documentation
Implement comprehensive error handling
Return properly formatted content
Include thorough documentation:
Add JSDoc comments to explain functionality
Document parameters and return types
Include examples where helpful
Leverage the inspector for debugging:
npm run inspectorThis helps you:
Test tool functionality
Debug request/response flow
Verify schema validation
Check error handling
Test comprehensively before deployment:
Verify input validation
Test error scenarios
Check response formatting
Ensure proper integration with hosts
Follow MCP best practices:
Use proper content types
Implement proper error handling
Validate all inputs and outputs
Handle network requests safely
Format responses consistently
Learn More
For further information on the MCP ecosystem, refer to:
Model Context Protocol Documentation: Detailed coverage of MCP architecture, design principles, and more advanced usage examples.
Smithery - MCP Server Registry: Guidelines for publishing your tools to Smithery and best practices for their registry.
MCP TypeScript SDK Documentation: Comprehensive documentation of the TypeScript SDK.
MCP Security Guidelines: Detailed security best practices and recommendations.
Conclusion
By following this template and best practices, you can quickly build a robust MCP server that opens your tools to a broad range of AI hosts. This expanded approach ensures easier maintenance, better type safety, and a smooth user experience when harnessing the capabilities of modern AI systems.
Credits
Template created by Seth Rose:
Website: https://www.sethrose.dev
𝕏 (Twitter): https://x.com/TheSethRose
🦋 (Bluesky): https://bsky.app/profile/sethrose.dev
Best Practices
Type Safety:
Leverage TypeScript's type system for robust tool definitions
Use Zod schemas for runtime validation
Define clear interfaces for tool parameters and responses
Transport Selection:
Use
StdioServerTransportfor local process communicationImplement
WebSocketServerTransportfor network-based toolsConsider custom transports for specific use cases
Capability Management:
Clearly define server capabilities during initialization
Implement proper capability negotiation
Handle capability-specific errors gracefully
Security Considerations:
Implement user consent flows for sensitive operations
Validate all inputs using TypeScript types and Zod schemas
Handle errors securely without exposing internal details
This server cannot be installed