by cyanheads
Production‑grade TypeScript template for building Model Context Protocol servers with declarative tools, robust error handling, dependency injection, pluggable authentication, optional OpenTelemetry, and seamless support for both local execution and Cloudflare Workers edge runtimes.
Provides a ready‑to‑go scaffold for creating MCP servers. It handles tool and resource registration, DI, logging, error handling, authentication, storage abstraction, and observability out of the box, letting developers focus on business logic.
npx -y mcp-ts-template
.env file (e.g., MCP_TRANSPORT_TYPE=http, STORAGE_PROVIDER_TYPE=filesystem, STORAGE_FILESYSTEM_PATH=./data).bun install
bun start:http # HTTP transport
# or
bun start:stdio # STDIO transport
bun build:worker
bun deploy:prod # uses Wrangler
McpError system for consistent error responses.tsyringe.bun start:stdio or bun start:http.OTEL_ENABLED=true.*.tool.ts file in src/mcp-server/tools/definitions and export it via the barrel index.MCP_AUTH_MODE to none, jwt, or oauth and provide the required secret or issuer URL in the environment.McpError system ensures consistent, structured error responses across the server.none, jwt, or oauth modes.in-memory, filesystem, Supabase, SurrealDB, Cloudflare D1/KV/R2) without changing business logic. Features secure opaque cursor pagination, parallel batch operations, and comprehensive validation.tsyringe for a clean, decoupled, and testable architecture.This template follows a modular, domain-driven architecture with clear separation of concerns:
┌─────────────────────────────────────────────────────────┐
│ MCP Client (Claude Code, ChatGPT, etc.) │
└────────────────────┬────────────────────────────────────┘
│ JSON-RPC 2.0
▼
┌─────────────────────────────────────────────────────────┐
│ MCP Server (Tools, Resources) │
│ 📖 [MCP Server Guide](src/mcp-server/) │
└────────────────────┬────────────────────────────────────┘
│ Dependency Injection
▼
┌─────────────────────────────────────────────────────────┐
│ Dependency Injection Container │
│ 📦 [Container Guide](src/container/) │
└────────────────────┬────────────────────────────────────┘
│
┌────────────┼────────────┐
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Services │ │ Storage │ │ Utilities│
│ 🔌 [→] │ │ 💾 [→] │ │ 🛠️ [→] │
└──────────┘ └──────────┘ └──────────┘
[→]: src/services/ [→]: src/storage/ [→]: src/utils/
Key Modules:
💡 Tip: Each module has its own comprehensive README with architecture diagrams, usage examples, and best practices. Click the links above to dive deeper!
This template includes working examples to get you started.
| Tool | Description |
|---|---|
template_echo_message |
Echoes a message back with optional formatting and repetition. |
template_cat_fact |
Fetches a random cat fact from an external API. |
template_madlibs_elicitation |
Demonstrates elicitation by asking for words to complete a story. |
template_code_review_sampling |
Uses the LLM service to perform a simulated code review. |
template_image_test |
Returns a test image as a base64-encoded data URI. |
| Resource | URI | Description |
|---|---|---|
echo |
echo://{message} |
A simple resource that echoes back a message. |
| Prompt | Description |
|---|---|
code-review |
A structured prompt for guiding an LLM to perform a code review. |
Add the following to your MCP Client configuration file (e.g., cline_mcp_settings.json).
{
"mcpServers": {
"mcp-ts-template": {
"type": "stdio",
"command": "bunx",
"args": ["mcp-ts-template@latest"],
"env": {
"MCP_TRANSPORT_TYPE": "stdio",
"MCP_LOG_LEVEL": "info",
"STORAGE_PROVIDER_TYPE": "filesystem",
"STORAGE_FILESYSTEM_PATH": "/path/to/your/storage"
}
}
}
}
git clone https://github.com/cyanheads/mcp-ts-template.git
cd mcp-ts-template
bun install
All configuration is centralized and validated at startup in src/config/index.ts. Key environment variables in your .env file include:
| Variable | Description | Default |
|---|---|---|
MCP_TRANSPORT_TYPE |
The transport to use: stdio or http. |
http |
MCP_HTTP_PORT |
The port for the HTTP server. | 3010 |
MCP_HTTP_HOST |
The hostname for the HTTP server. | 127.0.0.1 |
MCP_AUTH_MODE |
Authentication mode: none, jwt, or oauth. |
none |
MCP_AUTH_SECRET_KEY |
Required for jwt auth mode. A 32+ character secret. |
(none) |
OAUTH_ISSUER_URL |
Required for oauth auth mode. URL of the OIDC provider. |
(none) |
STORAGE_PROVIDER_TYPE |
Storage backend: in-memory, filesystem, supabase, surrealdb, cloudflare-d1, cloudflare-kv, cloudflare-r2. |
in-memory |
STORAGE_FILESYSTEM_PATH |
Required for filesystem storage. Path to the storage directory. |
(none) |
SUPABASE_URL |
Required for supabase storage. Your Supabase project URL. |
(none) |
SUPABASE_SERVICE_ROLE_KEY |
Required for supabase storage. Your Supabase service role key. |
(none) |
SURREALDB_URL |
Required for surrealdb storage. SurrealDB endpoint (e.g., wss://cloud.surrealdb.com/rpc). |
(none) |
SURREALDB_NAMESPACE |
Required for surrealdb storage. SurrealDB namespace. |
(none) |
SURREALDB_DATABASE |
Required for surrealdb storage. SurrealDB database name. |
(none) |
SURREALDB_USERNAME |
Optional for surrealdb storage. Database username for authentication. |
(none) |
SURREALDB_PASSWORD |
Optional for surrealdb storage. Database password for authentication. |
(none) |
OTEL_ENABLED |
Set to true to enable OpenTelemetry. |
false |
LOG_LEVEL |
The minimum level for logging (debug, info, warn, error). |
info |
OPENROUTER_API_KEY |
API key for OpenRouter LLM service. | (none) |
none (default), jwt (requires MCP_AUTH_SECRET_KEY), or oauth (requires OAUTH_ISSUER_URL and OAUTH_AUDIENCE).logic functions with withToolAuth([...]) or withResourceAuth([...]) to enforce scope checks. Scope checks are bypassed for developer convenience when auth mode is none.StorageService provides a consistent API for persistence. Never access fs or other storage SDKs directly from tool logic.in-memory. Node-only providers include filesystem. Edge-compatible providers include supabase, surrealdb, cloudflare-kv, and cloudflare-r2.surrealdb provider, initialize the database schema using docs/surrealdb-schema.surql before first use.StorageService requires context.tenantId. This is automatically propagated from the tid claim in a JWT when auth is enabled.getMany(), setMany(), deleteMany()RequestContext.OTEL_ENABLED=true and configure OTLP endpoints. Traces, metrics (duration, payload sizes), and errors are automatically captured for every tool call.Build and run the production version:
# One-time build
bun rebuild
# Run the built server
bun start:http
# or
bun start:stdio
Run checks and tests:
bun devcheck # Lints, formats, type-checks, and more
bun run test # Runs the test suite (Do not use 'bun test' directly as it may not work correctly)
bun build:worker
bun deploy:dev
bun deploy:prod
Note: The
wrangler.tomlfile is pre-configured to enablenodejs_compatfor best results.
| Directory | Purpose & Contents | Guide |
|---|---|---|
src/mcp-server/tools/definitions |
Your tool definitions (*.tool.ts). This is where you add new capabilities. |
📖 MCP Guide |
src/mcp-server/resources/definitions |
Your resource definitions (*.resource.ts). This is where you add new data sources. |
📖 MCP Guide |
src/mcp-server/transports |
Implementations for HTTP and STDIO transports, including auth middleware. | 📖 MCP Guide |
src/storage |
The StorageService abstraction and all storage provider implementations. |
💾 Storage Guide |
src/services |
Integrations with external services (e.g., the default OpenRouter LLM provider). | 🔌 Services Guide |
src/container |
Dependency injection container registrations and tokens. | 📦 Container Guide |
src/utils |
Core utilities for logging, error handling, performance, security, and telemetry. | |
src/config |
Environment variable parsing and validation with Zod. | |
tests/ |
Unit and integration tests, mirroring the src/ directory structure. |
Each major module includes comprehensive documentation with architecture diagrams, usage examples, and best practices:
MCP Server Guide - Complete guide to building MCP tools and resources
Container Guide - Dependency injection with tsyringe
Services Guide - External service integration patterns
Storage Guide - Abstracted persistence layer
For a strict set of rules when using this template with an AI agent, please refer to AGENTS.md. Key principles include:
try/catch in your tool/resource logic. Throw an McpError instead.elicitInput function from the SdkContext to ask the user for it.RequestContext object through your call stack.index.ts barrel files.bun run dev:stdio or bun run dev:http.bun run build:worker and deploy with Wrangler.OTEL_ENABLED=true in your .env file.docs/publishing-mcp-server-registry.md.Issues and pull requests are welcome! If you plan to contribute, please run the local checks and tests before submitting your PR.
bun run devcheck
bun test
This project is licensed under the Apache 2.0 License. See the LICENSE file for details.
Please log in to share your review and rating for this MCP.
{
"mcpServers": {
"mcp-ts-template": {
"command": "npx",
"args": [
"-y",
"mcp-ts-template"
],
"env": {
"MCP_TRANSPORT_TYPE": "http",
"MCP_AUTH_MODE": "none",
"STORAGE_PROVIDER_TYPE": "filesystem",
"STORAGE_FILESYSTEM_PATH": "./data"
}
}
}
}claude mcp add mcp-ts-template npx -y mcp-ts-templateExplore related MCPs that share similar capabilities and solve comparable challenges
by zed-industries
A high‑performance, multiplayer code editor designed for speed and collaboration.
by modelcontextprotocol
Model Context Protocol Servers
by modelcontextprotocol
A Model Context Protocol server for Git repository interaction and automation.
by modelcontextprotocol
A Model Context Protocol server that provides time and timezone conversion capabilities.
by cline
An autonomous coding assistant that can create and edit files, execute terminal commands, and interact with a browser directly from your IDE, operating step‑by‑step with explicit user permission.
by continuedev
Enables faster shipping of code by integrating continuous AI agents across IDEs, terminals, and CI pipelines, offering chat, edit, autocomplete, and customizable agent workflows.
by upstash
Provides up-to-date, version‑specific library documentation and code examples directly inside LLM prompts, eliminating outdated information and hallucinated APIs.
by github
Connects AI tools directly to GitHub, enabling natural‑language interactions for repository browsing, issue and pull‑request management, CI/CD monitoring, code‑security analysis, and team collaboration.
by daytonaio
Provides a secure, elastic infrastructure that creates isolated sandboxes for running AI‑generated code with sub‑90 ms startup, unlimited persistence, and OCI/Docker compatibility.