@modelcontextprotocol/express 2.0.0-alpha.2

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.
package/LICENSE ADDED
@@ -0,0 +1,216 @@
1
+ The MCP project is undergoing a licensing transition from the MIT License to the Apache License, Version 2.0 ("Apache-2.0"). All new code and specification contributions to the project are licensed under Apache-2.0. Documentation contributions (excluding specifications) are licensed under CC-BY-4.0.
2
+
3
+ Contributions for which relicensing consent has been obtained are licensed under Apache-2.0. Contributions made by authors who originally licensed their work under the MIT License and who have not yet granted explicit permission to relicense remain licensed under the MIT License.
4
+
5
+ No rights beyond those granted by the applicable original license are conveyed for such contributions.
6
+
7
+ ---
8
+
9
+ Apache License
10
+ Version 2.0, January 2004
11
+ http://www.apache.org/licenses/
12
+
13
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
14
+
15
+ 1. Definitions.
16
+
17
+ "License" shall mean the terms and conditions for use, reproduction,
18
+ and distribution as defined by Sections 1 through 9 of this document.
19
+
20
+ "Licensor" shall mean the copyright owner or entity authorized by
21
+ the copyright owner that is granting the License.
22
+
23
+ "Legal Entity" shall mean the union of the acting entity and all
24
+ other entities that control, are controlled by, or are under common
25
+ control with that entity. For the purposes of this definition,
26
+ "control" means (i) the power, direct or indirect, to cause the
27
+ direction or management of such entity, whether by contract or
28
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
29
+ outstanding shares, or (iii) beneficial ownership of such entity.
30
+
31
+ "You" (or "Your") shall mean an individual or Legal Entity
32
+ exercising permissions granted by this License.
33
+
34
+ "Source" form shall mean the preferred form for making modifications,
35
+ including but not limited to software source code, documentation
36
+ source, and configuration files.
37
+
38
+ "Object" form shall mean any form resulting from mechanical
39
+ transformation or translation of a Source form, including but
40
+ not limited to compiled object code, generated documentation,
41
+ and conversions to other media types.
42
+
43
+ "Work" shall mean the work of authorship, whether in Source or
44
+ Object form, made available under the License, as indicated by a
45
+ copyright notice that is included in or attached to the work
46
+ (an example is provided in the Appendix below).
47
+
48
+ "Derivative Works" shall mean any work, whether in Source or Object
49
+ form, that is based on (or derived from) the Work and for which the
50
+ editorial revisions, annotations, elaborations, or other modifications
51
+ represent, as a whole, an original work of authorship. For the purposes
52
+ of this License, Derivative Works shall not include works that remain
53
+ separable from, or merely link (or bind by name) to the interfaces of,
54
+ the Work and Derivative Works thereof.
55
+
56
+ "Contribution" shall mean any work of authorship, including
57
+ the original version of the Work and any modifications or additions
58
+ to that Work or Derivative Works thereof, that is intentionally
59
+ submitted to the Licensor for inclusion in the Work by the copyright
60
+ owner or by an individual or Legal Entity authorized to submit on behalf
61
+ of the copyright owner. For the purposes of this definition, "submitted"
62
+ means any form of electronic, verbal, or written communication sent
63
+ to the Licensor or its representatives, including but not limited to
64
+ communication on electronic mailing lists, source code control systems,
65
+ and issue tracking systems that are managed by, or on behalf of, the
66
+ Licensor for the purpose of discussing and improving the Work, but
67
+ excluding communication that is conspicuously marked or otherwise
68
+ designated in writing by the copyright owner as "Not a Contribution."
69
+
70
+ "Contributor" shall mean Licensor and any individual or Legal Entity
71
+ on behalf of whom a Contribution has been received by Licensor and
72
+ subsequently incorporated within the Work.
73
+
74
+ 2. Grant of Copyright License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ copyright license to reproduce, prepare Derivative Works of,
78
+ publicly display, publicly perform, sublicense, and distribute the
79
+ Work and such Derivative Works in Source or Object form.
80
+
81
+ 3. Grant of Patent License. Subject to the terms and conditions of
82
+ this License, each Contributor hereby grants to You a perpetual,
83
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
84
+ (except as stated in this section) patent license to make, have made,
85
+ use, offer to sell, sell, import, and otherwise transfer the Work,
86
+ where such license applies only to those patent claims licensable
87
+ by such Contributor that are necessarily infringed by their
88
+ Contribution(s) alone or by combination of their Contribution(s)
89
+ with the Work to which such Contribution(s) was submitted. If You
90
+ institute patent litigation against any entity (including a
91
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
92
+ or a Contribution incorporated within the Work constitutes direct
93
+ or contributory patent infringement, then any patent licenses
94
+ granted to You under this License for that Work shall terminate
95
+ as of the date such litigation is filed.
96
+
97
+ 4. Redistribution. You may reproduce and distribute copies of the
98
+ Work or Derivative Works thereof in any medium, with or without
99
+ modifications, and in Source or Object form, provided that You
100
+ meet the following conditions:
101
+
102
+ (a) You must give any other recipients of the Work or
103
+ Derivative Works a copy of this License; and
104
+
105
+ (b) You must cause any modified files to carry prominent notices
106
+ stating that You changed the files; and
107
+
108
+ (c) You must retain, in the Source form of any Derivative Works
109
+ that You distribute, all copyright, patent, trademark, and
110
+ attribution notices from the Source form of the Work,
111
+ excluding those notices that do not pertain to any part of
112
+ the Derivative Works; and
113
+
114
+ (d) If the Work includes a "NOTICE" text file as part of its
115
+ distribution, then any Derivative Works that You distribute must
116
+ include a readable copy of the attribution notices contained
117
+ within such NOTICE file, excluding those notices that do not
118
+ pertain to any part of the Derivative Works, in at least one
119
+ of the following places: within a NOTICE text file distributed
120
+ as part of the Derivative Works; within the Source form or
121
+ documentation, if provided along with the Derivative Works; or,
122
+ within a display generated by the Derivative Works, if and
123
+ wherever such third-party notices normally appear. The contents
124
+ of the NOTICE file are for informational purposes only and
125
+ do not modify the License. You may add Your own attribution
126
+ notices within Derivative Works that You distribute, alongside
127
+ or as an addendum to the NOTICE text from the Work, provided
128
+ that such additional attribution notices cannot be construed
129
+ as modifying the License.
130
+
131
+ You may add Your own copyright statement to Your modifications and
132
+ may provide additional or different license terms and conditions
133
+ for use, reproduction, or distribution of Your modifications, or
134
+ for any such Derivative Works as a whole, provided Your use,
135
+ reproduction, and distribution of the Work otherwise complies with
136
+ the conditions stated in this License.
137
+
138
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
139
+ any Contribution intentionally submitted for inclusion in the Work
140
+ by You to the Licensor shall be under the terms and conditions of
141
+ this License, without any additional terms or conditions.
142
+ Notwithstanding the above, nothing herein shall supersede or modify
143
+ the terms of any separate license agreement you may have executed
144
+ with Licensor regarding such Contributions.
145
+
146
+ 6. Trademarks. This License does not grant permission to use the trade
147
+ names, trademarks, service marks, or product names of the Licensor,
148
+ except as required for reasonable and customary use in describing the
149
+ origin of the Work and reproducing the content of the NOTICE file.
150
+
151
+ 7. Disclaimer of Warranty. Unless required by applicable law or
152
+ agreed to in writing, Licensor provides the Work (and each
153
+ Contributor provides its Contributions) on an "AS IS" BASIS,
154
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
155
+ implied, including, without limitation, any warranties or conditions
156
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
157
+ PARTICULAR PURPOSE. You are solely responsible for determining the
158
+ appropriateness of using or redistributing the Work and assume any
159
+ risks associated with Your exercise of permissions under this License.
160
+
161
+ 8. Limitation of Liability. In no event and under no legal theory,
162
+ whether in tort (including negligence), contract, or otherwise,
163
+ unless required by applicable law (such as deliberate and grossly
164
+ negligent acts) or agreed to in writing, shall any Contributor be
165
+ liable to You for damages, including any direct, indirect, special,
166
+ incidental, or consequential damages of any character arising as a
167
+ result of this License or out of the use or inability to use the
168
+ Work (including but not limited to damages for loss of goodwill,
169
+ work stoppage, computer failure or malfunction, or any and all
170
+ other commercial damages or losses), even if such Contributor
171
+ has been advised of the possibility of such damages.
172
+
173
+ 9. Accepting Warranty or Additional Liability. While redistributing
174
+ the Work or Derivative Works thereof, You may choose to offer,
175
+ and charge a fee for, acceptance of support, warranty, indemnity,
176
+ or other liability obligations and/or rights consistent with this
177
+ License. However, in accepting such obligations, You may act only
178
+ on Your own behalf and on Your sole responsibility, not on behalf
179
+ of any other Contributor, and only if You agree to indemnify,
180
+ defend, and hold each Contributor harmless for any liability
181
+ incurred by, or claims asserted against, such Contributor by reason
182
+ of your accepting any such warranty or additional liability.
183
+
184
+ END OF TERMS AND CONDITIONS
185
+
186
+ ---
187
+
188
+ MIT License
189
+
190
+ Copyright (c) 2024-2025 Model Context Protocol a Series of LF Projects, LLC.
191
+
192
+ Permission is hereby granted, free of charge, to any person obtaining a copy
193
+ of this software and associated documentation files (the "Software"), to deal
194
+ in the Software without restriction, including without limitation the rights
195
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
196
+ copies of the Software, and to permit persons to whom the Software is
197
+ furnished to do so, subject to the following conditions:
198
+
199
+ The above copyright notice and this permission notice shall be included in all
200
+ copies or substantial portions of the Software.
201
+
202
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
203
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
204
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
205
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
206
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
207
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
208
+ SOFTWARE.
209
+
210
+ ---
211
+
212
+ Creative Commons Attribution 4.0 International (CC-BY-4.0)
213
+
214
+ Documentation in this project (excluding specifications) is licensed under
215
+ CC-BY-4.0. See https://creativecommons.org/licenses/by/4.0/legalcode for
216
+ the full license text.
package/README.md ADDED
@@ -0,0 +1,62 @@
1
+ # `@modelcontextprotocol/express`
2
+
3
+ Express adapters for the MCP TypeScript server SDK.
4
+
5
+ This package is a thin Express integration layer for [`@modelcontextprotocol/server`](https://github.com/modelcontextprotocol/typescript-sdk/tree/main/packages/server).
6
+
7
+ It does **not** implement MCP itself. Instead, it helps you:
8
+
9
+ - create an Express app with sensible defaults for MCP servers
10
+ - add DNS rebinding protection via Host header validation (recommended for localhost servers)
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ npm install @modelcontextprotocol/server @modelcontextprotocol/express express
16
+
17
+ # For MCP Streamable HTTP over Node.js (IncomingMessage/ServerResponse):
18
+ npm install @modelcontextprotocol/node
19
+ ```
20
+
21
+ ## Exports
22
+
23
+ - `createMcpExpressApp(options?)`
24
+ - `hostHeaderValidation(allowedHostnames)`
25
+ - `localhostHostValidation()`
26
+
27
+ ## Usage
28
+
29
+ ### Create an Express app (localhost DNS rebinding protection by default)
30
+
31
+ ```ts
32
+ import { createMcpExpressApp } from '@modelcontextprotocol/express';
33
+
34
+ const app = createMcpExpressApp(); // default host is 127.0.0.1; protection enabled
35
+ ```
36
+
37
+ ### Streamable HTTP endpoint (Express)
38
+
39
+ ```ts
40
+ import { createMcpExpressApp } from '@modelcontextprotocol/express';
41
+ import { NodeStreamableHTTPServerTransport } from '@modelcontextprotocol/node';
42
+ import { McpServer } from '@modelcontextprotocol/server';
43
+
44
+ const app = createMcpExpressApp();
45
+ const server = new McpServer({ name: 'my-server', version: '1.0.0' });
46
+
47
+ app.post('/mcp', async (req, res) => {
48
+ // Stateless example: create a transport per request.
49
+ // For stateful mode (sessions), keep a transport instance around and reuse it.
50
+ const transport = new NodeStreamableHTTPServerTransport({ sessionIdGenerator: undefined });
51
+ await server.connect(transport);
52
+ await transport.handleRequest(req, res, req.body);
53
+ });
54
+ ```
55
+
56
+ ### Host header validation (DNS rebinding protection)
57
+
58
+ ```ts
59
+ import { hostHeaderValidation } from '@modelcontextprotocol/express';
60
+
61
+ app.use(hostHeaderValidation(['localhost', '127.0.0.1', '[::1]']));
62
+ ```
@@ -0,0 +1,93 @@
1
+ import { Express, RequestHandler } from "express";
2
+
3
+ //#region src/express.d.ts
4
+
5
+ /**
6
+ * Options for creating an MCP Express application.
7
+ */
8
+ interface CreateMcpExpressAppOptions {
9
+ /**
10
+ * The hostname to bind to. Defaults to `'127.0.0.1'`.
11
+ * When set to `'127.0.0.1'`, `'localhost'`, or `'::1'`, DNS rebinding protection is automatically enabled.
12
+ */
13
+ host?: string;
14
+ /**
15
+ * List of allowed hostnames for DNS rebinding protection.
16
+ * If provided, host header validation will be applied using this list.
17
+ * For IPv6, provide addresses with brackets (e.g., `'[::1]'`).
18
+ *
19
+ * This is useful when binding to `'0.0.0.0'` or `'::'` but still wanting
20
+ * to restrict which hostnames are allowed.
21
+ */
22
+ allowedHosts?: string[];
23
+ /**
24
+ * Controls the maximum request body size for the JSON body parser.
25
+ * Passed directly to Express's `express.json({ limit })` option.
26
+ * Defaults to Express's built-in default of `'100kb'`.
27
+ *
28
+ * @example '1mb', '500kb', '10mb'
29
+ */
30
+ jsonLimit?: string;
31
+ }
32
+ /**
33
+ * Creates an Express application pre-configured for MCP servers.
34
+ *
35
+ * When the host is `'127.0.0.1'`, `'localhost'`, or `'::1'` (the default is `'127.0.0.1'`),
36
+ * DNS rebinding protection middleware is automatically applied to protect against
37
+ * DNS rebinding attacks on localhost servers.
38
+ *
39
+ * @param options - Configuration options
40
+ * @returns A configured Express application
41
+ *
42
+ * @example Basic usage - defaults to 127.0.0.1 with DNS rebinding protection
43
+ * ```ts source="./express.examples.ts#createMcpExpressApp_default"
44
+ * const app = createMcpExpressApp();
45
+ * ```
46
+ *
47
+ * @example Custom host - DNS rebinding protection only applied for localhost hosts
48
+ * ```ts source="./express.examples.ts#createMcpExpressApp_customHost"
49
+ * const appOpen = createMcpExpressApp({ host: '0.0.0.0' }); // No automatic DNS rebinding protection
50
+ * const appLocal = createMcpExpressApp({ host: 'localhost' }); // DNS rebinding protection enabled
51
+ * ```
52
+ *
53
+ * @example Custom allowed hosts for non-localhost binding
54
+ * ```ts source="./express.examples.ts#createMcpExpressApp_allowedHosts"
55
+ * const app = createMcpExpressApp({ host: '0.0.0.0', allowedHosts: ['myapp.local', 'localhost'] });
56
+ * ```
57
+ */
58
+ declare function createMcpExpressApp(options?: CreateMcpExpressAppOptions): Express;
59
+ //#endregion
60
+ //#region src/middleware/hostHeaderValidation.d.ts
61
+ /**
62
+ * Express middleware for DNS rebinding protection.
63
+ * Validates `Host` header hostname (port-agnostic) against an allowed list.
64
+ *
65
+ * This is particularly important for servers without authorization or HTTPS,
66
+ * such as localhost servers or development servers. DNS rebinding attacks can
67
+ * bypass same-origin policy by manipulating DNS to point a domain to a
68
+ * localhost address, allowing malicious websites to access your local server.
69
+ *
70
+ * @param allowedHostnames - List of allowed hostnames (without ports).
71
+ * For IPv6, provide the address with brackets (e.g., `[::1]`).
72
+ * @returns Express middleware function
73
+ *
74
+ * @example
75
+ * ```ts source="./hostHeaderValidation.examples.ts#hostHeaderValidation_basicUsage"
76
+ * const middleware = hostHeaderValidation(['localhost', '127.0.0.1', '[::1]']);
77
+ * app.use(middleware);
78
+ * ```
79
+ */
80
+ declare function hostHeaderValidation(allowedHostnames: string[]): RequestHandler;
81
+ /**
82
+ * Convenience middleware for localhost DNS rebinding protection.
83
+ * Allows only `localhost`, `127.0.0.1`, and `[::1]` (IPv6 localhost) hostnames.
84
+ *
85
+ * @example
86
+ * ```ts source="./hostHeaderValidation.examples.ts#localhostHostValidation_basicUsage"
87
+ * app.use(localhostHostValidation());
88
+ * ```
89
+ */
90
+ declare function localhostHostValidation(): RequestHandler;
91
+ //#endregion
92
+ export { CreateMcpExpressAppOptions, createMcpExpressApp, hostHeaderValidation, localhostHostValidation };
93
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/express.ts","../src/middleware/hostHeaderValidation.ts"],"sourcesContent":[],"mappings":";;;;;;AAQA;AAqDgB,UArDC,0BAAA,CAqD4B;;;;ACvC7C;EA2BgB,IAAA,CAAA,EAAA,MAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBDYA,mBAAA,WAA6B,6BAAkC;;;;;AArD/E;AAqDA;;;;ACvCA;AA2BA;;;;;;;;;;;iBA3BgB,oBAAA,8BAAkD;;;;;;;;;;iBA2BlD,uBAAA,CAAA,GAA2B"}
package/dist/index.mjs ADDED
@@ -0,0 +1,98 @@
1
+ import express from "express";
2
+ import { localhostAllowedHostnames, validateHostHeader } from "@modelcontextprotocol/server";
3
+
4
+ //#region src/middleware/hostHeaderValidation.ts
5
+ /**
6
+ * Express middleware for DNS rebinding protection.
7
+ * Validates `Host` header hostname (port-agnostic) against an allowed list.
8
+ *
9
+ * This is particularly important for servers without authorization or HTTPS,
10
+ * such as localhost servers or development servers. DNS rebinding attacks can
11
+ * bypass same-origin policy by manipulating DNS to point a domain to a
12
+ * localhost address, allowing malicious websites to access your local server.
13
+ *
14
+ * @param allowedHostnames - List of allowed hostnames (without ports).
15
+ * For IPv6, provide the address with brackets (e.g., `[::1]`).
16
+ * @returns Express middleware function
17
+ *
18
+ * @example
19
+ * ```ts source="./hostHeaderValidation.examples.ts#hostHeaderValidation_basicUsage"
20
+ * const middleware = hostHeaderValidation(['localhost', '127.0.0.1', '[::1]']);
21
+ * app.use(middleware);
22
+ * ```
23
+ */
24
+ function hostHeaderValidation(allowedHostnames) {
25
+ return (req, res, next) => {
26
+ const result = validateHostHeader(req.headers.host, allowedHostnames);
27
+ if (!result.ok) {
28
+ res.status(403).json({
29
+ jsonrpc: "2.0",
30
+ error: {
31
+ code: -32e3,
32
+ message: result.message
33
+ },
34
+ id: null
35
+ });
36
+ return;
37
+ }
38
+ next();
39
+ };
40
+ }
41
+ /**
42
+ * Convenience middleware for localhost DNS rebinding protection.
43
+ * Allows only `localhost`, `127.0.0.1`, and `[::1]` (IPv6 localhost) hostnames.
44
+ *
45
+ * @example
46
+ * ```ts source="./hostHeaderValidation.examples.ts#localhostHostValidation_basicUsage"
47
+ * app.use(localhostHostValidation());
48
+ * ```
49
+ */
50
+ function localhostHostValidation() {
51
+ return hostHeaderValidation(localhostAllowedHostnames());
52
+ }
53
+
54
+ //#endregion
55
+ //#region src/express.ts
56
+ /**
57
+ * Creates an Express application pre-configured for MCP servers.
58
+ *
59
+ * When the host is `'127.0.0.1'`, `'localhost'`, or `'::1'` (the default is `'127.0.0.1'`),
60
+ * DNS rebinding protection middleware is automatically applied to protect against
61
+ * DNS rebinding attacks on localhost servers.
62
+ *
63
+ * @param options - Configuration options
64
+ * @returns A configured Express application
65
+ *
66
+ * @example Basic usage - defaults to 127.0.0.1 with DNS rebinding protection
67
+ * ```ts source="./express.examples.ts#createMcpExpressApp_default"
68
+ * const app = createMcpExpressApp();
69
+ * ```
70
+ *
71
+ * @example Custom host - DNS rebinding protection only applied for localhost hosts
72
+ * ```ts source="./express.examples.ts#createMcpExpressApp_customHost"
73
+ * const appOpen = createMcpExpressApp({ host: '0.0.0.0' }); // No automatic DNS rebinding protection
74
+ * const appLocal = createMcpExpressApp({ host: 'localhost' }); // DNS rebinding protection enabled
75
+ * ```
76
+ *
77
+ * @example Custom allowed hosts for non-localhost binding
78
+ * ```ts source="./express.examples.ts#createMcpExpressApp_allowedHosts"
79
+ * const app = createMcpExpressApp({ host: '0.0.0.0', allowedHosts: ['myapp.local', 'localhost'] });
80
+ * ```
81
+ */
82
+ function createMcpExpressApp(options = {}) {
83
+ const { host = "127.0.0.1", allowedHosts, jsonLimit } = options;
84
+ const app = express();
85
+ app.use(express.json(jsonLimit ? { limit: jsonLimit } : void 0));
86
+ if (allowedHosts) app.use(hostHeaderValidation(allowedHosts));
87
+ else if ([
88
+ "127.0.0.1",
89
+ "localhost",
90
+ "::1"
91
+ ].includes(host)) app.use(localhostHostValidation());
92
+ else if (host === "0.0.0.0" || host === "::") console.warn(`Warning: Server is binding to ${host} without DNS rebinding protection. Consider using the allowedHosts option to restrict allowed hosts, or use authentication to protect your server.`);
93
+ return app;
94
+ }
95
+
96
+ //#endregion
97
+ export { createMcpExpressApp, hostHeaderValidation, localhostHostValidation };
98
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/middleware/hostHeaderValidation.ts","../src/express.ts"],"sourcesContent":["import { localhostAllowedHostnames, validateHostHeader } from '@modelcontextprotocol/server';\nimport type { NextFunction, Request, RequestHandler, Response } from 'express';\n\n/**\n * Express middleware for DNS rebinding protection.\n * Validates `Host` header hostname (port-agnostic) against an allowed list.\n *\n * This is particularly important for servers without authorization or HTTPS,\n * such as localhost servers or development servers. DNS rebinding attacks can\n * bypass same-origin policy by manipulating DNS to point a domain to a\n * localhost address, allowing malicious websites to access your local server.\n *\n * @param allowedHostnames - List of allowed hostnames (without ports).\n * For IPv6, provide the address with brackets (e.g., `[::1]`).\n * @returns Express middleware function\n *\n * @example\n * ```ts source=\"./hostHeaderValidation.examples.ts#hostHeaderValidation_basicUsage\"\n * const middleware = hostHeaderValidation(['localhost', '127.0.0.1', '[::1]']);\n * app.use(middleware);\n * ```\n */\nexport function hostHeaderValidation(allowedHostnames: string[]): RequestHandler {\n return (req: Request, res: Response, next: NextFunction) => {\n const result = validateHostHeader(req.headers.host, allowedHostnames);\n if (!result.ok) {\n res.status(403).json({\n jsonrpc: '2.0',\n error: {\n code: -32_000,\n message: result.message\n },\n id: null\n });\n return;\n }\n next();\n };\n}\n\n/**\n * Convenience middleware for localhost DNS rebinding protection.\n * Allows only `localhost`, `127.0.0.1`, and `[::1]` (IPv6 localhost) hostnames.\n *\n * @example\n * ```ts source=\"./hostHeaderValidation.examples.ts#localhostHostValidation_basicUsage\"\n * app.use(localhostHostValidation());\n * ```\n */\nexport function localhostHostValidation(): RequestHandler {\n return hostHeaderValidation(localhostAllowedHostnames());\n}\n","import type { Express } from 'express';\nimport express from 'express';\n\nimport { hostHeaderValidation, localhostHostValidation } from './middleware/hostHeaderValidation.js';\n\n/**\n * Options for creating an MCP Express application.\n */\nexport interface CreateMcpExpressAppOptions {\n /**\n * The hostname to bind to. Defaults to `'127.0.0.1'`.\n * When set to `'127.0.0.1'`, `'localhost'`, or `'::1'`, DNS rebinding protection is automatically enabled.\n */\n host?: string;\n\n /**\n * List of allowed hostnames for DNS rebinding protection.\n * If provided, host header validation will be applied using this list.\n * For IPv6, provide addresses with brackets (e.g., `'[::1]'`).\n *\n * This is useful when binding to `'0.0.0.0'` or `'::'` but still wanting\n * to restrict which hostnames are allowed.\n */\n allowedHosts?: string[];\n\n /**\n * Controls the maximum request body size for the JSON body parser.\n * Passed directly to Express's `express.json({ limit })` option.\n * Defaults to Express's built-in default of `'100kb'`.\n *\n * @example '1mb', '500kb', '10mb'\n */\n jsonLimit?: string;\n}\n\n/**\n * Creates an Express application pre-configured for MCP servers.\n *\n * When the host is `'127.0.0.1'`, `'localhost'`, or `'::1'` (the default is `'127.0.0.1'`),\n * DNS rebinding protection middleware is automatically applied to protect against\n * DNS rebinding attacks on localhost servers.\n *\n * @param options - Configuration options\n * @returns A configured Express application\n *\n * @example Basic usage - defaults to 127.0.0.1 with DNS rebinding protection\n * ```ts source=\"./express.examples.ts#createMcpExpressApp_default\"\n * const app = createMcpExpressApp();\n * ```\n *\n * @example Custom host - DNS rebinding protection only applied for localhost hosts\n * ```ts source=\"./express.examples.ts#createMcpExpressApp_customHost\"\n * const appOpen = createMcpExpressApp({ host: '0.0.0.0' }); // No automatic DNS rebinding protection\n * const appLocal = createMcpExpressApp({ host: 'localhost' }); // DNS rebinding protection enabled\n * ```\n *\n * @example Custom allowed hosts for non-localhost binding\n * ```ts source=\"./express.examples.ts#createMcpExpressApp_allowedHosts\"\n * const app = createMcpExpressApp({ host: '0.0.0.0', allowedHosts: ['myapp.local', 'localhost'] });\n * ```\n */\nexport function createMcpExpressApp(options: CreateMcpExpressAppOptions = {}): Express {\n const { host = '127.0.0.1', allowedHosts, jsonLimit } = options;\n\n const app = express();\n app.use(express.json(jsonLimit ? { limit: jsonLimit } : undefined));\n\n // If allowedHosts is explicitly provided, use that for validation\n if (allowedHosts) {\n app.use(hostHeaderValidation(allowedHosts));\n } else {\n // Apply DNS rebinding protection automatically for localhost hosts\n const localhostHosts = ['127.0.0.1', 'localhost', '::1'];\n if (localhostHosts.includes(host)) {\n app.use(localhostHostValidation());\n } else if (host === '0.0.0.0' || host === '::') {\n // Warn when binding to all interfaces without DNS rebinding protection\n // eslint-disable-next-line no-console\n console.warn(\n `Warning: Server is binding to ${host} without DNS rebinding protection. ` +\n 'Consider using the allowedHosts option to restrict allowed hosts, ' +\n 'or use authentication to protect your server.'\n );\n }\n }\n\n return app;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,qBAAqB,kBAA4C;AAC7E,SAAQ,KAAc,KAAe,SAAuB;EACxD,MAAM,SAAS,mBAAmB,IAAI,QAAQ,MAAM,iBAAiB;AACrE,MAAI,CAAC,OAAO,IAAI;AACZ,OAAI,OAAO,IAAI,CAAC,KAAK;IACjB,SAAS;IACT,OAAO;KACH,MAAM;KACN,SAAS,OAAO;KACnB;IACD,IAAI;IACP,CAAC;AACF;;AAEJ,QAAM;;;;;;;;;;;;AAad,SAAgB,0BAA0C;AACtD,QAAO,qBAAqB,2BAA2B,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACW5D,SAAgB,oBAAoB,UAAsC,EAAE,EAAW;CACnF,MAAM,EAAE,OAAO,aAAa,cAAc,cAAc;CAExD,MAAM,MAAM,SAAS;AACrB,KAAI,IAAI,QAAQ,KAAK,YAAY,EAAE,OAAO,WAAW,GAAG,OAAU,CAAC;AAGnE,KAAI,aACA,KAAI,IAAI,qBAAqB,aAAa,CAAC;UAGpB;EAAC;EAAa;EAAa;EAAM,CACrC,SAAS,KAAK,CAC7B,KAAI,IAAI,yBAAyB,CAAC;UAC3B,SAAS,aAAa,SAAS,KAGtC,SAAQ,KACJ,iCAAiC,KAAK,oJAGzC;AAIT,QAAO"}
package/package.json ADDED
@@ -0,0 +1,66 @@
1
+ {
2
+ "name": "@modelcontextprotocol/express",
3
+ "private": false,
4
+ "version": "2.0.0-alpha.2",
5
+ "description": "Express adapters for the Model Context Protocol TypeScript server SDK - Express middleware",
6
+ "license": "MIT",
7
+ "author": "Anthropic, PBC (https://anthropic.com)",
8
+ "homepage": "https://modelcontextprotocol.io",
9
+ "bugs": "https://github.com/modelcontextprotocol/typescript-sdk/issues",
10
+ "type": "module",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/modelcontextprotocol/typescript-sdk.git"
14
+ },
15
+ "engines": {
16
+ "node": ">=20"
17
+ },
18
+ "keywords": [
19
+ "modelcontextprotocol",
20
+ "mcp",
21
+ "express",
22
+ "middleware"
23
+ ],
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.mts",
27
+ "import": "./dist/index.mjs"
28
+ }
29
+ },
30
+ "files": [
31
+ "dist"
32
+ ],
33
+ "dependencies": {},
34
+ "peerDependencies": {
35
+ "express": "^5.2.1",
36
+ "@modelcontextprotocol/server": "^2.0.0-alpha.2"
37
+ },
38
+ "devDependencies": {
39
+ "@eslint/js": "^9.39.2",
40
+ "@types/express": "^5.0.6",
41
+ "@types/express-serve-static-core": "^5.1.0",
42
+ "@typescript/native-preview": "^7.0.0-dev.20251217.1",
43
+ "eslint": "^9.39.2",
44
+ "eslint-config-prettier": "^10.1.8",
45
+ "eslint-plugin-n": "^17.23.1",
46
+ "prettier": "3.6.2",
47
+ "tsdown": "^0.18.0",
48
+ "typescript": "^5.9.3",
49
+ "typescript-eslint": "^8.48.1",
50
+ "vitest": "^4.0.15",
51
+ "@modelcontextprotocol/server": "^2.0.0-alpha.2",
52
+ "@modelcontextprotocol/tsconfig": "^2.0.0",
53
+ "@modelcontextprotocol/vitest-config": "^2.0.0",
54
+ "@modelcontextprotocol/eslint-config": "^2.0.0"
55
+ },
56
+ "scripts": {
57
+ "typecheck": "tsgo -p tsconfig.json --noEmit",
58
+ "build": "tsdown",
59
+ "build:watch": "tsdown --watch",
60
+ "lint": "eslint src/ && prettier --ignore-path ../../../.prettierignore --check .",
61
+ "lint:fix": "eslint src/ --fix && prettier --ignore-path ../../../.prettierignore --write .",
62
+ "check": "pnpm run typecheck && pnpm run lint",
63
+ "test": "vitest run",
64
+ "test:watch": "vitest"
65
+ }
66
+ }