mcp-ts-template 1.1.8 → 1.2.1

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 (63) hide show
  1. package/README.md +31 -25
  2. package/dist/config/index.d.ts +111 -32
  3. package/dist/config/index.js +294 -71
  4. package/dist/index.d.ts +22 -0
  5. package/dist/index.js +206 -99
  6. package/dist/mcp-client/client.js +1 -3
  7. package/dist/mcp-client/configLoader.d.ts +43 -17
  8. package/dist/mcp-client/configLoader.js +57 -68
  9. package/dist/mcp-client/transport.d.ts +35 -16
  10. package/dist/mcp-client/transport.js +42 -62
  11. package/dist/mcp-server/resources/echoResource/echoResourceLogic.d.ts +88 -22
  12. package/dist/mcp-server/resources/echoResource/echoResourceLogic.js +102 -31
  13. package/dist/mcp-server/resources/echoResource/index.d.ts +11 -3
  14. package/dist/mcp-server/resources/echoResource/index.js +11 -3
  15. package/dist/mcp-server/resources/echoResource/registration.d.ts +23 -3
  16. package/dist/mcp-server/resources/echoResource/registration.js +152 -86
  17. package/dist/mcp-server/server.d.ts +11 -4
  18. package/dist/mcp-server/server.js +77 -66
  19. package/dist/mcp-server/tools/echoTool/echoToolLogic.d.ts +52 -15
  20. package/dist/mcp-server/tools/echoTool/echoToolLogic.js +104 -40
  21. package/dist/mcp-server/tools/echoTool/index.d.ts +10 -3
  22. package/dist/mcp-server/tools/echoTool/index.js +10 -3
  23. package/dist/mcp-server/tools/echoTool/registration.d.ts +22 -3
  24. package/dist/mcp-server/tools/echoTool/registration.js +124 -59
  25. package/dist/mcp-server/transports/authentication/authMiddleware.d.ts +16 -11
  26. package/dist/mcp-server/transports/authentication/authMiddleware.js +63 -73
  27. package/dist/mcp-server/transports/httpTransport.d.ts +26 -14
  28. package/dist/mcp-server/transports/httpTransport.js +283 -229
  29. package/dist/mcp-server/transports/stdioTransport.d.ts +15 -12
  30. package/dist/mcp-server/transports/stdioTransport.js +25 -30
  31. package/dist/services/openRouterProvider.d.ts +102 -22
  32. package/dist/services/openRouterProvider.js +212 -147
  33. package/dist/types-global/errors.d.ts +84 -18
  34. package/dist/types-global/errors.js +85 -21
  35. package/dist/utils/index.d.ts +10 -4
  36. package/dist/utils/index.js +10 -4
  37. package/dist/utils/internal/errorHandler.d.ts +85 -46
  38. package/dist/utils/internal/errorHandler.js +177 -78
  39. package/dist/utils/internal/index.d.ts +9 -3
  40. package/dist/utils/internal/index.js +9 -3
  41. package/dist/utils/internal/logger.d.ts +179 -24
  42. package/dist/utils/internal/logger.js +342 -136
  43. package/dist/utils/internal/requestContext.d.ts +41 -23
  44. package/dist/utils/internal/requestContext.js +32 -21
  45. package/dist/utils/metrics/index.d.ts +7 -1
  46. package/dist/utils/metrics/index.js +7 -1
  47. package/dist/utils/metrics/tokenCounter.d.ts +35 -19
  48. package/dist/utils/metrics/tokenCounter.js +55 -58
  49. package/dist/utils/parsing/dateParser.d.ts +48 -14
  50. package/dist/utils/parsing/dateParser.js +51 -18
  51. package/dist/utils/parsing/index.d.ts +8 -2
  52. package/dist/utils/parsing/index.js +8 -2
  53. package/dist/utils/parsing/jsonParser.d.ts +83 -16
  54. package/dist/utils/parsing/jsonParser.js +130 -42
  55. package/dist/utils/security/idGenerator.d.ts +115 -40
  56. package/dist/utils/security/idGenerator.js +143 -70
  57. package/dist/utils/security/index.d.ts +9 -3
  58. package/dist/utils/security/index.js +9 -3
  59. package/dist/utils/security/rateLimiter.d.ts +78 -25
  60. package/dist/utils/security/rateLimiter.js +104 -71
  61. package/dist/utils/security/sanitization.d.ts +137 -102
  62. package/dist/utils/security/sanitization.js +318 -188
  63. package/package.json +5 -3
package/README.md CHANGED
@@ -1,9 +1,9 @@
1
1
  # MCP TypeScript Template 🚀
2
2
 
3
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)
4
+ [![Model Context Protocol SDK](https://img.shields.io/badge/MCP%20SDK-1.11.2-green.svg)](https://github.com/modelcontextprotocol/typescript-sdk)
5
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.8-blue.svg)](./CHANGELOG.md)
6
+ [![Version](https://img.shields.io/badge/Version-1.2.1-blue.svg)](./CHANGELOG.md)
7
7
  [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
8
8
  [![Status](https://img.shields.io/badge/Status-Stable-green.svg)](https://github.com/cyanheads/mcp-ts-template/issues)
9
9
  [![GitHub](https://img.shields.io/github/stars/cyanheads/mcp-ts-template?style=social)](https://github.com/cyanheads/mcp-ts-template)
@@ -23,7 +23,7 @@ Whether you're creating a new MCP server to extend an AI's capabilities or integ
23
23
  | **🚀 Production Utilities** | Logging, Error Handling, ID Generation, Rate Limiting, Request Context tracking, Input Sanitization. | `src/utils/` |
24
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
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 |
26
+ | **📚 Documentation** | Comprehensive `README.md`, structured JSDoc comments (via `tsdoc.json`), API references. | `README.md`, Codebase, `tsdoc.json`, `docs/api-references/` |
27
27
  | **🤖 Agent Ready** | Includes a [.clinerules](.clinerules) developer cheatsheet tailored for LLM coding agents. | `.clinerules` |
28
28
  | **🛠️ Utility Scripts** | Scripts for cleaning builds, setting executable permissions, generating directory trees, and fetching OpenAPI specs. | `scripts/` |
29
29
 
@@ -71,7 +71,13 @@ Get the example server running in minutes:
71
71
  # Or use 'npm run rebuild' for a clean install (deletes node_modules, logs, dist)
72
72
  ```
73
73
 
74
- 4. **Run the Example Server:**
74
+ 4. **Format the code (Optional but Recommended):**
75
+
76
+ ```bash
77
+ npm run format
78
+ ```
79
+
80
+ 5. **Run the Example Server:**
75
81
 
76
82
  - **Via Stdio (Default):** Many MCP host applications will run this automatically using `stdio`. To run manually for testing:
77
83
  ```bash
@@ -90,26 +96,26 @@ Get the example server running in minutes:
90
96
 
91
97
  Configure the MCP server's behavior using these environment variables:
92
98
 
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
- | `APP_URL` | URL of the application (used by OpenRouter service for HTTP Referer). | `http://localhost:3000` |
105
- | `APP_NAME` | Name of the application (used by OpenRouter service for X-Title header). | (from package.json or 'MCP TS App') |
106
- | `OPENROUTER_API_KEY` | API key for OpenRouter.ai service. Optional, but service will be unconfigured without it. | (none) |
107
- | `LLM_DEFAULT_MODEL` | Default model to use for LLM calls via OpenRouter. | `openrouter/auto` |
108
- | `LLM_DEFAULT_TEMPERATURE` | Default temperature for LLM calls (0-2). Optional. | (none) |
109
- | `LLM_DEFAULT_TOP_P` | Default top_p for LLM calls (0-1). Optional. | (none) |
110
- | `LLM_DEFAULT_MAX_TOKENS` | Default max_tokens for LLM calls. Optional. | (none) |
111
- | `LLM_DEFAULT_TOP_K` | Default top_k for LLM calls (non-negative integer). Optional. | (none) |
112
- | `LLM_DEFAULT_MIN_P` | Default min_p for LLM calls (0-1). Optional. | (none) |
99
+ | Variable | Description | Default |
100
+ | :------------------------ | :-------------------------------------------------------------------------------------------------- | :----------------------------------------- |
101
+ | `MCP_TRANSPORT_TYPE` | Server transport: `stdio` or `http`. | `stdio` |
102
+ | `MCP_HTTP_PORT` | Port for the HTTP server (if `MCP_TRANSPORT_TYPE=http`). | `3010` |
103
+ | `MCP_HTTP_HOST` | Host address for the HTTP server (if `MCP_TRANSPORT_TYPE=http`). | `127.0.0.1` |
104
+ | `MCP_ALLOWED_ORIGINS` | Comma-separated allowed origins for CORS (if `MCP_TRANSPORT_TYPE=http`). | (none) |
105
+ | `MCP_SERVER_NAME` | Optional server name (used in MCP initialization). | (from package.json) |
106
+ | `MCP_SERVER_VERSION` | Optional server version (used in MCP initialization). | (from package.json) |
107
+ | `MCP_LOG_LEVEL` | Server logging level (`debug`, `info`, `warning`, `error`, etc.). | `info` |
108
+ | `NODE_ENV` | Runtime environment (`development`, `production`). | `development` |
109
+ | `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**) |
110
+ | `OPENROUTER_APP_URL` | URL of the application (used by OpenRouter service for HTTP Referer). | `https://caseyjhand.com` |
111
+ | `OPENROUTER_APP_NAME` | Name of the application (used by OpenRouter service for X-Title header). | 'mcp-ts-template' |
112
+ | `OPENROUTER_API_KEY` | API key for OpenRouter.ai service. Optional, but service will be unconfigured without it. | (none) |
113
+ | `LLM_DEFAULT_MODEL` | Default model to use for LLM calls via OpenRouter. | `google/gemini-2.5-flash-preview:thinking` |
114
+ | `LLM_DEFAULT_TEMPERATURE` | Default temperature for LLM calls (0-2). Optional. | (none) |
115
+ | `LLM_DEFAULT_TOP_P` | Default top_p for LLM calls (0-1). Optional. | (none) |
116
+ | `LLM_DEFAULT_MAX_TOKENS` | Default max_tokens for LLM calls. Optional. | (none) |
117
+ | `LLM_DEFAULT_TOP_K` | Default top_k for LLM calls (non-negative integer). Optional. | (none) |
118
+ | `LLM_DEFAULT_MIN_P` | Default min_p for LLM calls (0-1). Optional. | (none) |
113
119
 
114
120
  **Note on HTTP Port Retries:** If the `MCP_HTTP_PORT` is busy, the server automatically tries the next port (up to 15 times).
115
121
 
@@ -211,7 +217,7 @@ This project is licensed under the Apache License 2.0. See the [LICENSE](LICENSE
211
217
  | | Configuration | Environment-aware settings with Zod validation. | `src/config/`, `src/mcp-client/configLoader.ts` |
212
218
  | | HTTP Transport | Express-based server with SSE, session management, CORS, port retries. | `src/mcp-server/transports/httpTransport.ts` |
213
219
  | | Stdio Transport | Handles MCP communication over standard input/output. | `src/mcp-server/transports/stdioTransport.ts` |
214
- | **Utilities (Core)** | Logger | Structured, context-aware logging (files & MCP notifications). | `src/utils/internal/logger.ts` |
220
+ | **Utilities (Core)** | Logger | Structured, context-aware logging (files with rotation & MCP notifications). | `src/utils/internal/logger.ts` |
215
221
  | | ErrorHandler | Centralized error processing, classification, and logging. | `src/utils/internal/errorHandler.ts` |
216
222
  | | RequestContext | Request/operation tracking and correlation. | `src/utils/internal/requestContext.ts` |
217
223
  | **Utilities (Metrics)** | TokenCounter | Estimates token counts using `tiktoken`. | `src/utils/metrics/tokenCounter.ts` |
@@ -1,82 +1,161 @@
1
+ /**
2
+ * @fileoverview Loads, validates, and exports application configuration.
3
+ * This module centralizes configuration management, sourcing values from
4
+ * environment variables and `package.json`. It uses Zod for schema validation
5
+ * to ensure type safety and correctness of configuration parameters.
6
+ *
7
+ * Key responsibilities:
8
+ * - Load environment variables from a `.env` file.
9
+ * - Read `package.json` for default server name and version.
10
+ * - Define a Zod schema for all expected environment variables.
11
+ * - Validate environment variables against the schema.
12
+ * - Construct and export a comprehensive `config` object.
13
+ * - Export individual configuration values like `logLevel` and `environment` for convenience.
14
+ *
15
+ * @module config/index
16
+ */
1
17
  /**
2
18
  * Main application configuration object.
3
- * Aggregates settings from environment variables and package.json.
19
+ * This object aggregates settings from validated environment variables (`env`)
20
+ * and `package.json` (`pkg`), providing a single source of truth for configuration
21
+ * throughout the application.
22
+ *
23
+ * @constant {object} config
4
24
  */
5
25
  export declare const config: {
6
26
  /**
7
27
  * 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)
28
+ * Prioritizes the `MCP_SERVER_NAME` environment variable.
29
+ * If `MCP_SERVER_NAME` is not set, it falls back to the `name` property from `package.json`.
30
+ * If `package.json` is also unavailable, it uses the hardcoded default 'mcp-ts-template'.
31
+ * @type {string}
10
32
  */
11
33
  mcpServerName: string;
12
34
  /**
13
35
  * The version of the MCP server.
14
- * Prioritizes MCP_SERVER_VERSION env var, falls back to package.json version.
15
- * Default: (from package.json)
36
+ * Prioritizes the `MCP_SERVER_VERSION` environment variable.
37
+ * If `MCP_SERVER_VERSION` is not set, it falls back to the `version` property from `package.json`.
38
+ * If `package.json` is also unavailable, it uses the hardcoded default '0.0.0'.
39
+ * @type {string}
16
40
  */
17
41
  mcpServerVersion: string;
18
42
  /**
19
43
  * Logging level for the application (e.g., "debug", "info", "warning", "error").
20
- * Controlled by MCP_LOG_LEVEL env var.
21
- * Default: "info"
44
+ * Sourced from the `MCP_LOG_LEVEL` environment variable.
45
+ * Defaults to "info" if `MCP_LOG_LEVEL` is not set (as defined in `EnvSchema`).
46
+ * @type {string}
22
47
  */
23
48
  logLevel: string;
24
49
  /**
25
- * The runtime environment (e.g., "development", "production").
26
- * Controlled by NODE_ENV env var.
27
- * Default: "development"
50
+ * The runtime environment of the application (e.g., "development", "production").
51
+ * Sourced from the `NODE_ENV` environment variable.
52
+ * Defaults to "development" if `NODE_ENV` is not set (as defined in `EnvSchema`).
53
+ * @type {string}
28
54
  */
29
55
  environment: string;
30
56
  /**
31
- * Specifies the transport mechanism for the server.
32
- * Controlled by MCP_TRANSPORT_TYPE env var. Options: 'stdio', 'http'.
33
- * Default: "stdio"
57
+ * Specifies the transport mechanism for MCP server communication ('stdio' or 'http').
58
+ * Sourced from the `MCP_TRANSPORT_TYPE` environment variable.
59
+ * Defaults to "stdio" if `MCP_TRANSPORT_TYPE` is not set (as defined in `EnvSchema`).
60
+ * @type {"stdio" | "http"}
34
61
  */
35
62
  mcpTransportType: "stdio" | "http";
36
63
  /**
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
64
+ * The port number for the HTTP server to listen on.
65
+ * Only applicable if `mcpTransportType` is 'http'.
66
+ * Sourced from the `MCP_HTTP_PORT` environment variable.
67
+ * Defaults to 3010 if `MCP_HTTP_PORT` is not set (as defined in `EnvSchema`).
68
+ * @type {number}
40
69
  */
41
70
  mcpHttpPort: number;
42
71
  /**
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"
72
+ * The host address for the HTTP server to bind to (e.g., "127.0.0.1", "0.0.0.0").
73
+ * Only applicable if `mcpTransportType` is 'http'.
74
+ * Sourced from the `MCP_HTTP_HOST` environment variable.
75
+ * Defaults to "127.0.0.1" if `MCP_HTTP_HOST` is not set (as defined in `EnvSchema`).
76
+ * @type {string}
46
77
  */
47
78
  mcpHttpHost: string;
48
79
  /**
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)
80
+ * An array of allowed origins for CORS requests when using the 'http' transport.
81
+ * Derived from the `MCP_ALLOWED_ORIGINS` environment variable (comma-separated string).
82
+ * Each origin string is trimmed. Empty strings resulting from multiple commas are filtered out.
83
+ * If `MCP_ALLOWED_ORIGINS` is not set, this will be `undefined`.
84
+ * The HTTP transport layer should handle the `undefined` case appropriately (e.g., by applying default CORS policies).
85
+ * @type {string[] | undefined}
52
86
  */
53
87
  mcpAllowedOrigins: string[] | undefined;
54
88
  /**
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)
89
+ * The secret key used for signing and verifying authentication tokens (e.g., JWTs).
90
+ * This is critical for securing the HTTP transport if authentication is enabled.
91
+ * Sourced from the `MCP_AUTH_SECRET_KEY` environment variable.
92
+ * It's crucial that this key is kept confidential and is sufficiently complex.
93
+ * The `EnvSchema` enforces a minimum length of 32 characters.
94
+ * If not set, this will be `undefined`. The authentication middleware should handle this,
95
+ * potentially throwing an error if it's required but missing, especially in production.
96
+ * @type {string | undefined}
59
97
  */
60
98
  mcpAuthSecretKey: string | undefined;
61
- appUrl: string;
62
- appName: string;
99
+ /**
100
+ * The application URL for OpenRouter integration.
101
+ * Defaults to "http://localhost:3000" if `OPENROUTER_APP_URL` is not set.
102
+ * @type {string}
103
+ */
104
+ openrouterAppUrl: string;
105
+ /**
106
+ * The application name for OpenRouter integration.
107
+ * Defaults to `mcpServerName` (which itself defaults to `pkg.name` or "MCP TS App") if `OPENROUTER_APP_NAME` is not set.
108
+ * @type {string}
109
+ */
110
+ openrouterAppName: string;
111
+ /**
112
+ * The API key for OpenRouter services.
113
+ * Sourced from `OPENROUTER_API_KEY` environment variable. No default is provided here;
114
+ * the service using this key should handle its absence (e.g., by disabling features or erroring).
115
+ * @type {string | undefined}
116
+ */
63
117
  openrouterApiKey: string | undefined;
118
+ /**
119
+ * Default model for LLM operations.
120
+ * @type {string}
121
+ */
64
122
  llmDefaultModel: string;
123
+ /**
124
+ * Default temperature for LLM sampling.
125
+ * @type {number | undefined}
126
+ */
65
127
  llmDefaultTemperature: number | undefined;
128
+ /**
129
+ * Default top_p for LLM sampling.
130
+ * @type {number | undefined}
131
+ */
66
132
  llmDefaultTopP: number | undefined;
133
+ /**
134
+ * Default maximum tokens for LLM responses.
135
+ * @type {number | undefined}
136
+ */
67
137
  llmDefaultMaxTokens: number | undefined;
138
+ /**
139
+ * Default top_k for LLM sampling.
140
+ * @type {number | undefined}
141
+ */
68
142
  llmDefaultTopK: number | undefined;
143
+ /**
144
+ * Default min_p for LLM sampling.
145
+ * @type {number | undefined}
146
+ */
69
147
  llmDefaultMinP: number | undefined;
70
148
  };
71
149
  /**
72
- * The configured logging level for the application.
73
- * Exported separately for convenience (e.g., logger initialization).
150
+ * The configured logging level for the application (e.g., "debug", "info").
151
+ * This is exported separately from the main `config` object for convenience,
152
+ * allowing direct import where only the log level is needed (e.g., during logger initialization).
74
153
  * @type {string}
75
154
  */
76
155
  export declare const logLevel: string;
77
156
  /**
78
- * The configured runtime environment for the application.
79
- * Exported separately for convenience.
157
+ * The configured runtime environment for the application (e.g., "development", "production").
158
+ * Exported separately for convenience, useful for conditional logic based on the environment.
80
159
  * @type {string}
81
160
  */
82
161
  export declare const environment: string;