Sponsored by Deepsite.site

MCP TypeScript Template 🚀

Created By
cyanheads9 months ago
TypeScript template for building Model Context Protocol (MCP) servers & clients. A beginner-friendly, production-ready starting point with essential utilities, examples, and type safety.
Content

MCP TypeScript Template 🚀

TypeScript Model Context Protocol SDK MCP Spec Version Version License Status GitHub

Jumpstart your Model Context Protocol (MCP) Client & Server development with this TypeScript MCP Repo Template!

This template provides a solid, beginner-friendly foundation for building robust MCP servers and clients, adhering to the MCP 2025-03-26 specification. It includes production-ready utilities, a well-structured codebase, working examples, and clear documentation to get you up and running quickly.

Whether you're creating a new MCP server to extend an AI's capabilities or integrating MCP client features into your application, this template is your starting point.

📋 Table of Contents

✨ Key Features

Feature AreaDescriptionKey Components / Location
🔌 MCP ServerFunctional server with example tools (EchoTool, CatFactFetcher for async/Promise API example) and an EchoResource. Supports stdio and Streamable HTTP transports.src/mcp-server/
💻 MCP ClientWorking client aligned with MCP 2025-03-26 spec. Connects via mcp-config.json. Includes detailed comments.src/mcp-client/
🚀 Production UtilitiesLogging, Error Handling, ID Generation, Rate Limiting, Request Context tracking, Input Sanitization.src/utils/
🔒 Type Safety/SecurityStrong type checking via TypeScript & Zod validation. Built-in security utilities (sanitization, auth middleware stub for HTTP).Throughout, src/utils/security/, src/mcp-server/transports/authentication/
⚙️ Error HandlingConsistent error categorization (BaseErrorCode), detailed logging, centralized handling (ErrorHandler).src/utils/internal/errorHandler.ts, src/types-global/
📚 DocumentationComprehensive README.md, structured JSDoc comments, API referencesREADME.md, Codebase, tsdoc.json, docs/api-references/
🤖 Agent ReadyIncludes a .clinerules developer cheatsheet tailored for LLM coding agents..clinerules
🛠️ Utility ScriptsScripts for cleaning builds, setting executable permissions, generating directory trees, and fetching OpenAPI specs.scripts/
🧩 ServicesReusable modules for LLM (OpenRouter) and data storage (DuckDB) integration, with examples.src/services/, src/storage/duckdbExample.ts

For a more granular breakdown, see the Detailed Features Table below.

🌟 Projects Using This Template

This template is already powering several MCP servers, demonstrating its flexibility and robustness:

ProjectDescriptionStatus / Notes
pubmed-mcp-serverMCP server for PubMed, enabling AI agents to search, retrieve, analyze, and visualize biomedical literature via NCBI E-utilities. Features advanced research workflow capabilities.Actively using this template.
git-mcp-serverProvides an enterprise-ready MCP interface for Git operations. Allows LLM agents to initialize, clone, branch, commit, and manage repositories via STDIO & Streamable HTTP.Actively using this template.
obsidian-mcp-serverEnables LLMs to interact securely with Obsidian vaults via MCP. Offers token-aware tools for searching, navigating, and updating Obsidian notes, facilitating seamless knowledge base management with Properties management.Refactor in progress using this template (see branch).
atlas-mcp-serverAdvanced task and knowledge management system with Neo4j backend, enabling structured data organization and complex querying for AI agents.Aligned with this template (as of v2.8.8).
filesystem-mcp-serverOffers platform-agnostic file system capabilities for AI agents via MCP. Enables reading, writing, updating, and managing files/directories, featuring advanced search/replace and directory traversal.Actively using this template.

Note: toolkit-mcp-server was initially built using an older version of this template and is pending updates to the latest structure.

You can also see my GitHub profile for additional MCP servers I've created, many of which are planned to be migrated to or built upon this template in the future.

🏁 Quick Start

