šŸš€ Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more →
Socket
DemoInstallSign in
Socket

mcp-ts-template

Package Overview
Dependencies
Maintainers
1
Versions
22
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

mcp-ts-template

TypeScript template for building Model Context Protocol (MCP) Servers & Clients. Features extensive utilities (logger, requestContext, etc.), STDIO & Streamable HTTP (with authMiddleware), examples, and type safety. Ideal starting point for creating produ

1.5.0
latest
Source
npm
Version published
Weekly downloads
153
-64.25%
Maintainers
1
Weekly downloads
Ā 
Created
Source

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:

  • Clone the repository:

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

    npm install
    
  • Build the project:

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

    npm run format
    
  • 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)
MCP_AUTH_MODEAuthentication mode: jwt (default) or oauth.jwt
OAUTH_ISSUER_URLRequired for oauth mode. The issuer URL of your authorization server.(none)
OAUTH_AUDIENCERequired for oauth mode. The audience identifier for this MCP server.(none)
OAUTH_JWKS_URIOptional for oauth mode. The JWKS endpoint URL. If omitted, it's discovered from the issuer.(none)
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 supports two modes via MCP_AUTH_MODE:

  • jwt (default): A simple, self-contained JWT mode ideal for development. It requires the MCP_AUTH_SECRET_KEY to be set for signing and verifying tokens.
  • oauth: A production-ready OAuth 2.1 mode where the server validates Bearer tokens from an external Authorization Server. This requires OAUTH_ISSUER_URL and OAUTH_AUDIENCE to be configured.

You MUST configure one of these modes for the security mechanism to function correctly when using the HTTP transport.

šŸ”Œ 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 TransportHono-based server implementing the MCP Streamable HTTP transport 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). Integrated with our utils (logger, etc.)src/services/llm-providers/openRouterProvider.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 ValidationThrows a descriptive error if the primary client config (mcp-config.json) is missing, preventing fallback to a potentially insecure example file.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

Keywords

typescript

FAQs

Package last updated on 12 Jun 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts