Streamflare

robertefreeman/Streamflare

3.2

If you are the rightful owner of Streamflare 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 template provides a comprehensive foundation for building streamable HTTP transport MCP servers, optimized for deployment on Cloudflare Workers.

๐Ÿš€ MCP Streamable HTTP Server Template

โœจ A reusable template for building streamable HTTP transport MCP servers that can be quickly deployed to Cloudflare Workers free tier. This template provides a complete foundation for creating Model Context Protocol (MCP) servers with real-time streaming capabilities and dual deployment support.


๐ŸŽฏ What This Template Provides

  • ๐Ÿ”ง Complete MCP Implementation: Full Model Context Protocol server implementation using the official @modelcontextprotocol/sdk
  • โšก Streamable HTTP Transport: Server-Sent Events (SSE) support for real-time client notifications
  • โ˜๏ธ Cloudflare Workers Integration: Optimized for deployment to Cloudflare Workers free tier
  • ๐Ÿ”„ Dual Runtime Support: Works in both Node.js development environment and Cloudflare Workers production
  • ๐Ÿ‘ฅ Multi-session Handling: Supports multiple simultaneous client connections
  • ๐Ÿ’ป TypeScript Foundation: Fully typed codebase with proper configuration
  • ๐Ÿ“ Example Implementation: Working example to demonstrate usage patterns

๐Ÿš€ Quick Start

1. ๐Ÿ“ฆ Clone and Setup

# Clone this template (replace with your repo URL)
git clone <your-template-repo-url>
cd your-mcp-server

# Install dependencies
npm install

2. ๐Ÿ”ง Environment Setup

# Copy the example environment file
cp .env.example .env

# Edit .env with your configuration
# Update API keys, database URLs, and other settings as needed

3. ๐Ÿ’ป Local Development

# Build the project
npm run build

# Run locally with Node.js
node build/index.js

# Or specify a custom port
node build/index.js --port=9000

๐ŸŒ The server will start at http://localhost:8123 by default (or the port specified in your .env file).

4. โ˜๏ธ Cloudflare Workers Development

# Start local Workers development server
npm run dev:worker

# Build for Workers deployment
npm run build:worker

5. ๐Ÿš€ Deploy to Cloudflare Workers

# Deploy to Cloudflare Workers (free tier)
npm run deploy

โœ… Success! Your MCP server is now live on the edge! ๐ŸŽ‰


๐Ÿ—๏ธ Core Architecture

๐Ÿ”„ Dual Runtime Support

This template is designed to work in both environments:

  • ๐Ÿ’ป Node.js: Full Express.js server for local development and traditional hosting
  • โ˜๏ธ Cloudflare Workers: Optimized worker implementation for edge deployment

๐Ÿงฉ Key Components

โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ index.ts           # ๐Ÿ’ป Node.js Express server entry point
โ”‚   โ”œโ”€โ”€ worker.ts          # โ˜๏ธ Cloudflare Workers entry point  
โ”‚   โ”œโ”€โ”€ worker-transport.ts # โšก Workers-optimized HTTP transport
โ”‚   โ”œโ”€โ”€ server.ts          # ๐Ÿ”ง Core MCP server implementation
โ”œโ”€โ”€ example-client.js      # ๐Ÿงช Example client for testing
โ”œโ”€โ”€ wrangler.toml         # โ˜๏ธ Cloudflare Workers configuration
โ”œโ”€โ”€ tsconfig.json         # ๐Ÿ’ป Node.js TypeScript config
โ””โ”€โ”€ tsconfig.worker.json  # โ˜๏ธ Workers TypeScript config

โœจ Customizing the Template

1. ๐Ÿ”ง Define Your Tools

Edit to implement your specific MCP tools:

// Add your custom tools
server.setRequestHandler(ListToolsRequestSchema, async () => {
  return {
    tools: [
      {
        name: "your-custom-tool",
        description: "Description of what your tool does",
        inputSchema: {
          type: "object",
          properties: {
            // Define your tool's parameters
          },
        },
      },
    ],
  };
});

// Implement your tool logic
server.setRequestHandler(CallToolRequestSchema, async (request) => {
  const { name, arguments: args } = request.params;
  
  switch (name) {
    case "your-custom-tool":
      // Implement your tool logic here
      return {
        content: [
          {
            type: "text",
            text: "Your tool response"
          }
        ]
      };
    default:
      throw new McpError(ErrorCode.MethodNotFound, `Tool not found: ${name}`);
  }
});

2. โ˜๏ธ Configure Workers Deployment

Update :

name = "your-mcp-server-name"
main = "src/worker.ts"
compatibility_date = "2024-12-06"

[vars]
# Add your environment variables
API_KEY = "your-api-key"

3. ๐Ÿ“ฆ Update Package Metadata

Modify :

{
  "name": "your-mcp-server",
  "description": "Your MCP server description",
  "version": "1.0.0"
}

๐ŸŒ API Endpoints

The server exposes a single MCP endpoint at /mcp:

  • ๐Ÿ“ค POST /mcp: Handle MCP JSON-RPC requests
  • ๐Ÿ“ก GET /mcp: Establish Server-Sent Events (SSE) stream for real-time notifications

๐Ÿ“‹ Example MCP Request

{
  "jsonrpc": "2.0",
  "id": "1",
  "method": "tools/call",
  "params": {
    "name": "your-tool-name",
    "arguments": {
      "param1": "value1"
    }
  }
}

โœจ Features

๐Ÿ” Security & Authentication

  • ๐Ÿ”‘ Optional API Key Authentication: Secure your MCP server with configurable API key authentication
  • ๐ŸŽ›๏ธ Flexible Authentication Formats: Support for both Bearer <token> and direct API key formats
  • ๐ŸŒ Environment-Controlled: Enable/disable authentication via environment variables
  • ๐ŸŒ CORS-Compatible: Proper CORS headers for cross-origin authentication

๐Ÿ“ก Streaming HTTP Transport

  • โšก Real-time Notifications: Server-Sent Events for live updates
  • ๐Ÿ‘ฅ Multi-session Support: Handle multiple concurrent client connections
  • ๐Ÿ”„ Dynamic Updates: Real-time tool and resource updates with client notifications

โ˜๏ธ Cloudflare Workers Optimization

  • ๐Ÿ’ฐ Free Tier Compatible: Designed to work within Cloudflare Workers free tier limits
  • ๐ŸŒ Edge Performance: Global edge deployment for low latency
  • ๐Ÿ—๏ธ Serverless Architecture: Pay-per-request pricing model
  • โšก Zero Cold Start: Optimized for fast startup times

๐Ÿ› ๏ธ Development Experience

  • ๐Ÿ’ป TypeScript Support: Full type safety and IntelliSense
  • ๐Ÿ”ฅ Hot Reload: Fast development iteration with wrangler dev
  • ๐Ÿšจ Error Handling: Comprehensive error handling and logging
  • ๐Ÿงช Example Client: Ready-to-use client for testing with authentication examples

๐Ÿงช Testing Your Server

Use the included example client to test your implementation:

# Start your server
npm run build && node build/index.js

# In another terminal, test with the example client
node example-client.js

The example client demonstrates:

  1. ๐Ÿ”Œ MCP connection initialization
  2. ๐Ÿ” Tool discovery and listing
  3. โš™๏ธ Tool execution with parameters
  4. ๐Ÿšจ Error handling
  5. ๐Ÿ” Authentication examples (configure USE_AUTH and API_KEY in the client)

๐Ÿ’ก Note: If you enable authentication on your server (MCP_AUTH_REQUIRED=true), make sure to update the authentication configuration in by setting USE_AUTH=true and providing your API_KEY.


๐Ÿš€ Deployment Options

โ˜๏ธ Cloudflare Workers (Recommended)

  • ๐Ÿ’ฐ Free tier: 100,000 requests/day
  • ๐ŸŒ Global edge: Low latency worldwide
  • ๐Ÿ”ง Zero maintenance: Serverless infrastructure

๐Ÿ–ฅ๏ธ Traditional Hosting

  • ๐Ÿ’ป Node.js: Deploy to any Node.js hosting platform
  • ๐ŸŒ Express.js: Full HTTP server capabilities
  • ๐ŸŽฏ Custom domains: Complete control over deployment

๐Ÿ”ง Environment Variables

๐Ÿ’ป Node.js Development (.env file)

For local Node.js development, copy .env.example to .env and configure:

# Copy the example file
cp .env.example .env
๐Ÿ“‹ Required Variables
  • PORT: Server port (default: 8123)
  • ENVIRONMENT: Current environment (development/production)
โš™๏ธ Optional Variables
  • MCP_SERVER_NAME: Name of your MCP server (default: "mcp-server")
  • MCP_SERVER_VERSION: Version of your MCP server (default: "1.0.0")
  • MCP_SESSION_HEADER_NAME: Header name for session ID (default: "mcp-session-id")
๐Ÿ” Authentication Variables
  • MCP_AUTH_REQUIRED: Enable/disable API key authentication (true/false, default: false)
  • MCP_API_KEY: API key for client authentication (required if MCP_AUTH_REQUIRED=true)
  • MCP_AUTH_HEADER_NAME: Header name for API key (default: "Authorization")
๐ŸŒค๏ธ Weather API Configuration (for example weather tools)
  • WEATHER_API_BASE_URL: Weather API base URL (default: "https://api.weather.gov")
  • USER_AGENT: User agent string for API requests (default: "weather-app/1.0")
