mcp-template

pshaddel/mcp-template

3.3

If you are the rightful owner of 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.

A Model Context Protocol (MCP) server template for Node.js with TypeScript support.

Tools
1
Resources
0
Prompts
0

šŸš€ MCP Template

CI License: MIT codecov Node.js Version TypeScript

A Model Context Protocol (MCP) server template for Node.js with TypeScript support.

šŸ“‹ Overview

This is a comprehensive MCP server template that provides a robust foundation for building Model Context Protocol servers. It supports multiple transport modes: stdio, SSE (Server-Sent Events), and HTTP streams, making it suitable for various integration scenarios. The template includes authentication, logging, and a sample weather tool to demonstrate the MCP tool implementation pattern.

ļæ½ Prerequisites

  • Node.js 18+
  • npm or pnpm
  • TypeScript knowledge for customization

ļæ½šŸ› ļø Installation

# Clone the repository
git clone https://github.com/pshaddel/mcp-template.git
cd mcp-template

# Install dependencies
npm install
# or
pnpm install

# Build the project
npm run build

āš™ļø Configuration

Create a .env file based on the sample provided:

cp .sample.env .env

Configure the following environment variables:

VariableDescriptionDefaultRequired
MODETransport mode: stdio, sse, or http-streamsstdioYes
API_KEYSComma-separated list of allowed API keys (SSE/HTTP streams mode only)-No (required for SSE/HTTP streams)
APP_PORTPort for SSE/HTTP streams server3000No

Example Configuration

For stdio mode (Claude Desktop):

MODE=stdio

For SSE mode (HTTP server):

MODE=sse
API_KEYS=your_api_key1,your_api_key2
APP_PORT=3000

For HTTP streams mode (HTTP server with streaming):

MODE=http-streams
API_KEYS=your_api_key1,your_api_key2
APP_PORT=3000

šŸƒā€ā™€ļø Running the Service

Development Mode

npm run dev
# or
npm run start:dev
# or with pnpm
pnpm dev

Production Mode

npm start
# or with pnpm
pnpm start

182288589 MCP Inspector

The MCP Inspector is a powerful debugging tool that provides a web interface to test and interact with your MCP server tools during development.

How to run

npx @modelcontextprotocol/inspector

This will start the inspector and open it in your browser (typically at http://localhost:5173).

Configuration

The inspector supports different transport modes depending on how your MCP server is running:

SSE Configuration

When running your server in SSE mode:

  1. URL: http://localhost:3000/sse (or your configured port)
  2. Headers: Add the following header for authentication:
    • Header Name: x-api-key
    • Header Value: Your API key from the .env file
Screenshot 2025-08-21 at 20 57 46
HTTP Streams Configuration

When running your server in HTTP streams mode:

  1. URL: http://localhost:3000/mcp (or your configured port)
  2. Headers: Add the following header for authentication:
    • Header Name: x-api-key
    • Header Value: Your API key from the .env file Screenshot 2025-08-21 at 20 57 26

Usage Tips

  • Start your MCP server first in either SSE or HTTP streams mode
  • The inspector will automatically detect available tools and display their schemas
  • You can test tools interactively and see real-time responses
  • Use the inspector to validate your tool implementations before integrating with other clients

ļæ½šŸ”Œ Integration

claude-color Claude Desktop Integration

  1. Build the project:
npm run build
  1. Add the following configuration to your Claude Desktop config file:

macOS: ~/Library/Application Support/Claude/claude_desktop_config.json Windows: %APPDATA%\Claude\claude_desktop_config.json

{
    "mcpServers": {
        "mcp-template": {
            "command": "node",
            "args": [
                "--env-file=/path/to/your/project/.env",
                "/path/to/your/project/build/main.js"
            ]
        }
    }
}

3.Then restart Claude Desktop. and you should see the MCP server listed in the settings.

ScreenRecording2025-07-30at15 24 49-ezgif com-crop

n8n-color n8n Integration

  1. Run the application in sse or http-streams mode. If running locally, use npm run dev or npm start.

    • For SSE mode: server will be available at http://localhost:3000/sse
    • For HTTP streams mode: server will be available at http://localhost:3000/mcp

    If you are running n8n in a docker container, you cannot use http://localhost:3000 as the n8n container cannot access the host's localhost. Instead, you can use http://host.docker.internal:3000 to access the host's services from within the n8n container, or you can run the n8n container with the --network="host" option to share the host's network stack.

  2. Run the n8n instance, if locally, use the following command:

docker run -it --rm \
    -p 5678:5678 \
    -v ~/.n8n:/home/node/.n8n \
    n8nio/n8n
  1. Open n8n in your browser at http://localhost:5678.

  2. Create a new workflow and add an AI Agent node.

  3. In Tools section, add a MCP Client Tool node.

  4. Configure the MCP Client Tool node with the following settings:

    • Server URL:
      • For SSE mode: http://host.docker.internal:3000/sse
      • For HTTP streams mode: http://host.docker.internal:3000/mcp
    • API Key: Add a custom header x-api-key with your API key from the .env file.

The Tools Should be available now.

n8n-integration

HTTP Streams Integration

When running in HTTP streams mode, the server provides streamable HTTP endpoints for MCP communication with session management:

Base URL: http://localhost:3000 (or your configured port)

Endpoints:

  • POST /mcp - Initialize session or send MCP messages
  • GET /mcp - Retrieve server-to-client notifications (requires session ID)
  • DELETE /mcp - Terminate MCP session
  • GET /health - Health check endpoint

Session Management: HTTP streams mode uses session-based communication. Include the mcp-session-id header in requests after initialization:

# Initialize a new session
curl -X POST \
  -H "x-api-key: your_api_key" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test-client","version":"1.0.0"}}}' \
  http://localhost:3000/mcp

# Use the returned session ID in subsequent requests
curl -X POST \
  -H "x-api-key: your_api_key" \
  -H "mcp-session-id: your-session-id" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' \
  http://localhost:3000/mcp

Authentication: Set the x-api-key header with one of your configured API keys for all requests.

VS Code Integration

  1. Enable MCP support in VS Code in settings.
Screenshot 2025-07-30 at 15 31 18
  1. Use it via VS Code by adding the following to your .vscode/mcp.json file:
{
    "servers": {
        "mcp-template": {
            "type": "stdio",
            "command": "node",
            "args": [
                "--env-file=/path/to/your/project/.env",
                "/path/to/your/project/build/main.js"
            ]
        }
    },
    "inputs": []
}
  1. Start using it in VS Code by running the MCP commands in Copilot Chat(In Agent mode).

SSE Server Integration

When running in SSE mode, the server provides HTTP endpoints for MCP communication:

Base URL: http://localhost:3000 (or your configured port)

Endpoints:

  • GET /sse - Establish SSE connection
  • POST /messages - Send MCP messages
  • GET /health - Health check endpoint

Authentication: Set the x-api-key header with one of your configured API keys:

curl -H "x-api-key: your_api_key" http://localhost:3000/sse

🧰 Available Tools

1. weather

Fetches weather data from the Open Meteo API.

Input Parameters:

ParameterTypeDescriptionExample
latitudestringLatitude of the location"47.8095"
longitudestringLongitude of the location"13.0550"
start_datestringStart date (YYYY-MM-DD)"2025-07-25"
end_datestringEnd date (YYYY-MM-DD)"2025-07-25"
timezoneenumTimezone"Europe/London"

Supported Timezones:

  • Europe/London
  • America/New_York
  • Asia/Tokyo

Example Usage:

{
  "latitude": "47.8095",
  "longitude": "13.0550",
  "start_date": "2025-07-25",
  "end_date": "2025-07-25",
  "timezone": "Europe/London"
}

šŸ› ļø Development

Project Structure

src/
ā”œā”€ā”€ main.ts              # Main server entry point
ā”œā”€ā”€ tools/               # MCP tools directory
│   ā”œā”€ā”€ tool.interface.ts # Tool interface definition
│   └── weather.ts       # Weather tool implementation
└── tests/               # Test files
    └── weather.test.ts  # Weather tool tests

Adding New Tools

  1. Create a new tool file in src/tools/:
import { z } from 'zod';
import { Tool } from './tool.interface.js';

export const myTool: Tool = {
    tool_name: 'my_tool',
    description: 'Description of what your tool does',
    inputSchema: {
        // Define your input schema using zod validators
        param1: z.string().describe('Parameter description'),
    },
    function: async (args) => {
        // Implement your tool logic here
        return {
            content: [{
                type: 'text',
                text: 'Tool response'
            }]
        };
    }
};
  1. Register the tool in src/main.ts:
import { myTool } from './tools/my-tool.js';

// Add this line after the existing tool registration
mcpServer.registerTool(myTool.tool_name, {
    description: myTool.description,
    inputSchema: myTool.inputSchema,
}, myTool.function);

Available Scripts

ScriptDescription
npm run buildCompile TypeScript to JavaScript
npm run devRun in development mode with hot reload
npm run start:devAlternative development command
npm startRun the built server
npm run test:coverageRun tests with coverage report

🐳 Docker Support

Build and run with Docker:

# Build the Docker image
docker build -t mcp-template .

# Run the container
docker run -p 3000:3000 --env-file .env mcp-template

ļæ½ Testing

Run tests to ensure everything works correctly:

npm test              # Run tests
npm run test:coverage # Run tests with coverage
# or
pnpm test
pnpm run test:coverage

šŸ”§ Troubleshooting

Common Issues

Common Issues

"Transport not found" error in SSE/HTTP streams mode:

  • Ensure the SSE connection is established before sending messages (SSE mode)
  • Check that the sessionId is properly passed in requests (HTTP streams mode)
  • Verify the correct endpoint is being used (/sse for SSE, /mcp for HTTP streams)

Session management issues (HTTP streams mode):

  • Ensure you initialize a session with the initialize method before other requests
  • Include the mcp-session-id header in all requests after initialization
  • Check that the session hasn't expired or been terminated

Permission errors:

  • Verify the API key is correctly set in headers
  • Check that the API key exists in your API_KEYS environment variable

Build errors:

  • Run npm run build to ensure TypeScript compilation succeeds
  • Check that all dependencies are installed

Debug Mode

Enable detailed logging by setting the log level:

// In main.ts, modify the capabilities
capabilities: {
    logging: {
        level: 'debug', // Change from 'info' to 'debug'
        format: 'json',
        destination: 'stdout',
    }
}

šŸ“š Resources

ļæ½šŸ¤ Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Add tests for new functionality
  5. Commit your changes (git commit -m 'Add amazing feature')
  6. Push to the branch (git push origin feature/amazing-feature)
  7. Open a Pull Request

šŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

šŸ™ Acknowledgments

  • Anthropic for the Model Context Protocol
  • Open Meteo for the weather API used in the example tool