Get the example server running in minutes:

  1. Clone the repository:

    git clone https://github.com/cyanheads/mcp-ts-template.git
    cd mcp-ts-template
    
  2. Install dependencies:

    npm install
    
  3. Build the project:

    npm run build
    # Or use 'npm run rebuild' for a clean install (deletes node_modules, logs, dist)
    
  4. Format the code (Optional but Recommended):

    npm run format
    
  5. Run the Example Server:

    • Via Stdio (Default): Many MCP host applications will run this automatically using stdio. To run manually for testing:
      npm start
      # or 'npm run start:stdio'
      
    • Via Streamable HTTP:
      npm run start:http
      
      This starts a Streamable HTTP server (default: http://127.0.0.1:3010) which uses Server-Sent Events for the server-to-client streaming component. The port, host, and allowed origins are configurable via environment variables (see Configuration).

⚙️ Configuration

🔩 Server Configuration (Environment Variables)

Configure the MCP server's behavior using these environment variables:

VariableDescriptionDefault
MCP_TRANSPORT_TYPEServer transport: stdio or http.stdio
MCP_HTTP_PORTPort for the HTTP server (if MCP_TRANSPORT_TYPE=http).3010
MCP_HTTP_HOSTHost address for the HTTP server (if MCP_TRANSPORT_TYPE=http).127.0.0.1
MCP_ALLOWED_ORIGINSComma-separated allowed origins for CORS (if MCP_TRANSPORT_TYPE=http).(none)
MCP_SERVER_NAMEOptional server name (used in MCP initialization).(from package.json)
MCP_SERVER_VERSIONOptional server version (used in MCP initialization).(from package.json)
MCP_LOG_LEVELServer logging level (debug, info, warning, error, etc.).debug
LOGS_DIRDirectory for log files.logs/ (in project root)
NODE_ENVRuntime environment (development, production).development
MCP_AUTH_SECRET_KEYRequired for HTTP transport. Secret key (min 32 chars) for signing/verifying auth tokens (JWT).(none - MUST be set in production)
OPENROUTER_API_KEYAPI key for OpenRouter.ai service. Optional, but service will be unconfigured without it.(none)
LLM_DEFAULT_MODELDefault model to use for LLM calls via OpenRouter.google/gemini-2.5-flash-preview-05-20
LLM_DEFAULT_TEMPERATUREDefault temperature for LLM calls (0-2). Optional.(none)

Note on HTTP Port Retries: If the MCP_HTTP_PORT is busy, the server automatically tries the next port (up to 15 times).

Security Note for HTTP Transport: When using MCP_TRANSPORT_TYPE=http, authentication is mandatory as per the MCP specification. This template includes JWT-based authentication middleware (src/mcp-server/transports/authentication/authMiddleware.ts). You MUST set a strong, unique MCP_AUTH_SECRET_KEY in your production environment for this security mechanism to function correctly. Failure to do so will result in bypassed authentication checks in development and fatal errors in production.

🔌 Client Configuration

For detailed information on configuring the built-in MCP client, including how to set up connections to external MCP servers using mcp-config.json, please see the Client Configuration Guide.

🏗️ Project Structure

This project follows a standard TypeScript project layout. Here's an overview of the key directories and files:

  • .clinerules: Developer cheatsheet and guidelines for LLM coding agents working with this repository.
  • docs/: Contains project documentation, including API references and the auto-generated tree.md file.
  • scripts/: Utility scripts for development tasks like cleaning builds, generating directory trees, and fetching OpenAPI specs.
  • src/: The heart of the application, containing all TypeScript source code.
    • src/config/: Handles loading and validation of environment variables and application configuration.
    • src/mcp-client/: Implements the MCP client logic for connecting to and interacting with external MCP servers. This includes client configuration, core connection management, and transport handlers.
    • src/mcp-server/: Contains the MCP server implementation provided by this template, including example tools, resources, and transport handlers (Stdio, HTTP).
    • src/services/: Provides reusable modules for integrating with external services, such as DuckDB for local data storage and OpenRouter for LLM access.
    • src/types-global/: Defines shared TypeScript interfaces and type definitions used across the project, particularly for error handling and MCP-specific types.
    • src/utils/: A collection of core utilities.
      • src/utils/internal/: Core internal utilities like the logger, error handler, and request context management.
      • src/utils/metrics/: Utilities related to metrics, such as token counting.
      • src/utils/network/: Network-related utilities, like fetch with timeout.
      • src/utils/parsing/: Utilities for parsing data, such as dates and JSON.
      • src/utils/security/: Security-focused utilities including ID generation, rate limiting, and input sanitization.
    • src/index.ts: The main entry point for the application, responsible for initializing and starting the MCP server. The MCP client is meant to be built upon, so it does not have a dedicated entry point in this template.
  • package.json: Defines project metadata, dependencies, and npm scripts.
  • README.md: This file, providing an overview of the project.
  • tsconfig.json: TypeScript compiler options for the project.
  • LICENSE: Apache 2.0 License file.

Explore the full structure yourself:

See the current file tree in docs/tree.md or generate it dynamically:

npm run tree

(This uses scripts/tree.ts to generate a current file tree, respecting .gitignore.)

🧩 Extending the MCP Server

For detailed guidance on how to add your own custom Tools and Resources to this MCP server template, including workflow examples and best practices, please see the Server Extension Guide.

🌍 Explore More MCP Resources

Looking for more examples, guides, and pre-built MCP servers? Check out the companion repository:

➡️ cyanheads/model-context-protocol-resources

This collection includes servers for Filesystem, Obsidian, Git, GitHub, Perplexity, Atlas, Ntfy, and more, along with in-depth guides based on my real-world MCP development.

📜 License

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

📊 Detailed Features Table

CategoryFeatureDescriptionLocation(s)
Core ComponentsMCP ServerCore server logic, tool/resource registration, transport handling. Includes Echo Tool & Resource examples.src/mcp-server/
MCP ClientLogic for connecting to external MCP servers (updated to MCP 2025-03-26 spec). Refactored for modularity.src/mcp-client/ (see subdirs: core/, client-config/, transports/)
ConfigurationEnvironment-aware settings with Zod validation.src/config/, src/mcp-client/client-config/configLoader.ts
Streamable HTTP TransportExpress-based server implementing the MCP Streamable HTTP transport (utilizing Server-Sent Events for server-to-client streaming), with session management, CORS, and port retries.src/mcp-server/transports/httpTransport.ts
Stdio TransportHandles MCP communication over standard input/output.src/mcp-server/transports/stdioTransport.ts
Utilities (Core)LoggerStructured, context-aware logging (files with rotation & MCP notifications).src/utils/internal/logger.ts
ErrorHandlerCentralized error processing, classification, and logging.src/utils/internal/errorHandler.ts
RequestContextRequest/operation tracking and correlation.src/utils/internal/requestContext.ts
Utilities (Metrics)TokenCounterEstimates token counts using tiktoken.src/utils/metrics/tokenCounter.ts
Utilities (Parsing)DateParserParses natural language date strings using chrono-node.src/utils/parsing/dateParser.ts
JsonParserParses potentially partial JSON, handles <think> blocks.src/utils/parsing/jsonParser.ts
Utilities (Security)IdGeneratorGenerates unique IDs (prefixed or UUIDs).src/utils/security/idGenerator.ts
RateLimiterRequest throttling based on keys.src/utils/security/rateLimiter.ts
SanitizationInput validation/cleaning (HTML, paths, URLs, numbers, JSON) & log redaction (validator, sanitize-html).src/utils/security/sanitization.ts
ServicesDuckDB IntegrationReusable module for in-process analytical data management using DuckDB. A storage layer that runs on the same level as the application. Includes connection management, query execution, and example usage. Integrated with our utils (logger, etc.)src/services/duck-db/, src/storage/duckdbExample.ts
OpenRouter LLM IntegrationReusable module for interacting with various LLMs via the OpenRouter API (OpenAI SDK compatible). Includes a factory for client instantiation. Integrated with our utils (logger, etc.)src/services/llm-providers/openRouter/, src/services/llm-providers/llmFactory.ts
Type SafetyGlobal TypesShared TypeScript definitions for consistent interfaces (Errors, MCP types).src/types-global/
Zod SchemasUsed for robust validation of configuration files and tool/resource inputs.Throughout (config, mcp-client, tools, etc.)
Error HandlingPattern-Based ClassificationAutomatically categorize errors based on message patterns.src/utils/internal/errorHandler.ts
Consistent FormattingStandardized error responses with additional context.src/utils/internal/errorHandler.ts
Safe Try/Catch PatternsCentralized error processing helpers (ErrorHandler.tryCatch).src/utils/internal/errorHandler.ts
Client/Transport Error HandlingSpecific handlers for MCP client and transport error handling.src/mcp-client/core/, src/mcp-client/transports/
SecurityInput ValidationUsing validator and zod for various data type checks.src/utils/security/sanitization.ts, etc.
Input SanitizationUsing sanitize-html to prevent injection attacks.src/utils/security/sanitization.ts
Sensitive Data RedactionAutomatic redaction in logs.src/utils/security/sanitization.ts
Configuration FallbackSafely falls back to mcp-config.json.example if primary client config is missing.src/mcp-client/client-config/configLoader.ts
ScriptsClean ScriptRemoves dist and logs directories (or custom targets).scripts/clean.ts
Make Executable ScriptSets executable permissions (chmod +x) on specified files (Unix-like only).scripts/make-executable.ts
Tree ScriptGenerates a directory structure tree, respecting .gitignore.scripts/tree.ts
Fetch OpenAPI Spec ScriptFetches an OpenAPI spec (YAML/JSON) from a URL with fallbacks, saves locally.scripts/fetch-openapi-spec.ts

Built with ❤️ and the Model Context Protocol
Recommend Servers
TraeBuild with Free GPT-4.1 & Claude 3.7. Fully MCP-Ready.
Serper MCP ServerA Serper MCP Server
Howtocook Mcp基于Anduin2017 / HowToCook (程序员在家做饭指南)的mcp server,帮你推荐菜谱、规划膳食,解决“今天吃什么“的世纪难题; Based on Anduin2017/HowToCook (Programmer's Guide to Cooking at Home), MCP Server helps you recommend recipes, plan meals, and solve the century old problem of "what to eat today"
WindsurfThe new purpose-built IDE to harness magic
Playwright McpPlaywright MCP server
EdgeOne Pages MCPAn MCP service designed for deploying HTML content to EdgeOne Pages and obtaining an accessible public URL.
Baidu Map百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
CursorThe AI Code Editor
TimeA Model Context Protocol server that provides time and timezone conversion capabilities. This server enables LLMs to get current time information and perform timezone conversions using IANA timezone names, with automatic system timezone detection.
Jina AI MCP ToolsA Model Context Protocol (MCP) server that integrates with Jina AI Search Foundation APIs.
ChatWiseThe second fastest AI chatbot™
Zhipu Web SearchZhipu Web Search MCP Server is a search engine specifically designed for large models. It integrates four search engines, allowing users to flexibly compare and switch between them. Building upon the web crawling and ranking capabilities of traditional search engines, it enhances intent recognition capabilities, returning results more suitable for large model processing (such as webpage titles, URLs, summaries, site names, site icons, etc.). This helps AI applications achieve "dynamic knowledge acquisition" and "precise scenario adaptation" capabilities.
Tavily Mcp
DeepChatYour AI Partner on Desktop
BlenderBlenderMCP connects Blender to Claude AI through the Model Context Protocol (MCP), allowing Claude to directly interact with and control Blender. This integration enables prompt assisted 3D modeling, scene creation, and manipulation.
Amap Maps高德地图官方 MCP Server
MCP AdvisorMCP Advisor & Installation - Use the right MCP server for your needs
Context7Context7 MCP Server -- Up-to-date code documentation for LLMs and AI code editors
AiimagemultistyleA Model Context Protocol (MCP) server for image generation and manipulation using fal.ai's Stable Diffusion model.
Visual Studio Code - Open Source ("Code - OSS")Visual Studio Code
MiniMax MCPOfficial MiniMax Model Context Protocol (MCP) server that enables interaction with powerful Text to Speech, image generation and video generation APIs.