MCP-SERVER-TEMPLATE

by vyasa1986

Integrations

  • Loads environment variables from .env files for server configuration, enabling customization of transport types, HTTP settings, authentication, and logging options.

  • Provides HTTP request utilities through the 'serviceRequest' function in httpUtils.ts, supporting authenticated API requests with OAuth2 or API key authentication, retries, and response validation.

  • Implements the HTTP transport layer using Express to handle POST requests to the /mcp endpoint, process JSON-RPC messages, and support stateless request handling.

MCP-SERVER-TEMPLATE

Welcome to MCP-SERVER-TEMPLATE, a template project for implementing a Model Context Protocol (MCP) server using the official TypeScript SDK. This project provides a foundation for building stateless and stateful MCP servers, with support for different transport mechanisms such as HTTP and standard I/O (stdio).

Table of Contents

Overview

This project, MCP-SERVER-TEMPLATE, is a TypeScript-based starter template for building Model Context Protocol (MCP) servers using the official SDK. The server acts as an interface between user queries and tool execution, enabling AI assistants and external systems to dynamically call tools, interpret prompts, and manage resources in a modular and extensible way.

Key Capabilities

  • Modular Architecture: The project is divided into clear modules for configuration, transport management, tool registration, server orchestration, and utility helpers—promoting separation of concerns and ease of maintenance.
  • Transport Abstraction: Built-in support for multiple transport types including:
    • HTTP (Stateless): Each request spins up a new MCP server instance for full isolation and compliance with RESTful practices.
    • STDIO (Stateful): For desktop or CLI-based integrations requiring persistent communication.
    • Easily extendable to future transports such as SSE or WebSocket via a unified interface and factory pattern.
  • Dependency Injection: A custom DI system injects services like configuration and logging into tools and transport layers—ensuring testability and decoupling.
  • Tool System: Tools are isolated classes that define:
    • A unique name and description
    • A Zod schema for input validation
    • An execute function to handle business logic
    • Auto-generated JSON schema for external introspection
  • Prompt & Resource Extensibility: Scaffolding is included to support prompt templates and dynamic resource fetching, allowing future integration with LLMs for prompt orchestration or retrieval-augmented generation (RAG) use cases.
  • Built-in Testing & Debugging:
    • MCP Inspector: GUI for visualizing tool calls, input/output flows, and live debugging.
    • HTTP Test Script: Sends JSON-RPC requests to test endpoint responses.
    • Unit Tests: Jest-based testing framework for tool and utility logic.
  • Configurable & Secure: Easily adjustable through .env and runtime configuration files for:
    • Auth credentials and API keys
    • Server ports and transport options
    • Logging levels and session behaviors

Use Cases

This template is ideal for:

  • Building conversational MCP servers
  • Creating a backend to manage callable tools for LLM-based workflows

Whether you're prototyping an LLM toolchain, integrating with proprietary systems, or preparing a scalable production MCP assistant backend—this project offers a ready-to-extend and thoroughly structured solution.

Prerequisites

  • Node.js (version 18.x or later recommended)
  • npm (Node Package Manager)
  • Git (for cloning the repository)

Installation

  1. Clone the repository:
    git clone xxxx cd mcp-server-template
  2. Install dependencies:
    npm install
    This will install both production dependencies (e.g., @modelcontextprotocol/sdk, express, axios) and development dependencies (e.g., typescript, ts-node, jest) as defined in package.json.
  3. Ensure the @modelcontextprotocol/sdk package (version ^1.10.1) is installed, as it is the core dependency for MCP functionality.

Configuration

The project uses a configuration system managed through environment variables and two key files in src/core/config/. Settings are defined in ConfigService and runtimeConfig, allowing customization of transport types, logging, and external API integrations.

Configuration Options

  • Environment Variables (loaded via dotenv in runtimeConfig.ts):
    • TRANSPORT_TYPE: Sets the transport mechanism ('http' or 'stdio', default: 'stdio').
    • HTTP_PORT: Port for the HTTP server (default: 3000).
    • HTTP_HOST: Host for the HTTP server (default: localhost).
    • SESSION_SUPPORT: Enables/disables session support (default: 'true').
    • LOG_LEVEL: Logging level (e.g., 'info', 'debug', default: 'info').
    • MCP_INSPECTOR_PORT: Port for MCP inspector (default: 6274).

Example Configuration

Set environment variables in a .env file:

TRANSPORT_TYPE=http HTTP_PORT=3000 HTTP_HOST=localhost LOG_LEVEL=debug

Running the Server

The server is started via the entry point src/index.ts, which orchestrates the initialization and startup process using dependency injection and configuration settings.

Startup Process

  1. Environment Setup: index.ts loads environment variables using dotenv to ensure configuration settings (e.g., TRANSPORT_TYPE, HTTP_PORT) are available.
  2. Dependencies Initialization: Uses createDependencies to set up shared dependencies like the logger and ConfigService.
  3. Transport Configuration: The transport (HttpTransport or StdioTransport) is configured via runtimeConfig based on the TRANSPORT_TYPE setting.
  4. Server Initialization: Creates an MCPServer instance with the configured transport and dependencies.
  5. Server Start: Asynchronously starts the server, handling any fatal errors by logging and exiting with a failure code.

Starting the Server

  1. Production Mode:
    • Build the project to compile TypeScript to JavaScript:
      npm run build
      This runs tsc to generate the dist/ folder with compiled JavaScript files.
    • Start the server:
      npm start
      This executes node dist/index.js to run the compiled server.
    • For http, the server listens on http://localhost:3000/mcp (port and host configurable via HTTP_PORT and HTTP_HOST).
    • For stdio, the server reads from and writes to the console.
  2. Development Mode:
    • Run the server directly with TypeScript using ts-node:
      npm run dev
      This executes ts-node src/index.ts, allowing for faster iteration without a build step.

Notes

  • Ensure environment variables or runtimeConfig settings are correctly set before starting the server.
  • Check the console output for logs (controlled by LOG_LEVEL) to verify the server started successfully.

Testing

The project includes several scripts to test the server, debug its behavior, and verify functionality using automated tests and the MCP Inspector.

Unit Tests

Run unit tests using Jest to verify the functionality of individual components:

npm test

This executes jest, running all tests defined in the project (e.g., testing tools, utilities, or server logic). Ensure test files are set up with Jest and ts-jest for TypeScript support.

HTTP Transport Test

A test script is provided for the HTTP transport to verify basic functionality of the MCP server.

Script Details (src/scripts/testHttpTransport.js)
  • Purpose: Tests the HTTP transport by sending a JSON-RPC tools/list request to the server and validating the response.
  • Dependencies:
    • Uses axios to send HTTP POST requests to the server.
  • Functionality:
    • Sends a JSON-RPC 2.0 request to http://localhost:3000/mcp with method: 'tools/list', id: 1, and appropriate headers.
    • Validates the response to ensure:
      • The response adheres to JSON-RPC 2.0 (jsonrpc: '2.0').
      • The response id matches the request (id: 1).
      • The response contains a result field with the expected tools key.
    • Logs a success message with the response data if valid, or an error with the received data if the format is unexpected.
  • Error Handling:
    • Catches and logs any request failures (e.g., network errors, server not running) with the error message.
Running the Test
  1. Ensure the server is running with TRANSPORT_TYPE set to 'http':
    npm start
  2. Run the test script:
    npm run test:http
    This executes ts-node src/scripts/testHttpTransport.ts.
Combined Start and Test

To start the server and run the HTTP test in one command:

npm run mcp:http

This runs npm run start & npm run test:http, starting the server in the background and immediately running the HTTP test script.

Expected Output
  • Success Case: If the server responds correctly, the script logs:
    ✅ HTTP transport responded correctly to tools/list Response: { "tools": [ { "name": "calculator_tool", "description": "Performs basic arithmetic operations: add, subtract, multiply, divide.", "inputSchema": {...} } ] }
  • Failure Case (Invalid Response Format): If the response format is unexpected, the script logs:
    ❌ Response received, but unexpected format Received: {...}
  • Failure Case (Request Fails): If the request fails (e.g., server not running), the script logs:
    ❌ HTTP request failed: <error message>
Notes
  • The script assumes the server is running on http://localhost:3000/mcp. Adjust the endpoint in the script if HTTP_PORT or HTTP_HOST is different.
  • Ensure tools like CalculatorTool are registered to see them in the tools/list response.

MCP Inspector Debugging

The MCP Inspector is a powerful tool for debugging and monitoring the MCP server, providing a Web UI to inspect server state and interactions.

