TypeScript MCP Server Template
A comprehensive TypeScript MCP Server Template following the official MCP TypeScript SDK best practices, built with Fastify and providing tools, resources, and prompts.
📖 README en Español - Para usuarios que prefieren documentación en español
📌 How to Use or Contribute
This repository is available as both a collaborative project and a template:
- Use as a template → Create your own MCP server project instantly by clicking Use this template.
- Contribute improvements → Fork this repo, make your changes, and send a Pull Request so we can review and integrate them.
We welcome:
- New MCP tools, resources, and prompts
- Performance optimizations
- Documentation improvements
- Bug fixes and code quality enhancements
If you create something based on this template, please mention this repository in your README.
🛠️ Tech Stack & Tools Explained
Core Technologies
- TypeScript - Type-safe development with compile-time error checking
- Fastify - Fast and efficient web framework for building APIs
- @modelcontextprotocol/sdk - Official MCP Server SDK for AI model integration
Development Tools
- Zod - Runtime type validation and schema definition for API inputs
- @fastify/cors - CORS support for web clients to access the API
- tsx - Modern TypeScript execution without compilation step
- pino-pretty - Beautiful development logging with structured output
Code Quality Tools
- ESLint - Static code analysis to catch errors and enforce coding standards
- Prettier - Automatic code formatting for consistent style
- Husky - Git hooks to run quality checks before commits
- lint-staged - Run linters only on staged files for faster feedback
Deployment Tools
- Docker - Containerization for consistent deployment across environments
- Docker Compose - Multi-container orchestration for development and production
📦 Project Structure
🚀 Getting Started
1. Install Dependencies
What this does: Installs all required dependencies including TypeScript, Fastify, MCP SDK, and development tools.
2. Environment Setup
Copy the environment example file and configure your variables:
What this does: Creates a local environment file with configuration for:
- Server settings (port, host)
- MCP configuration (STDIO mode, session timeout)
- Logging levels and formatting
- CORS settings
- External API keys (weather service)
3. Start Development Server
HTTP Mode (for web clients):
STDIO Mode (for CLI clients like Claude Desktop):
Debug Mode (with detailed logging):
What each mode does:
- HTTP Mode: Starts server on port 3000 for web-based MCP clients
- STDIO Mode: Runs as CLI process for desktop AI applications
- Debug Mode: Enables verbose logging for troubleshooting
4. Build for Production
What this does:
clean
: Removes old build artifactsbuild
: Compiles TypeScript to optimized JavaScriptstart
: Runs the production server
Production STDIO Mode:
🌐 Available Endpoints
HTTP Mode: The server starts on http://localhost:3000
with these endpoints:
MCP Protocol Endpoints
POST /mcp
- Model Context Protocol interface (handles all MCP operations)- Purpose: Main interface for AI models to interact with tools and resources
- Usage: Send JSON-RPC 2.0 requests with MCP methods
REST API Endpoints
GET /hello/:name
- Traditional REST API endpoint- Purpose: Example of hybrid REST + MCP server
- Usage:
curl http://localhost:3000/hello/YourName
Weather Plugin Endpoints
GET /weather/forecast?lat=40.7128&lng=-74.0060
- Weather forecast- Purpose: Get weather data for specific coordinates
- Usage:
curl "http://localhost:3000/weather/forecast?lat=40.7128&lng=-74.0060"
GET /weather/alerts/:state
- Weather alerts for US state- Purpose: Get weather alerts for specific US states
- Usage:
curl http://localhost:3000/weather/alerts/CA
Monitoring Endpoints
GET /health
- Enhanced server status with session info- Purpose: Health check with detailed metrics
- Usage:
curl http://localhost:3000/health
GET /info
- Server capabilities and endpoints- Purpose: Discover available features
- Usage:
curl http://localhost:3000/info
STDIO Mode: The server runs as a CLI process for direct integration with MCP clients like Claude Desktop.
🧪 Testing the Server
Quick Health Check
Expected response:
What this tells you:
- Server is running and healthy
- Current timestamp and uptime
- Number of active MCP sessions
- Available MCP capabilities
Using the Client Example
The included client example demonstrates all MCP features:
This demonstrates:
- ✅ Connection: Establishing connection to MCP server
- 🔧 Tools: Listing and calling MCP tools
- 📚 Resources: Listing and reading MCP resources
- 💭 Prompts: Listing and getting MCP prompts
- 🚨 Error Handling: Proper error handling examples
🔧 MCP Features Explained
🛠️ Tools - What They Are and How to Use
Tools are functions that AI models can call to perform actions. Each tool:
- Has a name, description, and input schema
- Validates inputs using Zod schemas
- Returns structured results
Available Tools:
1. sayHello
Tool
Purpose: Simple greeting tool for testing MCP communication Input: Person's name Usage Example:
2. calculate
Tool
Purpose: Perform arithmetic operations Input: Operation type and two numbers Usage Example:
3. getWeatherForecast
Tool
Purpose: Get weather forecast for specific coordinates Input: Latitude and longitude Usage: Called by AI models to get weather data
4. getWeatherAlerts
Tool
Purpose: Get weather alerts for US states Input: US state name Usage: Called by AI models to get weather alerts
📋 Zod Validation - Why It's Important
Zod provides runtime type validation that matches TypeScript types:
Benefits:
- ✅ Type Safety: Runtime validation matches TypeScript types
- ✅ Better Errors: Descriptive validation error messages
- ✅ Reusability: Common schemas can be shared across tools
- ✅ Maintainability: Centralized validation logic
📚 Resources - What They Are and How to Use
Resources are data sources that AI models can read. Each resource:
- Has a URI scheme (
mcp://
,file://
, etc.) - Contains structured data
- Can be read multiple times
Available Resources:
1. Server Information (mcp://server-info
)
Purpose: Provides server metadata and capabilities Usage:
2. Hello Message (mcp://hello-message
)
Purpose: Example resource with greeting content Usage:
💭 Prompts - What They Are and How to Use
Prompts are template messages that AI models can use. Each prompt:
- Has a name and description
- Accepts arguments for customization
- Returns formatted messages
Available Prompts:
Greeting Prompt (greeting-prompt
)
Purpose: Generate personalized greetings Usage:
🏗️ Architecture & Best Practices
Official SDK Patterns Used
This template follows the official MCP TypeScript SDK documentation:
- ✅ Proper Request Handlers: Using
setRequestHandler()
for all MCP operations - ✅ Session Management: Map-based session storage for transport instances
- ✅ Streamable HTTP Transport: Latest transport method (not deprecated SSE)
- ✅ Standard JSON Schema: Proper tool input schemas without Zod dependency
- ✅ Error Handling: Comprehensive error handling with proper MCP error responses
- ✅ Resource URI Schemes: Using
mcp://
scheme following best practices
Key Improvements Over Basic Implementation
- Session Management: Proper session tracking with cleanup
- Enhanced Error Handling: Detailed error responses and logging
- Multiple Capabilities: Tools, resources, AND prompts (many examples only show one)
- Production Ready: Graceful shutdown, health checks, proper logging
- Type Safety: Full TypeScript support without runtime schema validation overhead
- Code Quality: ESLint, Prettier, and Husky for consistent code
- Containerization: Docker support for easy deployment
- CI/CD: GitHub Actions pipeline for automated testing
Integration Features
- CORS: Enhanced CORS configuration for web clients
- Logging: Structured logging with pino-pretty for development
- Health Monitoring: Detailed health endpoint with session metrics
- REST + MCP: Hybrid server supporting both traditional REST and MCP protocols
- Error Handling: Centralized error handling with custom error types
- Configuration: Centralized configuration management
🔄 Git Flow Workflow
This project follows Git Flow methodology for organized development:
Branch Structure
main
- Production-ready codedevelop
- Integration branch for featuresfeature/*
- New features and improvementsrelease/*
- Release preparationhotfix/*
- Critical production fixes
Development Workflow
Commit Message Convention
We follow Conventional Commits:
feat:
- New featuresfix:
- Bug fixesdocs:
- Documentation changesstyle:
- Code style changes (formatting, etc.)refactor:
- Code refactoringtest:
- Adding or updating testschore:
- Maintenance tasks
🔧 Development Tools Explained
Available Scripts
Development Scripts
npm run dev
- Start development server with hot reload and pretty logging- Purpose: Main development command with live reload
- Use when: Developing new features
npm run dev:debug
- Start with debug logging enabled- Purpose: Detailed logging for troubleshooting
- Use when: Debugging issues or understanding server behavior
npm run dev:stdio
- Start in STDIO mode for CLI clients- Purpose: Run server for desktop AI applications
- Use when: Testing with Claude Desktop or similar
Build Scripts
npm run build
- Compile TypeScript to JavaScript indist/
folder- Purpose: Create production-ready JavaScript files
- Use when: Deploying to production
npm run build:watch
- Build with watch mode- Purpose: Auto-rebuild when files change
- Use when: Developing with build step
npm start
- Run compiled server (production mode)- Purpose: Start production server
- Use when: Running in production environment
Code Quality Scripts
npm run clean
- Remove compiled files- Purpose: Clean build artifacts
- Use when: Troubleshooting build issues
npm run lint
- Run ESLint- Purpose: Check code quality and style
- Use when: Before committing code
npm run lint:fix
- Run ESLint with auto-fix- Purpose: Automatically fix linting issues
- Use when: ESLint reports fixable errors
npm run format
- Format code with Prettier- Purpose: Ensure consistent code formatting
- Use when: Code formatting is inconsistent
npm run type-check
- Run TypeScript type checking- Purpose: Verify TypeScript types without building
- Use when: Checking for type errors
npm run validate
- Run type check and linting- Purpose: Comprehensive code quality check
- Use when: Before pushing code or creating PRs
Testing Scripts
npm test
- Run tests (placeholder)- Purpose: Execute test suite
- Use when: Verifying functionality
Environment Requirements
- Node.js: >=18.0.0 (for modern JavaScript features)
- TypeScript: ^5.7.2 (for type safety)
- MCP SDK: ^1.0.4 (for MCP protocol support)
Adding New MCP Tools
Following official SDK patterns:
- Add tool definition to
tools/list
handler:
- Handle tool execution in
tools/call
handler:
Adding New Resources
- Add to
resources/list
handler - Define available resources - Handle reading in
resources/read
handler - Implement resource reading logic - Use proper URI schemes (
mcp://
,file://
, etc.) - Follow MCP conventions
Adding Prompts
- Add to
prompts/list
handler - Define available prompts - Handle generation in
prompts/get
handler - Implement prompt generation logic - Return proper message format with roles - Follow MCP prompt format
🐳 Docker Support
Building the Image
What this does:
- Creates a multi-stage Docker image
- Optimizes for production with minimal size
- Includes all necessary dependencies
Running with Docker
What each does:
- Production mode: Runs optimized container for production
- Development mode: Runs with volume mounts for live development
Docker Compose
What this provides:
- Multi-service orchestration: Easy management of multiple containers
- Development profiles: Separate configurations for dev/prod
- Volume mounts: Live code reloading in development
Docker Documentation
For detailed information about Docker setup, troubleshooting, and best practices:
- Docker Troubleshooting Guide - Common issues and solutions
- Docker Best Practices - Best practices for Node.js containerization
Key improvements made:
- ✅ Multi-stage builds for optimized production images
- ✅ Non-root user execution for security
- ✅ Proper healthcheck configuration with curl
- ✅ Separate npm scripts to avoid prestart hook issues
- ✅ Comprehensive .dockerignore for faster builds
🌐 CORS & Security
Enhanced CORS configuration for MCP compatibility:
- Origin: Flexible origin handling (
true
instead of*
) - Headers: All required MCP headers plus standard web headers
- Methods: All HTTP methods for maximum compatibility
- Session Security: Session-based transport isolation
🚨 Troubleshooting
Common Issues
1. Port Already in Use
What this fixes: Resolves port conflicts when starting the server
2. TypeScript Compilation Errors
What this fixes: Resolves build issues caused by stale files
3. MCP Connection Issues
- Ensure proper
Mcp-Session-Id
header - Check CORS configuration for web clients
- Verify JSON-RPC 2.0 format in requests
What this fixes: Resolves MCP protocol communication issues
4. STDIO Mode Not Working
What this fixes: Ensures server runs in correct mode for CLI clients
5. Linting Errors
What this fixes: Resolves code style and quality issues
Debug Mode
Enable debug logging by setting environment variable:
What this provides: Detailed logging for troubleshooting MCP issues
Performance Monitoring
The health endpoint provides real-time metrics:
What this shows: Server status, uptime, active sessions, and capabilities
📚 Learn More
- Model Context Protocol Specification
- Official TypeScript SDK
- MCP Server Examples
- Fastify Documentation
- Git Flow Documentation
📝 License
MIT License - see LICENSE file for details
🤝 Contributing
We encourage both direct contributions and independent projects based on this template.
- To collaborate:
- Fork the repository.
- Create a feature branch using Git Flow:
git flow feature start feature-name
. - Follow the patterns from the official MCP SDK documentation.
- Add tests if applicable.
- Submit a Pull Request.
- To create your own project without linking back:
- Click Use this template and start building.
Built following Official MCP TypeScript SDK best practices
This server cannot be installed
remote-capable server
The server can be hosted and run remotely because it primarily relies on remote services or has no dependency on the local environment.
A comprehensive template for building MCP servers with TypeScript, Fastify, and Docker support. Includes tools for calculations and weather data, resources for server information, and prompts for greetings with full development tooling.
- 📌 How to Use or Contribute
- 🛠️ Tech Stack & Tools Explained
- 📦 Project Structure
- 🚀 Getting Started
- 🌐 Available Endpoints
- 🧪 Testing the Server
- 🔧 MCP Features Explained
- 🏗️ Architecture & Best Practices
- 🔄 Git Flow Workflow
- 🔧 Development Tools Explained
- 🐳 Docker Support
- 🌐 CORS & Security
- 🚨 Troubleshooting
- 📚 Learn More
- 📝 License
- 🤝 Contributing
Related MCP Servers
- AsecurityFlicenseAqualityA template for creating Model Context Protocol (MCP) servers in TypeScript, offering features like container-based dependency injection, a service-based architecture, and integration with the LLM CLI for architectural design feedback through natural language.Last updated -126TypeScript
- -securityFlicense-qualityA TypeScript framework for building Model Context Protocol (MCP) servers with automatic discovery and loading of tools, resources, and prompts.Last updated -1TypeScript
- -securityFlicense-qualityA template repository for building Model Context Protocol (MCP) servers with TypeScript, featuring full TypeScript support, testing setup, CI/CD pipelines, and modular architecture for easy extension.Last updated -2TypeScript
- -securityAlicense-qualityA template repository for creating MCP servers that can be easily containerized and used with MCP clients.Last updated -7101MIT License