mcp-ts-template 1.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +233 -0
  3. package/dist/config/index.d.ts +73 -0
  4. package/dist/config/index.js +125 -0
  5. package/dist/index.d.ts +2 -0
  6. package/dist/index.js +162 -0
  7. package/dist/mcp-client/client.d.ts +36 -0
  8. package/dist/mcp-client/client.js +276 -0
  9. package/dist/mcp-client/configLoader.d.ts +75 -0
  10. package/dist/mcp-client/configLoader.js +203 -0
  11. package/dist/mcp-client/index.d.ts +10 -0
  12. package/dist/mcp-client/index.js +14 -0
  13. package/dist/mcp-client/transport.d.ts +34 -0
  14. package/dist/mcp-client/transport.js +183 -0
  15. package/dist/mcp-server/resources/echoResource/echoResourceLogic.d.ts +38 -0
  16. package/dist/mcp-server/resources/echoResource/echoResourceLogic.js +40 -0
  17. package/dist/mcp-server/resources/echoResource/index.d.ts +5 -0
  18. package/dist/mcp-server/resources/echoResource/index.js +5 -0
  19. package/dist/mcp-server/resources/echoResource/registration.d.ts +12 -0
  20. package/dist/mcp-server/resources/echoResource/registration.js +122 -0
  21. package/dist/mcp-server/server.d.ts +27 -0
  22. package/dist/mcp-server/server.js +176 -0
  23. package/dist/mcp-server/tools/echoTool/echoToolLogic.d.ts +68 -0
  24. package/dist/mcp-server/tools/echoTool/echoToolLogic.js +73 -0
  25. package/dist/mcp-server/tools/echoTool/index.d.ts +5 -0
  26. package/dist/mcp-server/tools/echoTool/index.js +5 -0
  27. package/dist/mcp-server/tools/echoTool/registration.d.ts +12 -0
  28. package/dist/mcp-server/tools/echoTool/registration.js +86 -0
  29. package/dist/mcp-server/transports/authentication/authMiddleware.d.ts +57 -0
  30. package/dist/mcp-server/transports/authentication/authMiddleware.js +145 -0
  31. package/dist/mcp-server/transports/httpTransport.d.ts +23 -0
  32. package/dist/mcp-server/transports/httpTransport.js +411 -0
  33. package/dist/mcp-server/transports/stdioTransport.d.ts +40 -0
  34. package/dist/mcp-server/transports/stdioTransport.js +70 -0
  35. package/dist/types-global/errors.d.ts +73 -0
  36. package/dist/types-global/errors.js +66 -0
  37. package/dist/utils/index.d.ts +4 -0
  38. package/dist/utils/index.js +12 -0
  39. package/dist/utils/internal/errorHandler.d.ts +90 -0
  40. package/dist/utils/internal/errorHandler.js +247 -0
  41. package/dist/utils/internal/index.d.ts +3 -0
  42. package/dist/utils/internal/index.js +3 -0
  43. package/dist/utils/internal/logger.d.ts +50 -0
  44. package/dist/utils/internal/logger.js +267 -0
  45. package/dist/utils/internal/requestContext.d.ts +47 -0
  46. package/dist/utils/internal/requestContext.js +48 -0
  47. package/dist/utils/metrics/index.d.ts +1 -0
  48. package/dist/utils/metrics/index.js +1 -0
  49. package/dist/utils/metrics/tokenCounter.d.ts +27 -0
  50. package/dist/utils/metrics/tokenCounter.js +124 -0
  51. package/dist/utils/parsing/dateParser.d.ts +27 -0
  52. package/dist/utils/parsing/dateParser.js +62 -0
  53. package/dist/utils/parsing/index.d.ts +2 -0
  54. package/dist/utils/parsing/index.js +2 -0
  55. package/dist/utils/parsing/jsonParser.d.ts +46 -0
  56. package/dist/utils/parsing/jsonParser.js +79 -0
  57. package/dist/utils/security/idGenerator.d.ts +93 -0
  58. package/dist/utils/security/idGenerator.js +147 -0
  59. package/dist/utils/security/index.d.ts +3 -0
  60. package/dist/utils/security/index.js +3 -0
  61. package/dist/utils/security/rateLimiter.d.ts +92 -0
  62. package/dist/utils/security/rateLimiter.js +171 -0
  63. package/dist/utils/security/sanitization.d.ts +180 -0
  64. package/dist/utils/security/sanitization.js +372 -0
  65. package/package.json +79 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 Casey Hand @cyanheads
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,233 @@
1
+ # MCP TypeScript Template 🚀
2
+
3
+ [![TypeScript](https://img.shields.io/badge/TypeScript-^5.8.3-blue.svg)](https://www.typescriptlang.org/)
4
+ [![Model Context Protocol SDK](https://img.shields.io/badge/MCP%20SDK-1.11.0-green.svg)](https://github.com/modelcontextprotocol/typescript-sdk)
5
+ [![MCP Spec Version](https://img.shields.io/badge/MCP%20Spec-2025--03--26-lightgrey.svg)](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/docs/specification/2025-03-26/changelog.mdx)
6
+ [![Version](https://img.shields.io/badge/Version-1.1.5-blue.svg)](./CHANGELOG.md)
7
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
8
+ [![Status](https://img.shields.io/badge/Status-Stable-green.svg)](https://github.com/cyanheads/mcp-ts-template/issues)
9
+ [![GitHub](https://img.shields.io/github/stars/cyanheads/mcp-ts-template?style=social)](https://github.com/cyanheads/mcp-ts-template)
10
+
11
+ **Jumpstart your [Model Context Protocol (MCP) Client & Server](https://modelcontextprotocol.io/) development with this TypeScript Repo Template!**
12
+
13
+ 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.
14
+
15
+ 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.
16
+
17
+ ## ✨ Key Features
18
+
19
+ | Feature Area | Description | Key Components / Location |
20
+ | :-------------------------- | :------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------- |
21
+ | **🔌 MCP Server** | Functional server example with Echo Tool & Resource. Supports `stdio` and `http` (SSE) transports. | `src/mcp-server/` |
22
+ | **💻 MCP Client** | Working client aligned with **MCP 2025-03-26 spec**. Connects via `mcp-config.json`. Includes detailed comments. | `src/mcp-client/` |
23
+ | **🚀 Production Utilities** | Logging, Error Handling, ID Generation, Rate Limiting, Request Context tracking, Input Sanitization. | `src/utils/` |
24
+ | **🔒 Type Safety/Security** | Strong 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/` |
25
+ | **⚙️ Error Handling** | Consistent error categorization (`BaseErrorCode`), detailed logging, centralized handling (`ErrorHandler`). | `src/utils/internal/errorHandler.ts`, `src/types-global/` |
26
+ | **📚 Documentation** | Comprehensive `README.md`, inline JSDoc comments. | `README.md`, Codebase |
27
+ | **🤖 Agent Ready** | Includes a [.clinerules](.clinerules) developer cheatsheet tailored for LLM coding agents. | `.clinerules` |
28
+ | **🛠️ Utility Scripts** | Scripts for cleaning builds, setting executable permissions, generating directory trees, and fetching OpenAPI specs. | `scripts/` |
29
+
30
+ _For a more granular breakdown, see the [Detailed Features Table](#detailed-features-table) below._
31
+
32
+ ## 🚀 Projects Using This Template
33
+
34
+ This template is already powering several MCP servers, demonstrating its flexibility and robustness:
35
+
36
+ | Project | Description | Status / Notes |
37
+ | :-------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------- |
38
+ | [**git-mcp-server**](https://github.com/cyanheads/git-mcp-server) | Provides 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. |
39
+ | [**obsidian-mcp-server**](https://github.com/cyanheads/obsidian-mcp-server/tree/mcp-ts-template-refactor) | Enables 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](https://github.com/cyanheads/obsidian-mcp-server/tree/mcp-ts-template-refactor)). |
40
+ | [**filesystem-mcp-server**](https://github.com/cyanheads/filesystem-mcp-server) | Offers 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. |
41
+
42
+ _Note: [**toolkit-mcp-server**](https://github.com/cyanheads/toolkit-mcp-server) and [**atlas-mcp-server**](https://github.com/cyanheads/atlas-mcp-server) were initially built using an older version of this template and are pending updates to the latest structure._
43
+
44
+ You can also **see my [GitHub profile](https://github.com/cyanheads/)** for additional MCP servers I've created, many of which are planned to be migrated to or built upon this template in the future.
45
+
46
+ ## 📋 Table of Contents
47
+
48
+ [✨ Key Features](#-key-features) | [🚀 Projects Using This Template](#-projects-using-this-template) | [🚀 Quick Start](#quick-start) | [⚙️ Configuration](#️-configuration) | [Server Configuration](#server-configuration-environment-variables) | [Client Configuration](#client-configuration-mcp-configjson) | [🏗️ Project Structure](#️-project-structure) | [🧩 Adding Tools/Resources](#-adding-your-own-tools--resources) | [🌍 More MCP Resources](#-explore-more-mcp-resources) | [📜 License](#-license) | [Detailed Features](#detailed-features-table)
49
+
50
+ ## Quick Start
51
+
52
+ Get the example server running in minutes:
53
+
54
+ 1. **Clone the repository:**
55
+
56
+ ```bash
57
+ git clone https://github.com/cyanheads/mcp-ts-template.git
58
+ cd mcp-ts-template
59
+ ```
60
+
61
+ 2. **Install dependencies:**
62
+
63
+ ```bash
64
+ npm install
65
+ ```
66
+
67
+ 3. **Build the project:**
68
+
69
+ ```bash
70
+ npm run build
71
+ # Or use 'npm run rebuild' for a clean install (deletes node_modules, logs, dist)
72
+ ```
73
+
74
+ 4. **Run the Example Server:**
75
+
76
+ - **Via Stdio (Default):** Many MCP host applications will run this automatically using `stdio`. To run manually for testing:
77
+ ```bash
78
+ npm start
79
+ # or 'npm run start:stdio'
80
+ ```
81
+ - **Via HTTP (SSE):**
82
+ ```bash
83
+ npm run start:http
84
+ ```
85
+ This starts an HTTP server (default: `http://127.0.0.1:3010`) using Server-Sent Events. The port, host, and allowed origins are configurable via environment variables (see [Configuration](#configuration)).
86
+
87
+ ## ⚙️ Configuration
88
+
89
+ ### Server Configuration (Environment Variables)
90
+
91
+ Configure the MCP server's behavior using these environment variables:
92
+
93
+ | Variable | Description | Default |
94
+ | :-------------------- | :-------------------------------------------------------------------------------------------------- | :------------------------------------- |
95
+ | `MCP_TRANSPORT_TYPE` | Server transport: `stdio` or `http`. | `stdio` |
96
+ | `MCP_HTTP_PORT` | Port for the HTTP server (if `MCP_TRANSPORT_TYPE=http`). | `3010` |
97
+ | `MCP_HTTP_HOST` | Host address for the HTTP server (if `MCP_TRANSPORT_TYPE=http`). | `127.0.0.1` |
98
+ | `MCP_ALLOWED_ORIGINS` | Comma-separated allowed origins for CORS (if `MCP_TRANSPORT_TYPE=http`). | (none) |
99
+ | `MCP_SERVER_NAME` | Optional server name (used in MCP initialization). | (from package.json) |
100
+ | `MCP_SERVER_VERSION` | Optional server version (used in MCP initialization). | (from package.json) |
101
+ | `MCP_LOG_LEVEL` | Server logging level (`debug`, `info`, `warning`, `error`, etc.). | `info` |
102
+ | `NODE_ENV` | Runtime environment (`development`, `production`). | `development` |
103
+ | `MCP_AUTH_SECRET_KEY` | **Required for HTTP transport.** Secret key (min 32 chars) for signing/verifying auth tokens (JWT). | (none - **MUST be set in production**) |
104
+
105
+ **Note on HTTP Port Retries:** If the `MCP_HTTP_PORT` is busy, the server automatically tries the next port (up to 15 times).
106
+
107
+ **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.
108
+
109
+ ### Client Configuration (`mcp-config.json`)
110
+
111
+ Configure the connections for the built-in **MCP client** using `src/mcp-client/mcp-config.json`. If this file is missing, it falls back to `src/mcp-client/mcp-config.json.example`.
112
+
113
+ This file defines external MCP servers the client can connect to. The client implementation adheres to the **MCP 2025-03-26 specification**.
114
+
115
+ **Example `mcp-config.json` (see `mcp-config.json.example` for the full version):**
116
+
117
+ ```json
118
+ {
119
+ "mcpServers": {
120
+ "my-stdio-server": {
121
+ "command": "node", // Command or executable
122
+ "args": ["/path/to/my-server/index.js"], // Arguments for stdio
123
+ "env": { "LOG_LEVEL": "debug" }, // Optional environment variables
124
+ "transportType": "stdio" // Explicitly stdio (or omit for default)
125
+ },
126
+ "my-http-server": {
127
+ "command": "http://localhost:8080", // Base URL for HTTP
128
+ "args": [], // Not used for HTTP
129
+ "env": {}, // Not used for HTTP
130
+ "transportType": "http" // Explicitly http
131
+ }
132
+ // ... add other servers
133
+ }
134
+ }
135
+ ```
136
+
137
+ - **`command`**: Executable path (`stdio`) or Base URL (`http`).
138
+ - **`args`**: Array of arguments (required for `stdio`).
139
+ - **`env`**: Optional environment variables to set for the server process (`stdio`).
140
+ - **`transportType`**: `stdio` (default) or `http`.
141
+
142
+ See `src/mcp-client/configLoader.ts` for the Zod validation schema and `src/mcp-client/mcp-config.json.example` for a complete example.
143
+
144
+ ## 🏗️ Project Structure
145
+
146
+ The `src/` directory is organized for clarity:
147
+
148
+ - `config/`: Loads environment variables and package info.
149
+ - `mcp-client/`: Logic for the client connecting to _external_ MCP servers (updated to MCP 2025-03-26 spec).
150
+ - `client.ts`: Core connection management, initialization, capability declaration.
151
+ - `configLoader.ts`: Loads and validates `mcp-config.json`.
152
+ - `transport.ts`: Creates `stdio` or `http` client transports based on config.
153
+ - `mcp-config.json.example`: Example client config. Copy to `mcp-config.json`.
154
+ - `mcp-server/`: Logic for the MCP server _provided by this template_.
155
+ - `server.ts`: Initializes the server, registers tools/resources.
156
+ - `resources/`: Example resource implementations (e.g., EchoResource).
157
+ - `tools/`: Example tool implementations (e.g., EchoTool).
158
+ - `transports/`: Handles `stdio` and `http` communication for the server.
159
+ - `types-global/`: Shared TypeScript definitions (Errors, MCP types).
160
+ - `utils/`: Reusable utilities (logging, errors, security, parsing, etc.). Exported via `index.ts`.
161
+
162
+ **Explore the structure yourself:**
163
+
164
+ ```bash
165
+ npm run tree
166
+ ```
167
+
168
+ (This uses `scripts/tree.ts` to generate a current file tree.)
169
+
170
+ ## 🧩 Adding Your Own Tools & Resources
171
+
172
+ This template is designed for extension! Follow the high-level SDK patterns:
173
+
174
+ 1. **Create Directories**: Add new directories under `src/mcp-server/tools/yourToolName/` or `src/mcp-server/resources/yourResourceName/`.
175
+ 2. **Implement Logic (`logic.ts`)**: Define Zod schemas for inputs/outputs and write your core processing function.
176
+ 3. **Register (`registration.ts`)**:
177
+ - **Tools**: Use `server.tool(name, description, zodSchemaShape, handler)` (SDK v1.10.2+). This handles schema generation, validation, and routing. Remember to add relevant annotations (`readOnlyHint`, `destructiveHint`, etc.) as untrusted hints.
178
+ - **Resources**: Use `server.resource(regName, template, metadata, handler)`.
179
+ - Wrap logic in `ErrorHandler.tryCatch` for robust error handling.
180
+ 4. **Export & Import**: Export the registration function from your new directory's `index.ts` and call it within `createMcpServerInstance` in `src/mcp-server/server.ts`.
181
+
182
+ Refer to the included `EchoTool` and `EchoResource` examples and the [.clinerules](.clinerules) cheatsheet for detailed patterns.
183
+
184
+ ## 🌍 Explore More MCP Resources
185
+
186
+ Looking for more examples, guides, and pre-built MCP servers? Check out the companion repository:
187
+
188
+ ➡️ **[cyanheads/model-context-protocol-resources](https://github.com/cyanheads/model-context-protocol-resources)**
189
+
190
+ 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.
191
+
192
+ ## 📜 License
193
+
194
+ This project is licensed under the Apache License 2.0. See the [LICENSE](LICENSE) file for details.
195
+
196
+ ## Detailed Features Table
197
+
198
+ | Category | Feature | Description | Location(s) |
199
+ | :----------------------- | :------------------------------ | :----------------------------------------------------------------------------------------------------------- | :----------------------------------------------- |
200
+ | **Core Components** | MCP Server | Core server logic, tool/resource registration, transport handling. Includes Echo Tool & Resource examples. | `src/mcp-server/` |
201
+ | | MCP Client | Logic for connecting to external MCP servers (updated to **MCP 2025-03-26 spec**). | `src/mcp-client/` |
202
+ | | Configuration | Environment-aware settings with Zod validation. | `src/config/`, `src/mcp-client/configLoader.ts` |
203
+ | | HTTP Transport | Express-based server with SSE, session management, CORS, port retries. | `src/mcp-server/transports/httpTransport.ts` |
204
+ | | Stdio Transport | Handles MCP communication over standard input/output. | `src/mcp-server/transports/stdioTransport.ts` |
205
+ | **Utilities (Core)** | Logger | Structured, context-aware logging (files & MCP notifications). | `src/utils/internal/logger.ts` |
206
+ | | ErrorHandler | Centralized error processing, classification, and logging. | `src/utils/internal/errorHandler.ts` |
207
+ | | RequestContext | Request/operation tracking and correlation. | `src/utils/internal/requestContext.ts` |
208
+ | **Utilities (Metrics)** | TokenCounter | Estimates token counts using `tiktoken`. | `src/utils/metrics/tokenCounter.ts` |
209
+ | **Utilities (Parsing)** | DateParser | Parses natural language date strings using `chrono-node`. | `src/utils/parsing/dateParser.ts` |
210
+ | | JsonParser | Parses potentially partial JSON, handles `<think>` blocks. | `src/utils/parsing/jsonParser.ts` |
211
+ | **Utilities (Security)** | IdGenerator | Generates unique IDs (prefixed or UUIDs). | `src/utils/security/idGenerator.ts` |
212
+ | | RateLimiter | Request throttling based on keys. | `src/utils/security/rateLimiter.ts` |
213
+ | | Sanitization | Input validation/cleaning (HTML, paths, URLs, numbers, JSON) & log redaction (`validator`, `sanitize-html`). | `src/utils/security/sanitization.ts` |
214
+ | **Type Safety** | Global Types | Shared TypeScript definitions for consistent interfaces (Errors, MCP types). | `src/types-global/` |
215
+ | | Zod Schemas | Used for robust validation of configuration files and tool/resource inputs. | Throughout (`config`, `mcp-client`, tools, etc.) |
216
+ | **Error Handling** | Pattern-Based Classification | Automatically categorize errors based on message patterns. | `src/utils/internal/errorHandler.ts` |
217
+ | | Consistent Formatting | Standardized error responses with additional context. | `src/utils/internal/errorHandler.ts` |
218
+ | | Safe Try/Catch Patterns | Centralized error processing helpers (`ErrorHandler.tryCatch`). | `src/utils/internal/errorHandler.ts` |
219
+ | | Client/Transport Error Handling | Specific handlers for MCP client and transport error handling. | `src/mcp-client/client.ts`, `transport.ts` |
220
+ | **Security** | Input Validation | Using `validator` and `zod` for various data type checks. | `src/utils/security/sanitization.ts`, etc. |
221
+ | | Input Sanitization | Using `sanitize-html` to prevent injection attacks. | `src/utils/security/sanitization.ts` |
222
+ | | Sensitive Data Redaction | Automatic redaction in logs. | `src/utils/security/sanitization.ts` |
223
+ | | Configuration Fallback | Safely falls back to `mcp-config.json.example` if primary client config is missing. | `src/mcp-client/configLoader.ts` |
224
+ | **Scripts** | Clean Script | Removes `dist` and `logs` directories (or custom targets). | `scripts/clean.ts` |
225
+ | | Make Executable Script | Sets executable permissions (`chmod +x`) on specified files (Unix-like only). | `scripts/make-executable.ts` |
226
+ | | Tree Script | Generates a directory structure tree, respecting `.gitignore`. | `scripts/tree.ts` |
227
+ | | Fetch OpenAPI Spec Script | Fetches an OpenAPI spec (YAML/JSON) from a URL with fallbacks, saves locally. | `scripts/fetch-openapi-spec.ts` |
228
+
229
+ ---
230
+
231
+ <div align="center">
232
+ Built with ❤️ and the <a href="https://modelcontextprotocol.io/">Model Context Protocol</a>
233
+ </div>
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Main application configuration object.
3
+ * Aggregates settings from environment variables and package.json.
4
+ */
5
+ export declare const config: {
6
+ /**
7
+ * The name of the MCP server.
8
+ * Prioritizes MCP_SERVER_NAME env var, falls back to package.json name.
9
+ * Default: 'mcp-ts-template' (from package.json)
10
+ */
11
+ mcpServerName: string;
12
+ /**
13
+ * The version of the MCP server.
14
+ * Prioritizes MCP_SERVER_VERSION env var, falls back to package.json version.
15
+ * Default: (from package.json)
16
+ */
17
+ mcpServerVersion: string;
18
+ /**
19
+ * Logging level for the application (e.g., "debug", "info", "warning", "error").
20
+ * Controlled by MCP_LOG_LEVEL env var.
21
+ * Default: "info"
22
+ */
23
+ logLevel: string;
24
+ /**
25
+ * The runtime environment (e.g., "development", "production").
26
+ * Controlled by NODE_ENV env var.
27
+ * Default: "development"
28
+ */
29
+ environment: string;
30
+ /**
31
+ * Specifies the transport mechanism for the server.
32
+ * Controlled by MCP_TRANSPORT_TYPE env var. Options: 'stdio', 'http'.
33
+ * Default: "stdio"
34
+ */
35
+ mcpTransportType: "stdio" | "http";
36
+ /**
37
+ * The port number for the HTTP server to listen on (if MCP_TRANSPORT_TYPE is 'http').
38
+ * Controlled by MCP_HTTP_PORT env var.
39
+ * Default: 3010
40
+ */
41
+ mcpHttpPort: number;
42
+ /**
43
+ * The host address for the HTTP server to bind to (if MCP_TRANSPORT_TYPE is 'http').
44
+ * Controlled by MCP_HTTP_HOST env var.
45
+ * Default: "127.0.0.1"
46
+ */
47
+ mcpHttpHost: string;
48
+ /**
49
+ * Comma-separated list of allowed origins for CORS requests when using the 'http' transport.
50
+ * Controlled by MCP_ALLOWED_ORIGINS env var.
51
+ * Default: undefined (meaning CORS might be restrictive by default in the transport layer)
52
+ */
53
+ mcpAllowedOrigins: string[] | undefined;
54
+ /**
55
+ * A secret key used for signing and verifying authentication tokens (e.g., JWT).
56
+ * MUST be set in production for HTTP transport security.
57
+ * Controlled by MCP_AUTH_SECRET_KEY env var.
58
+ * Default: undefined (Auth middleware should throw error if not set in production)
59
+ */
60
+ mcpAuthSecretKey: string | undefined;
61
+ };
62
+ /**
63
+ * The configured logging level for the application.
64
+ * Exported separately for convenience (e.g., logger initialization).
65
+ * @type {string}
66
+ */
67
+ export declare const logLevel: string;
68
+ /**
69
+ * The configured runtime environment for the application.
70
+ * Exported separately for convenience.
71
+ * @type {string}
72
+ */
73
+ export declare const environment: string;
@@ -0,0 +1,125 @@
1
+ import dotenv from "dotenv";
2
+ import { readFileSync } from "fs";
3
+ import { dirname, join } from "path";
4
+ import { fileURLToPath } from "url";
5
+ import { z } from 'zod';
6
+ dotenv.config(); // Load environment variables from .env file
7
+ // Determine the directory name of the current module
8
+ const __dirname = dirname(fileURLToPath(import.meta.url));
9
+ // Construct the path to package.json relative to the current file
10
+ const pkgPath = join(__dirname, '../../package.json');
11
+ // Default package information in case package.json is unreadable
12
+ let pkg = { name: 'mcp-ts-template', version: '0.0.0' };
13
+ try {
14
+ // Read and parse package.json to get default server name and version
15
+ pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));
16
+ }
17
+ catch (error) {
18
+ // Silently use default pkg info if reading fails.
19
+ // Consider adding logging here if robust error handling is needed.
20
+ if (process.stdout.isTTY) {
21
+ console.error("Warning: Could not read package.json for default config values.", error);
22
+ }
23
+ }
24
+ // Define a schema for environment variables for validation and type safety
25
+ const EnvSchema = z.object({
26
+ MCP_SERVER_NAME: z.string().optional(),
27
+ MCP_SERVER_VERSION: z.string().optional(),
28
+ MCP_LOG_LEVEL: z.string().default("info"),
29
+ NODE_ENV: z.string().default("development"),
30
+ MCP_TRANSPORT_TYPE: z.enum(['stdio', 'http']).default('stdio'),
31
+ MCP_HTTP_PORT: z.coerce.number().int().positive().default(3010), // Updated default port
32
+ MCP_HTTP_HOST: z.string().default('127.0.0.1'),
33
+ MCP_ALLOWED_ORIGINS: z.string().optional(), // Comma-separated string
34
+ MCP_AUTH_SECRET_KEY: z.string().min(32, "MCP_AUTH_SECRET_KEY must be at least 32 characters long for security").optional(), // Secret for signing/verifying tokens
35
+ });
36
+ // Parse and validate environment variables
37
+ const parsedEnv = EnvSchema.safeParse(process.env);
38
+ if (!parsedEnv.success) {
39
+ if (process.stdout.isTTY) {
40
+ console.error("❌ Invalid environment variables:", parsedEnv.error.flatten().fieldErrors);
41
+ }
42
+ // Decide if the application should exit or continue with defaults
43
+ // For critical configs, you might want to throw an error:
44
+ // throw new Error("Invalid environment configuration.");
45
+ // For now, we'll log the error and proceed with defaults where possible.
46
+ }
47
+ const env = parsedEnv.success ? parsedEnv.data : EnvSchema.parse({}); // Use defaults on failure
48
+ /**
49
+ * Main application configuration object.
50
+ * Aggregates settings from environment variables and package.json.
51
+ */
52
+ export const config = {
53
+ /**
54
+ * The name of the MCP server.
55
+ * Prioritizes MCP_SERVER_NAME env var, falls back to package.json name.
56
+ * Default: 'mcp-ts-template' (from package.json)
57
+ */
58
+ mcpServerName: env.MCP_SERVER_NAME || pkg.name,
59
+ /**
60
+ * The version of the MCP server.
61
+ * Prioritizes MCP_SERVER_VERSION env var, falls back to package.json version.
62
+ * Default: (from package.json)
63
+ */
64
+ mcpServerVersion: env.MCP_SERVER_VERSION || pkg.version,
65
+ /**
66
+ * Logging level for the application (e.g., "debug", "info", "warning", "error").
67
+ * Controlled by MCP_LOG_LEVEL env var.
68
+ * Default: "info"
69
+ */
70
+ logLevel: env.MCP_LOG_LEVEL,
71
+ /**
72
+ * The runtime environment (e.g., "development", "production").
73
+ * Controlled by NODE_ENV env var.
74
+ * Default: "development"
75
+ */
76
+ environment: env.NODE_ENV,
77
+ /**
78
+ * Specifies the transport mechanism for the server.
79
+ * Controlled by MCP_TRANSPORT_TYPE env var. Options: 'stdio', 'http'.
80
+ * Default: "stdio"
81
+ */
82
+ mcpTransportType: env.MCP_TRANSPORT_TYPE,
83
+ /**
84
+ * The port number for the HTTP server to listen on (if MCP_TRANSPORT_TYPE is 'http').
85
+ * Controlled by MCP_HTTP_PORT env var.
86
+ * Default: 3010
87
+ */
88
+ mcpHttpPort: env.MCP_HTTP_PORT,
89
+ /**
90
+ * The host address for the HTTP server to bind to (if MCP_TRANSPORT_TYPE is 'http').
91
+ * Controlled by MCP_HTTP_HOST env var.
92
+ * Default: "127.0.0.1"
93
+ */
94
+ mcpHttpHost: env.MCP_HTTP_HOST,
95
+ /**
96
+ * Comma-separated list of allowed origins for CORS requests when using the 'http' transport.
97
+ * Controlled by MCP_ALLOWED_ORIGINS env var.
98
+ * Default: undefined (meaning CORS might be restrictive by default in the transport layer)
99
+ */
100
+ mcpAllowedOrigins: env.MCP_ALLOWED_ORIGINS?.split(',').map(origin => origin.trim()).filter(Boolean),
101
+ /**
102
+ * A secret key used for signing and verifying authentication tokens (e.g., JWT).
103
+ * MUST be set in production for HTTP transport security.
104
+ * Controlled by MCP_AUTH_SECRET_KEY env var.
105
+ * Default: undefined (Auth middleware should throw error if not set in production)
106
+ */
107
+ mcpAuthSecretKey: env.MCP_AUTH_SECRET_KEY,
108
+ // Note: mcpClient configuration is loaded separately via src/mcp-client/configLoader.ts
109
+ // Note: Logger-specific configurations (LOG_FILE_PATH, LOG_MAX_FILES, etc.)
110
+ // are typically handled directly within the logger utility (src/utils/internal/logger.ts)
111
+ };
112
+ /**
113
+ * The configured logging level for the application.
114
+ * Exported separately for convenience (e.g., logger initialization).
115
+ * @type {string}
116
+ */
117
+ export const logLevel = config.logLevel;
118
+ /**
119
+ * The configured runtime environment for the application.
120
+ * Exported separately for convenience.
121
+ * @type {string}
122
+ */
123
+ export const environment = config.environment;
124
+ // Logger initialization and validation logic should occur at the application entry point (e.g., src/index.ts)
125
+ // after configuration is loaded.
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};