๐Ÿ”‘ API Keys (configure as needed for your tools)
  • WEATHER_API_KEY: Weather service API key
  • OPENAI_API_KEY: OpenAI API key
  • GOOGLE_API_KEY: Google services API key
  • ANTHROPIC_API_KEY: Anthropic API key
๐Ÿ”— External Services
  • DATABASE_URL: Database connection string
  • REDIS_URL: Redis connection string
  • EXTERNAL_API_URL: External API base URL
๐ŸŒ CORS Configuration
  • CORS_ORIGIN: Allowed origins (default: "*")
  • CORS_METHODS: Allowed HTTP methods (default: "GET, POST, OPTIONS")
  • CORS_HEADERS: Allowed headers (default: "Content-Type, mcp-session-id")
๐ŸŽ›๏ธ Feature Flags
  • ENABLE_LOGGING: Enable detailed logging (true/false)
  • ENABLE_DEBUG_MODE: Enable debug mode (true/false)

โ˜๏ธ Cloudflare Workers (.dev.vars file)

For Cloudflare Workers development, copy .dev.vars.example to .dev.vars and configure similarly.

๐Ÿ’ก Note: The .env file is for Node.js development, while .dev.vars is for Cloudflare Workers. Both files are ignored by git for security.


๐Ÿ” Authentication

This MCP server supports optional API key authentication to secure access to your server endpoints.

๐Ÿ”‘ Enabling Authentication

Authentication is controlled by environment variables and is disabled by default. To enable authentication:

  1. Set authentication environment variables in your .env file (Node.js) or .dev.vars file (Cloudflare Workers):
# Enable authentication
MCP_AUTH_REQUIRED=true

# Set your API key (keep this secure!)
MCP_API_KEY=your-secure-api-key-here

# Optional: customize the header name (default: Authorization)
MCP_AUTH_HEADER_NAME=Authorization
  1. Restart your server after updating the environment variables.

๐ŸŽฏ Supported Authentication Formats

The server supports two authentication formats:

๐Ÿท๏ธ Bearer Token Format (Recommended)
Authorization: Bearer your-api-key-here
๐Ÿ”‘ Direct API Key Format
Authorization: your-api-key-here

๐Ÿ’ป Client Implementation

When authentication is enabled, clients must include the API key in their requests:

// Example client code with authentication
const headers = {
  'Content-Type': 'application/json',
  'Authorization': 'Bearer your-api-key-here'  // or just 'your-api-key-here'
};

const response = await fetch('http://localhost:8123/mcp', {
  method: 'POST',
  headers: headers,
  body: JSON.stringify(mcpRequest)
});

๐Ÿ“‹ Authentication Responses

  • โœ… 200 OK: Request successful (valid API key or authentication disabled)
  • โŒ 401 Unauthorized: Invalid or missing API key when authentication is required

Example error response:

{
  "jsonrpc": "2.0",
  "error": {
    "code": -32600,
    "message": "Unauthorized: Invalid or missing API key"
  },
  "id": null
}

๐Ÿ”’ Security Best Practices

  1. ๐Ÿ” Keep API keys secure: Never commit API keys to version control
  2. ๐ŸŒ Use environment variables: Store API keys in .env files that are gitignored
  3. ๐Ÿ”’ Use HTTPS in production: Always use HTTPS when deploying to production
  4. ๐Ÿ”„ Rotate keys regularly: Change API keys periodically for better security
  5. ๐Ÿท๏ธ Use Bearer format: The Bearer <token> format is the recommended standard

โŒ Disabling Authentication

To disable authentication (default behavior):

# In .env or .dev.vars
MCP_AUTH_REQUIRED=false
# or simply omit the MCP_AUTH_REQUIRED variable

When authentication is disabled, the server will accept all requests without checking for API keys.


๐Ÿ“„ License

ISC


๐ŸŽฏ Next Steps

  1. ๐Ÿ”ง Customize Tools: Replace the example tools with your specific functionality
  2. โ˜๏ธ Configure Deployment: Update wrangler.toml with your project details
  3. ๐Ÿงช Test Locally: Use the example client to verify your implementation
  4. ๐Ÿš€ Deploy: Push to Cloudflare Workers free tier
  5. ๐Ÿ”Œ Connect: Integrate with MCP-compatible clients

๐ŸŽ‰ This template provides everything you need to build, test, and deploy production-ready MCP servers with minimal setup time! โœจ


Built with โค๏ธ for the MCP community

๐Ÿš€ Get Started โ€ข ๐Ÿ“– Documentation โ€ข ๐Ÿ› ๏ธ Features โ€ข ๐Ÿ”ง Customization