Skip to content

HTTP Stream MCP Template - A foundational structure for building MCP servers with HTTP streaming capabilities

Notifications You must be signed in to change notification settings

CortexFlow-AI/http-stream-mcp-template

Repository files navigation

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

  1. Clone or download the template:

    git clone <repository-url> my-mcp-server
    cd my-mcp-server
  2. Install dependencies:

    npm install
  3. 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

  1. 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
        };
      }
    }
  2. 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:

  1. Use HTTPS: Always use TLS in production
  2. Firewall: Restrict access to the MCP port
  3. Authentication: Add authentication middleware (see examples)
  4. Rate limiting: Implement rate limiting for tool calls
  5. 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:

  1. Check test coverage: npm run test:coverage
  2. Profile memory usage: Use Node.js --inspect flag
  3. Monitor tool execution time: Check server logs
  4. Validate input schemas: Ensure efficient validation

Getting Help

  1. Check the logs: Server logs contain detailed error information
  2. Review test cases: Tests demonstrate expected behavior
  3. Consult MCP specification: MCP Protocol Documentation
  4. Check examples: See examples/ directory for usage patterns

Documentation

Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/my-feature
  3. Make changes and add tests
  4. Ensure tests pass: npm test
  5. Check code quality: npm run lint
  6. Commit changes: git commit -am 'Add my feature'
  7. Push to branch: git push origin feature/my-feature
  8. Create a Pull Request

License

MIT License - see LICENSE file for details.

About

HTTP Stream MCP Template - A foundational structure for building MCP servers with HTTP streaming capabilities

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages