CortexFlow-AI/http-stream-mcp-template
If you are the rightful owner of http-stream-mcp-template and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.
This document provides a comprehensive overview of a Model Context Protocol (MCP) server template designed for HTTP streaming, offering a robust foundation for developers to build and deploy MCP-compliant servers.
HTTP Stream MCP Template
A foundational structure for building MCP (Model Context Protocol) servers with HTTP streaming capabilities.
Overview
This template provides a complete, production-ready MCP server implementation using the Streamable HTTP transport protocol. It includes Hello-world functionality, comprehensive test coverage, and clear documentation to serve as a starting point for developers building their own MCP servers.
The template implements MCP Protocol version 2025-06-18 and follows all security best practices, making it suitable for both development and production use.
Features
- ✅ MCP Protocol 2025-06-18 compliance - Full implementation of the latest MCP specification
- ✅ HTTP Streamable transport - POST/GET support with optional Server-Sent Events (SSE)
- ✅ Hello-world tool implementation - Complete example tool with parameter handling
- ✅ Comprehensive test coverage - 95%+ line coverage with unit and integration tests
- ✅ TypeScript with strict mode - Full type safety and modern JavaScript features
- ✅ Security best practices - Origin validation, localhost binding, input sanitization
- ✅ Extensible architecture - Easy to add new tools and customize behavior
- ✅ Production ready - Error handling, logging, graceful shutdown, and configuration
Quick Start
Prerequisites
- Node.js 18+ (recommended: Node.js 20 LTS)
- npm 9+ or yarn 1.22+
Installation
-
Clone or download the template:
git clone <repository-url> my-mcp-server cd my-mcp-server -
Install dependencies:
npm install -
Start development server:
npm run dev
The server will start on http://127.0.0.1:3000 by default.
Verify Installation
Test the server with a simple HTTP request:
# Test server health
curl http://127.0.0.1:3000/mcp
# Test MCP initialization (requires proper MCP client)
curl -X POST http://127.0.0.1:3000/mcp \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-06-18",
"capabilities": {},
"clientInfo": {"name": "test-client", "version": "1.0.0"}
}
}'
Configuration
Environment Variables
The server can be configured using environment variables:
# Server configuration
export MCP_PORT=3000 # Server port (default: 3000)
export MCP_HOST=127.0.0.1 # Server host (default: 127.0.0.1)
# Start server with custom configuration
npm start
Programmatic Configuration
import { MCPServer, createDefaultConfig } from './src/index.js';
const config = {
...createDefaultConfig(),
port: 8080,
host: '0.0.0.0', // WARNING: Only use in secure environments
allowedOrigins: ['localhost', '127.0.0.1', 'myapp.com'],
serverInfo: {
name: 'my-custom-mcp-server',
version: '2.0.0'
}
};
const server = new MCPServer(config);
await server.start();
Configuration Options
| Option | Type | Default | Description |
|---|---|---|---|
port | number | 3000 | HTTP server port |
host | string | '127.0.0.1' | Server bind address |
allowedOrigins | string[] | ['localhost', '127.0.0.1'] | Allowed Origin headers |
protocolVersion | string | '2025-06-18' | MCP protocol version |
serverInfo.name | string | 'http-stream-mcp-template' | Server name |
serverInfo.version | string | '1.0.0' | Server version |
Usage
Using the Hello Tool
The template includes a Hello tool that demonstrates basic MCP functionality:
# List available tools
curl -X POST http://127.0.0.1:3000/mcp \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/list"
}'
# Call Hello tool without parameters
curl -X POST http://127.0.0.1:3000/mcp \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "hello",
"arguments": {}
}
}'
# Call Hello tool with name parameter
curl -X POST http://127.0.0.1:3000/mcp \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 4,
"method": "tools/call",
"params": {
"name": "hello",
"arguments": {"name": "Alice"}
}
}'
Adding Custom Tools
-
Create a new tool class:
// src/tools/my-tool.ts import { ToolImplementation, ToolResult } from '../types/index.js'; export class MyTool implements ToolImplementation { name = 'my-tool'; description = 'My custom tool'; inputSchema = { type: 'object', properties: { input: { type: 'string' } } }; async execute(args: any): Promise<ToolResult> { return { content: [{ type: 'text', text: `Processed: ${args.input}` }], isError: false }; } } -
Register the tool:
// In your server setup import { MyTool } from './tools/my-tool.js'; const server = new MCPServer(config); server.registerTool(new MyTool()); await server.start();
Development
Available Scripts
| Script | Description |
|---|---|
npm run dev | Start development server with hot reload |
npm run build | Build TypeScript to JavaScript |
npm start | Start production server |
npm test | Run all tests |
npm run test:watch | Run tests in watch mode |
npm run test:coverage | Run tests with coverage report |
npm run lint | Check code style |
npm run lint:fix | Fix code style issues |
npm run format | Format code with Prettier |
Project Structure
├── src/
│ ├── types/ # TypeScript type definitions
│ │ ├── index.ts # Main type exports
│ │ ├── mcp.ts # MCP protocol types
│ │ └── server.ts # Server configuration types
│ ├── protocol/ # MCP protocol implementation
│ │ ├── errors.ts # Error handling and standard error codes
│ │ ├── initialization.ts # MCP initialization handshake
│ │ └── jsonrpc.ts # JSON-RPC message handling
│ ├── transport/ # HTTP transport layer
│ │ ├── http-server.ts # Main HTTP server implementation
│ │ ├── content-negotiation.ts # Accept header handling
│ │ └── security-middleware.ts # Origin validation & security
│ ├── server/ # MCP server orchestration
│ │ ├── mcp-server.ts # Main server class
│ │ └── tools-handler.ts # Tool request routing
│ ├── tools/ # Tool implementations
│ │ ├── hello-tool.ts # Hello world tool example
│ │ ├── registry.ts # Tool registration and management
│ │ └── index.ts # Tool exports
│ └── index.ts # Main entry point and exports
├── tests/
│ ├── unit/ # Unit tests
│ └── integration/ # Integration tests
├── examples/ # Usage examples
├── dist/ # Compiled JavaScript (generated)
└── coverage/ # Test coverage reports (generated)
Testing
The template includes comprehensive test coverage:
# Run all tests
npm test
# Run tests with coverage
npm run test:coverage
# Run tests in watch mode during development
npm run test:watch
# Run specific test file
npx vitest run tests/unit/tools/hello-tool.test.ts
Code Quality
The project uses ESLint and Prettier for code quality:
# Check for linting issues
npm run lint
# Automatically fix linting issues
npm run lint:fix
# Format code
npm run format
Production Deployment
Building for Production
# Build the project
npm run build
# Start production server
npm start
Docker Deployment
Create a Dockerfile:
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY dist/ ./dist/
EXPOSE 3000
CMD ["npm", "start"]
Build and run:
docker build -t my-mcp-server .
docker run -p 3000:3000 my-mcp-server
Process Management
For production deployment, use a process manager like PM2:
# Install PM2
npm install -g pm2
# Start with PM2
pm2 start dist/index.js --name mcp-server
# Monitor
pm2 status
pm2 logs mcp-server
Security Considerations
Default Security Features
- Localhost binding: Server binds to 127.0.0.1 by default
- Origin validation: Validates Origin header to prevent DNS rebinding attacks
- Input sanitization: All tool inputs are validated and sanitized
- Error handling: Prevents information leakage through error messages
Production Security
For production deployments:
- Use HTTPS: Always use TLS in production
- Firewall: Restrict access to the MCP port
- Authentication: Add authentication middleware (see examples)
- Rate limiting: Implement rate limiting for tool calls
- Monitoring: Add logging and monitoring
Adding Authentication
// Example authentication middleware
import { MCPServer } from './src/index.js';
const server = new MCPServer(config);
// Add authentication hook (implement based on your needs)
server.addAuthenticationHook(async (request) => {
const token = request.headers.authorization;
if (!isValidToken(token)) {
throw new Error('Unauthorized');
}
});
Troubleshooting
Common Issues
Server Won't Start
Problem: Error: listen EADDRINUSE :::3000
Solution: Port 3000 is already in use. Either:
- Stop the process using port 3000:
lsof -ti:3000 | xargs kill - Use a different port:
MCP_PORT=3001 npm start
Problem: Error: listen EACCES :::80
Solution: Ports below 1024 require root privileges. Use port 3000+ or run with sudo (not recommended).
Connection Refused
Problem: curl: (7) Failed to connect to 127.0.0.1 port 3000: Connection refused
Solution:
- Ensure server is running:
npm run dev - Check server logs for startup errors
- Verify port configuration
Origin Validation Errors
Problem: Error: Invalid Origin header
Solution: Add your domain to allowedOrigins in configuration:
const config = {
...createDefaultConfig(),
allowedOrigins: ['localhost', '127.0.0.1', 'yourdomain.com']
};
Tool Not Found
Problem: Method not found: tools/call
Solution:
- Ensure server is initialized before calling tools
- Check that tools are properly registered
- Verify tool name in the request
JSON-RPC Errors
Problem: Parse error or Invalid Request
Solution:
- Ensure Content-Type is
application/json - Validate JSON syntax
- Include required JSON-RPC fields (
jsonrpc,method,id)
Debug Mode
Enable debug logging:
# Set debug environment variable
DEBUG=mcp:* npm run dev
# Or in code
process.env.DEBUG = 'mcp:*';
Health Checks
The server provides health check endpoints:
# Basic health check
curl http://127.0.0.1:3000/mcp
# Server statistics
curl -X POST http://127.0.0.1:3000/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"server/stats"}'
Performance Issues
If experiencing performance issues:
- Check test coverage:
npm run test:coverage - Profile memory usage: Use Node.js
--inspectflag - Monitor tool execution time: Check server logs
- Validate input schemas: Ensure efficient validation
Getting Help
- Check the logs: Server logs contain detailed error information
- Review test cases: Tests demonstrate expected behavior
- Consult MCP specification: MCP Protocol Documentation
- Check examples: See
examples/directory for usage patterns
Documentation
- - Detailed feature requirements
- - Architecture and design decisions
- - Development task breakdown
- MCP Protocol Specification - Official MCP documentation
Contributing
- Fork the repository
- Create a feature branch:
git checkout -b feature/my-feature - Make changes and add tests
- Ensure tests pass:
npm test - Check code quality:
npm run lint - Commit changes:
git commit -am 'Add my feature' - Push to branch:
git push origin feature/my-feature - Create a Pull Request
License
MIT License - see LICENSE file for details.