Script Details (src/scripts/mcpInspectorScript.ts)
  • Purpose: Launches the MCP Inspector, waits for its Web UI to be ready, and opens it in a browser for debugging the MCP server locally using stdio transport.
  • Dependencies:
    • Uses child_process to spawn the mcp-inspector process and execute browser-opening commands.
    • Uses axios to check if the MCP Inspector Web UI is reachable.
    • Leverages dependency injection via createDependencies() to access ConfigService for port configuration.
  • Functionality:
    • Spawns the mcp-inspector process using npx mcp-inspector node dist/index.js, inheriting stdio for console output.
    • Implements waitUntilInspectorIsReady to poll the Web UI (default port: 6274, configurable via MCP_INSPECTOR_PORT) with retries (20 attempts, 500ms delay).
    • Opens the Web UI in a platform-specific browser:
      • macOS: open
      • Windows: start
      • Linux: xdg-open
    • Logs a launch summary table with URLs:
      • MCP Inspector UI: http://localhost:6274 (or configured port)
      • MCP Proxy Server: http://localhost:6277
  • Error Handling:
    • Retries if the Web UI isn’t immediately available.
    • Throws an error and exits if the inspector fails to start after retries.
    • Kills the inspector process on failure and logs a message to manually check or restart.
Running the MCP Inspector
  1. Ensure the server is compiled (e.g., npm run build to generate dist/index.js).
  2. Run the MCP Inspector script:
    npm run mcp:inspector
    This executes ts-node src/scripts/start-mcp-inspector.ts.
Combined Build and Inspector

To build the project and launch the MCP Inspector in one command:

npm run mcp:dev

This runs npm run build && npm run mcp:inspector, ensuring the project is compiled before starting the inspector.

Debugging Tips
  • Use the MCP Inspector UI to monitor server requests, tool calls, and responses.
  • Check the console output for startup logs or errors if the inspector fails to launch.
  • Verify MCP_INSPECTOR_PORT is not in use by another service.

Code Formatting

The project uses Prettier to maintain consistent code formatting across all files.

Format Code

To format all files in the project:

npm run format

This executes prettier --write ., automatically formatting all supported files (e.g., .ts, .js, .json).

Check Formatting

To check if all files adhere to the Prettier formatting rules:

npm run format:check

This executes prettier --check ., reporting any files that do not conform to the formatting rules without modifying them.

Project Structure

  • src/core/config/
    • configService.ts: Implements ConfigService, a class for managing server configuration. It loads settings from environment variables with defaults for transport type, HTTP server settings, logging level, API URLs (e.g., MealDB), authentication credentials, and MCP inspector port.
    • runtimeConfig.ts: Defines runtime configuration using dotenv to load environment variables. It sets up transport configuration (transportType, port) and authentication strategy (authStrategy, tokenSecret, username, password).
  • src/core/dependencies/
    • dependencies.ts: Implements dependency injection with the Dependencies interface, providing a logger (using Winston) and a ConfigService instance. The createDependencies function dynamically configures logging transports based on transportType (stderr for stdio, stdout for others, plus a file log combined.log), and exports a singleton logger for global use.
  • src/core/server/
    • transports/
      • http/
      • server.ts: Implements HttpTransport, a stateless HTTP transport using Express. It handles POST /mcp requests, processes JSON-RPC messages with optional Bearer token authentication, stores responses in a ResponseMap, and supports sending responses asynchronously. It relies on dependency-injected Dependencies for logging and configuration.
        • stdio/
      • server.ts: Implements StdioTransport, a transport using the SDK’s StdioServerTransport. It manages stdin/stdout communication, starts and closes the transport, and handles message sending with error logging via dependency-injected Dependencies.
        • baseTransport.ts: Defines the BaseTransport interface and abstract AbstractTransport class, extending the SDK’s Transport interface. It specifies methods (start, send, close, isRunning) and event handlers (onmessage, onerror, onclose) for transport implementations, providing a common contract for HttpTransport and StdioTransport.
        • transportFactory.ts: Implements TransportFactory, a static class that creates instances of HttpTransport or StdioTransport based on the TransportConfig type (e.g., 'http' or 'stdio'). It uses dependency injection with Dependencies to provide logging and configuration, throwing an error for unsupported transport types.
    • mcpServer.ts: Implements MCPServer, the core server class that integrates the MCP SDK’s Server with a transport (HttpTransport or StdioTransport). It initializes the server, sets up a RequestHandler with a ToolRegistry, connects the transport, and handles message passing, errors, and responses using dependency-injected Dependencies for logging.
    • requestHandler.ts: Implements RequestHandler, which registers handlers for tools/list and tools/call requests using the MCP SDK. It lists available tools and executes tool calls with validated arguments (via Zod), supporting authentication tokens and throwing errors for invalid tools (ToolNotFoundError) or arguments (ValidationError). It uses dependency-injected Dependencies for logging.
  • src/core/toolManagement/
    • toolFactory.ts: Implements ToolFactory, a class that creates instances of tools (e.g., calculatorTool) using dependency injection with Dependencies. It defines a generic ToolConstructor type and handles instantiation errors with logging.
    • toolRegistry.ts: Implements ToolRegistry, a class that manages tool registration and retrieval. It uses ToolFactory to instantiate tools from toolClasses, stores them in a Map, and provides methods to register, get, and list tools with their metadata (name, description, input schema). It logs loading status and errors via dependency-injected Dependencies.
    • errors.ts: Defines custom error classes for tool management, including ToolNotFoundError (thrown when a requested tool isn’t registered) and ValidationError (thrown when tool arguments fail validation, e.g., via Zod).
    • types.ts: Defines TypeScript types for transport and authentication configurations. Includes TransportType ('stdio', 'sse', 'http'), TransportConfig (with options for SSE or HTTP and authentication), SSETransportConfig (port, CORS, auth), HttpStreamTransportConfig (port, response mode, CORS, session, resumability, auth), and AuthConfig (strategy, credentials).
  • src/prompts/: Directory for prompt templates (currently empty, reserved for future implementation).
  • src/resources/: Directory for resource management (currently empty, reserved for future implementation).
  • src/scripts/
    • testHttpTransport.js: Test script for the HTTP transport to verify basic functionality by sending a tools/list request and validating the response.
    • mcpInspectorScript.ts: Script to launch the MCP Inspector, wait for its Web UI to be ready, and open it in a browser for debugging the MCP server. It uses dependency injection to access ConfigService for port configuration and handles platform-specific browser opening.
  • src/tools/
    • types/
      • ITool.ts: Defines the ITool interface for tools, specifying name, description, schema (Zod type), jsonSchema, and the execute method for processing JSON-RPC CallToolRequest. Exports Dependencies for tool implementations.
      • baseTool.ts: Implements an abstract BaseTool class that reduces boilerplate, handles dependency injection with Dependencies, and automatically converts Zod schemas to JSON schemas using zod-to-json-schema for introspection, documentation, and UI generation.
      • index.ts: Exports toolClasses as an array of tool constructors (e.g., CalculatorTool) for dynamic loading by the ToolRegistry, allowing easy extension with new tools.
      • calculatorTool.ts: Implements CalculatorTool, a concrete tool that performs basic arithmetic operations (add, subtract, multiply, divide) with input validation via Zod, error handling (e.g., division by zero using HttpError), and logging via dependency-injected Dependencies.
    • utils/
      • httpUtils.ts: Provides utility functions for HTTP operations, including serviceRequest for making authenticated HTTP requests (OAuth2 or API key) with retries and timeout handling, getAuthToken for fetching and caching OAuth2 tokens, buildQueryString for creating query strings, and validateResponse for response validation. It integrates with ConfigService for configuration.
      • index.ts: Exports utility functions for use in tools and other components.
  • src/index.ts: Entry point to start the MCP server. Loads environment variables using dotenv, initializes dependencies with createDependencies, creates an MCPServer instance with the transport from runtimeConfig, and starts the server asynchronously, handling fatal errors by logging and exiting.

Troubleshooting

  • "Server not initialized" Error:
    • Ensure handlers are registered and capabilities are set in the MCPServer setup (via RequestHandler).
    • Verify the transport is connected immediately before handling each request (for HTTP).
    • Use the stateless approach (new server per request) if the error persists with a reused server.
  • Performance Issues:
    • Creating a new server per request may impact performance under high load. Consider reusing a single MCPServer with session management if needed, but test thoroughly.
  • Configuration Issues:
    • Ensure environment variables are correctly set in a .env file or passed directly to the process.
    • Check ConfigService logs to verify loaded settings if external API integrations (e.g., MealDB, OMDB) fail.
  • Logging Issues:
    • Verify LOG_LEVEL environment variable matches expected levels (e.g., 'info', 'debug').
    • For stdio transport, ensure logs are directed to stderr as intended; check combined.log for file-based logs.
  • Transport Issues:
    • For HttpTransport, ensure the port is available and no conflicting services are running.
    • For StdioTransport, check stdin/stdout availability if no messages are processed.
    • If TransportFactory fails, verify TRANSPORT_TYPE matches a supported type ('http' or 'stdio') in the configuration.
  • Request Handling Issues:
    • If tools/list or tools/call requests fail, check ToolRegistry for registered tools.
    • Validate tool arguments against the schema in CallToolRequestSchema to avoid ValidationError.
    • Ensure authentication tokens are provided if required by tools.
  • Tool Management Issues:
    • If tools fail to load, verify toolClasses in src/tools/index.ts includes valid tool implementations.
    • Check ToolFactory logs for instantiation errors and ensure Dependencies are properly injected.
  • MCP Inspector Issues:
    • If the MCP Inspector fails to start, verify MCP_INSPECTOR_PORT (default: 6274) is not in use.
    • Ensure dist/index.js exists by running npm run build before launching the script.
    • Check console output for errors during startup, such as network issues or missing dependencies.
  • HTTP Request Issues:
    • If serviceRequest fails, verify the authType, authEndpoint, clientId, clientSecret, or apiKey settings in ConfigService.
    • Check for network issues or server errors (5xx) that may trigger retries.
    • Ensure the request URL and method are correct, and validate the response schema with validateResponse.
  • HTTP Transport Test Issues:
    • If the testHttpTransport.js script fails, ensure the server is running with TRANSPORT_TYPE='http' and listening on http://localhost:3000/mcp.
    • Verify the port and host match the script’s endpoint (adjust if HTTP_PORT or HTTP_HOST is different).
    • Check for registered tools in ToolRegistry; an empty tools array may indicate a tool loading issue.
  • Testing Issues:
    • If npm test fails, ensure Jest is configured correctly with ts-jest for TypeScript support, and verify that test files exist.
    • If npm run mcp:inspector or npm run mcp:dev fails, check that @modelcontextprotocol/inspector is installed and the server is compiled (dist/index.js exists).
  • Formatting Issues:
    • If npm run format:check reports issues, run npm run format to automatically fix formatting, or manually adjust the files to match Prettier’s rules.

Contributing

Feel free to submit issues or pull requests on the GitHub repository. Contributions to improve the server implementation, add new features, or optimize performance are welcome!

License

This project is licensed under the ISC License. See the LICENSE file for details.

Acknowledgments

-
security - not tested
F
license - not found
-
quality - not tested

A TypeScript-based starter template for building Model Context Protocol servers that enables AI assistants to dynamically call tools, interpret prompts, and manage resources through modular architecture with support for multiple transport methods.

  1. Table of Contents
    1. Overview
      1. Key Capabilities
      2. Use Cases
    2. Prerequisites
      1. Installation
        1. Configuration
          1. Configuration Options
          2. Example Configuration
        2. Running the Server
          1. Startup Process
          2. Starting the Server
          3. Notes
        3. Testing
          1. Unit Tests
          2. HTTP Transport Test
          3. MCP Inspector Debugging
        4. Code Formatting
          1. Format Code
          2. Check Formatting
        5. Project Structure
          1. Troubleshooting
            1. Contributing
              1. License
                1. Acknowledgments

                  Related MCP Servers

                  • A
                    security
                    F
                    license
                    A
                    quality
                    A starter template for building Model Context Protocol servers that can be integrated with Cursor or Claude Desktop, allowing developers to create custom tools and extensions for AI assistants.
                    Last updated -
                    1
                    28
                    9
                    TypeScript
                  • -
                    security
                    A
                    license
                    -
                    quality
                    A TypeScript implementation of a Model Context Protocol server that provides a frictionless framework for developers to build and deploy AI tools and prompts, focusing on developer experience with zero boilerplate and automatic tool registration.
                    Last updated -
                    6
                    TypeScript
                    MIT License
                  • -
                    security
                    F
                    license
                    -
                    quality
                    A TypeScript framework for building Model Context Protocol (MCP) servers with automatic discovery and loading of tools, resources, and prompts.
                    Last updated -
                    67
                    TypeScript
                    • Apple
                  • -
                    security
                    F
                    license
                    -
                    quality
                    A Model Context Protocol implementation for managing and serving AI prompts with a TypeScript-based architecture in a monorepo structure.
                    Last updated -
                    28,526,583
                    2
                    TypeScript

                  View all related MCP servers

                  ID: 6l41001l9o