@agentailor/create-mcp-server 0.1.0 → 0.2.0
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 +201 -0
- package/README.md +43 -5
- package/dist/index.js +45 -8
- package/dist/templates/common/env.example.d.ts +4 -1
- package/dist/templates/common/env.example.js +17 -2
- package/dist/templates/common/package.json.d.ts +4 -1
- package/dist/templates/common/package.json.js +17 -9
- package/dist/templates/stateful-streamable-http/auth.d.ts +1 -0
- package/dist/templates/stateful-streamable-http/auth.js +199 -0
- package/dist/templates/stateful-streamable-http/auth.test.d.ts +1 -0
- package/dist/templates/stateful-streamable-http/auth.test.js +100 -0
- package/dist/templates/stateful-streamable-http/index.d.ts +5 -1
- package/dist/templates/stateful-streamable-http/index.js +60 -10
- package/dist/templates/stateful-streamable-http/readme.d.ts +2 -1
- package/dist/templates/stateful-streamable-http/readme.js +82 -16
- package/dist/templates/stateful-streamable-http/templates.test.js +87 -0
- package/dist/templates/streamable-http/index.d.ts +4 -1
- package/dist/templates/streamable-http/index.js +3 -1
- package/dist/templates/streamable-http/readme.d.ts +2 -1
- package/dist/templates/streamable-http/readme.js +3 -1
- package/package.json +1 -1
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 [yyyy] [name of copyright owner]
|
|
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
CHANGED
|
@@ -1,19 +1,57 @@
|
|
|
1
1
|
# @agentailor/create-mcp-server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Scaffold production-ready MCP servers in seconds.
|
|
4
4
|
|
|
5
|
-
##
|
|
5
|
+
## Quick Start
|
|
6
6
|
|
|
7
7
|
```bash
|
|
8
8
|
npx @agentailor/create-mcp-server
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
## Features
|
|
12
|
+
|
|
13
|
+
- **Two templates** — stateless or stateful with session management
|
|
14
|
+
- **Optional OAuth** — OIDC-compliant authentication ([setup guide](docs/oauth-setup.md))
|
|
15
|
+
- **Package manager choice** — npm, pnpm, or yarn
|
|
16
|
+
- **TypeScript + Express.js** — ready to customize
|
|
17
|
+
- **MCP Inspector** — built-in debugging with `npm run inspect`
|
|
18
|
+
|
|
19
|
+
## Templates
|
|
20
|
+
|
|
21
|
+
| Feature | Stateless (default) | Stateful |
|
|
22
|
+
|---------|---------------------|----------|
|
|
23
|
+
| Session management | — | ✓ |
|
|
24
|
+
| SSE support | — | ✓ |
|
|
25
|
+
| OAuth option | — | ✓ |
|
|
26
|
+
| Endpoints | POST /mcp | POST, GET, DELETE /mcp |
|
|
27
|
+
|
|
28
|
+
**Stateless**: Simple HTTP server — each request creates a new transport instance.
|
|
29
|
+
|
|
30
|
+
**Stateful**: Session-based server with transport reuse, Server-Sent Events for real-time updates, and optional OAuth authentication.
|
|
31
|
+
|
|
32
|
+
## Generated Project
|
|
33
|
+
|
|
34
|
+
```
|
|
35
|
+
my-mcp-server/
|
|
36
|
+
├── src/
|
|
37
|
+
│ ├── server.ts # MCP server (tools, prompts, resources)
|
|
38
|
+
│ ├── index.ts # Express app and transport setup
|
|
39
|
+
│ └── auth.ts # OAuth middleware (if enabled)
|
|
40
|
+
├── package.json
|
|
41
|
+
├── tsconfig.json
|
|
42
|
+
├── .gitignore
|
|
43
|
+
├── .env.example
|
|
44
|
+
└── README.md
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
**Scripts:**
|
|
48
|
+
- `npm run dev` — build and start the server
|
|
49
|
+
- `npm run inspect` — open MCP Inspector (update URL in `package.json` if needed)
|
|
12
50
|
|
|
13
51
|
## What is MCP?
|
|
14
52
|
|
|
15
53
|
The [Model Context Protocol](https://modelcontextprotocol.io/) (MCP) is an open protocol that enables AI assistants to interact with external tools, data sources, and services.
|
|
16
54
|
|
|
17
|
-
##
|
|
55
|
+
## Built by Agentailor
|
|
18
56
|
|
|
19
|
-
|
|
57
|
+
Built by [Agentailor](https://agentailor.com/?utm_source=github&utm_medium=readme&utm_campaign=create-mcp-server) — your launchpad for production-ready MCP servers and scalable AI agents. We provide the tools, templates, and expertise to ship AI-powered applications faster.
|
package/dist/index.js
CHANGED
|
@@ -2,12 +2,13 @@
|
|
|
2
2
|
import prompts from 'prompts';
|
|
3
3
|
import { mkdir, writeFile } from 'node:fs/promises';
|
|
4
4
|
import { join } from 'node:path';
|
|
5
|
+
import { execSync } from 'node:child_process';
|
|
5
6
|
import { getPackageJsonTemplate } from './templates/common/package.json.js';
|
|
6
7
|
import { getTsconfigTemplate } from './templates/common/tsconfig.json.js';
|
|
7
8
|
import { getGitignoreTemplate } from './templates/common/gitignore.js';
|
|
8
9
|
import { getEnvExampleTemplate } from './templates/common/env.example.js';
|
|
9
10
|
import { getServerTemplate as getStatelessServerTemplate, getIndexTemplate as getStatelessIndexTemplate, getReadmeTemplate as getStatelessReadmeTemplate, } from './templates/streamable-http/index.js';
|
|
10
|
-
import { getServerTemplate as getStatefulServerTemplate, getIndexTemplate as getStatefulIndexTemplate, getReadmeTemplate as getStatefulReadmeTemplate, } from './templates/stateful-streamable-http/index.js';
|
|
11
|
+
import { getServerTemplate as getStatefulServerTemplate, getIndexTemplate as getStatefulIndexTemplate, getReadmeTemplate as getStatefulReadmeTemplate, getAuthTemplate as getStatefulAuthTemplate, } from './templates/stateful-streamable-http/index.js';
|
|
11
12
|
const templateFunctions = {
|
|
12
13
|
stateless: {
|
|
13
14
|
getServerTemplate: getStatelessServerTemplate,
|
|
@@ -18,6 +19,7 @@ const templateFunctions = {
|
|
|
18
19
|
getServerTemplate: getStatefulServerTemplate,
|
|
19
20
|
getIndexTemplate: getStatefulIndexTemplate,
|
|
20
21
|
getReadmeTemplate: getStatefulReadmeTemplate,
|
|
22
|
+
getAuthTemplate: getStatefulAuthTemplate,
|
|
21
23
|
},
|
|
22
24
|
};
|
|
23
25
|
const packageManagerCommands = {
|
|
@@ -77,22 +79,57 @@ async function main() {
|
|
|
77
79
|
initial: 0,
|
|
78
80
|
}, { onCancel });
|
|
79
81
|
const templateType = templateTypeResponse.templateType || 'stateless';
|
|
82
|
+
// OAuth prompt - only for stateful template
|
|
83
|
+
let withOAuth = false;
|
|
84
|
+
if (templateType === 'stateful') {
|
|
85
|
+
const oauthResponse = await prompts({
|
|
86
|
+
type: 'confirm',
|
|
87
|
+
name: 'withOAuth',
|
|
88
|
+
message: 'Enable OAuth authentication?',
|
|
89
|
+
initial: false,
|
|
90
|
+
}, { onCancel });
|
|
91
|
+
withOAuth = oauthResponse.withOAuth ?? false;
|
|
92
|
+
}
|
|
93
|
+
// Git init prompt
|
|
94
|
+
const gitInitResponse = await prompts({
|
|
95
|
+
type: 'confirm',
|
|
96
|
+
name: 'withGitInit',
|
|
97
|
+
message: 'Initialize git repository?',
|
|
98
|
+
initial: true,
|
|
99
|
+
}, { onCancel });
|
|
100
|
+
const withGitInit = gitInitResponse.withGitInit ?? false;
|
|
101
|
+
const templateOptions = { withOAuth };
|
|
80
102
|
const templates = templateFunctions[templateType];
|
|
81
103
|
const projectPath = join(process.cwd(), projectName);
|
|
82
104
|
const srcPath = join(projectPath, 'src');
|
|
83
105
|
try {
|
|
84
106
|
// Create directories
|
|
85
107
|
await mkdir(srcPath, { recursive: true });
|
|
86
|
-
//
|
|
87
|
-
|
|
108
|
+
// Build list of files to write
|
|
109
|
+
const filesToWrite = [
|
|
88
110
|
writeFile(join(srcPath, 'server.ts'), templates.getServerTemplate(projectName)),
|
|
89
|
-
writeFile(join(srcPath, 'index.ts'), templates.getIndexTemplate()),
|
|
90
|
-
writeFile(join(projectPath, 'package.json'), getPackageJsonTemplate(projectName)),
|
|
111
|
+
writeFile(join(srcPath, 'index.ts'), templates.getIndexTemplate(templateOptions)),
|
|
112
|
+
writeFile(join(projectPath, 'package.json'), getPackageJsonTemplate(projectName, templateOptions)),
|
|
91
113
|
writeFile(join(projectPath, 'tsconfig.json'), getTsconfigTemplate()),
|
|
92
114
|
writeFile(join(projectPath, '.gitignore'), getGitignoreTemplate()),
|
|
93
|
-
writeFile(join(projectPath, '.env.example'), getEnvExampleTemplate()),
|
|
94
|
-
writeFile(join(projectPath, 'README.md'), templates.getReadmeTemplate(projectName)),
|
|
95
|
-
]
|
|
115
|
+
writeFile(join(projectPath, '.env.example'), getEnvExampleTemplate(templateOptions)),
|
|
116
|
+
writeFile(join(projectPath, 'README.md'), templates.getReadmeTemplate(projectName, templateOptions)),
|
|
117
|
+
];
|
|
118
|
+
// Conditionally add auth.ts for OAuth-enabled stateful template
|
|
119
|
+
if (withOAuth && templates.getAuthTemplate) {
|
|
120
|
+
filesToWrite.push(writeFile(join(srcPath, 'auth.ts'), templates.getAuthTemplate()));
|
|
121
|
+
}
|
|
122
|
+
// Write all template files
|
|
123
|
+
await Promise.all(filesToWrite);
|
|
124
|
+
// Initialize git repository if requested
|
|
125
|
+
if (withGitInit) {
|
|
126
|
+
try {
|
|
127
|
+
execSync('git init', { cwd: projectPath, stdio: 'ignore' });
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
console.log('\n⚠️ Could not initialize git repository (is git installed?)');
|
|
131
|
+
}
|
|
132
|
+
}
|
|
96
133
|
const commands = packageManagerCommands[packageManager];
|
|
97
134
|
console.log(`\n✅ Created ${projectName} at ${projectPath}`);
|
|
98
135
|
console.log(`\nNext steps:`);
|
|
@@ -1,4 +1,19 @@
|
|
|
1
|
-
export function getEnvExampleTemplate() {
|
|
1
|
+
export function getEnvExampleTemplate(options) {
|
|
2
|
+
const withOAuth = options?.withOAuth ?? false;
|
|
3
|
+
const oauthVars = withOAuth
|
|
4
|
+
? `
|
|
5
|
+
# OAuth Configuration
|
|
6
|
+
# Issuer URL - your OAuth provider's base URL
|
|
7
|
+
# Examples:
|
|
8
|
+
# Auth0: https://your-tenant.auth0.com
|
|
9
|
+
# Keycloak: http://localhost:8080/realms/your-realm
|
|
10
|
+
OAUTH_ISSUER_URL=https://your-oauth-provider.com
|
|
11
|
+
|
|
12
|
+
# Audience - the API identifier (optional, but recommended)
|
|
13
|
+
# This should match the "aud" claim in your JWT tokens
|
|
14
|
+
OAUTH_AUDIENCE=https://your-mcp-server.com
|
|
15
|
+
`
|
|
16
|
+
: '';
|
|
2
17
|
return `PORT=3000
|
|
3
|
-
`;
|
|
18
|
+
${oauthVars}`;
|
|
4
19
|
}
|
|
@@ -1,4 +1,14 @@
|
|
|
1
|
-
export function getPackageJsonTemplate(projectName) {
|
|
1
|
+
export function getPackageJsonTemplate(projectName, options) {
|
|
2
|
+
const withOAuth = options?.withOAuth ?? false;
|
|
3
|
+
const dependencies = {
|
|
4
|
+
'@modelcontextprotocol/sdk': '^1.25.1',
|
|
5
|
+
express: '^5.2.1',
|
|
6
|
+
zod: '^4.3.5',
|
|
7
|
+
};
|
|
8
|
+
if (withOAuth) {
|
|
9
|
+
dependencies['dotenv'] = '^17.2.3';
|
|
10
|
+
dependencies['jose'] = '^6.1.3';
|
|
11
|
+
}
|
|
2
12
|
const packageJson = {
|
|
3
13
|
name: projectName,
|
|
4
14
|
version: '0.1.0',
|
|
@@ -8,16 +18,14 @@ export function getPackageJsonTemplate(projectName) {
|
|
|
8
18
|
build: 'tsc',
|
|
9
19
|
dev: 'tsc && node dist/index.js',
|
|
10
20
|
start: 'node dist/index.js',
|
|
21
|
+
inspect: 'mcp-inspector http://localhost:3000/mcp',
|
|
11
22
|
},
|
|
12
|
-
dependencies
|
|
13
|
-
'@modelcontextprotocol/sdk': '^1.12.1',
|
|
14
|
-
express: '^5.1.0',
|
|
15
|
-
zod: '^3.25.30',
|
|
16
|
-
},
|
|
23
|
+
dependencies,
|
|
17
24
|
devDependencies: {
|
|
18
|
-
'@types/express': '^5.0.
|
|
19
|
-
'@types/node': '^
|
|
20
|
-
typescript: '^5.
|
|
25
|
+
'@types/express': '^5.0.6',
|
|
26
|
+
'@types/node': '^25.0.3',
|
|
27
|
+
typescript: '^5.9.3',
|
|
28
|
+
'@modelcontextprotocol/inspector': '^0.18.0',
|
|
21
29
|
},
|
|
22
30
|
engines: {
|
|
23
31
|
node: '>=20',
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function getAuthTemplate(): string;
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
export function getAuthTemplate() {
|
|
2
|
+
return `import 'dotenv/config';
|
|
3
|
+
import { createRemoteJWKSet, jwtVerify, type JWTPayload, type JWTVerifyGetKey } from 'jose';
|
|
4
|
+
import {
|
|
5
|
+
mcpAuthMetadataRouter,
|
|
6
|
+
getOAuthProtectedResourceMetadataUrl,
|
|
7
|
+
} from '@modelcontextprotocol/sdk/server/auth/router.js';
|
|
8
|
+
import { requireBearerAuth } from '@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js';
|
|
9
|
+
import type { OAuthMetadata } from '@modelcontextprotocol/sdk/shared/auth.js';
|
|
10
|
+
import type { Express, RequestHandler } from 'express';
|
|
11
|
+
|
|
12
|
+
// OAuth configuration from environment variables
|
|
13
|
+
const CONFIG = {
|
|
14
|
+
host: process.env.HOST || 'localhost',
|
|
15
|
+
port: Number(process.env.PORT) || 3000,
|
|
16
|
+
oauth: {
|
|
17
|
+
issuerUrl: process.env.OAUTH_ISSUER_URL || 'http://localhost:8080',
|
|
18
|
+
audience: process.env.OAUTH_AUDIENCE || '',
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
// Ensure issuer URL doesn't have trailing slash for consistency
|
|
23
|
+
const normalizedIssuerUrl = CONFIG.oauth.issuerUrl.replace(/\\/$/, '');
|
|
24
|
+
|
|
25
|
+
const mcpServerUrl = new URL(\`http://\${CONFIG.host}:\${CONFIG.port}\`);
|
|
26
|
+
|
|
27
|
+
// OAuth metadata and JWKS fetched from OIDC discovery endpoint at startup
|
|
28
|
+
let oauthMetadata: OAuthMetadata | null = null;
|
|
29
|
+
let JWKS: JWTVerifyGetKey | null = null;
|
|
30
|
+
|
|
31
|
+
// Extended JWT payload type with common OAuth claims
|
|
32
|
+
interface OAuthJWTPayload extends JWTPayload {
|
|
33
|
+
scope?: string;
|
|
34
|
+
azp?: string;
|
|
35
|
+
client_id?: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// OIDC Discovery document structure (partial)
|
|
39
|
+
interface OIDCDiscoveryDocument {
|
|
40
|
+
issuer: string;
|
|
41
|
+
authorization_endpoint: string;
|
|
42
|
+
token_endpoint: string;
|
|
43
|
+
jwks_uri: string;
|
|
44
|
+
response_types_supported?: string[];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Token verifier using JWKS/JWT validation
|
|
48
|
+
const tokenVerifier = {
|
|
49
|
+
verifyAccessToken: async (token: string) => {
|
|
50
|
+
if (!JWKS) {
|
|
51
|
+
throw new Error('JWKS not initialized. Call validateOAuthConfig() first.');
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
try {
|
|
55
|
+
// Check if the token looks like a JWT (three base64url-encoded parts separated by dots)
|
|
56
|
+
const parts = token.split('.');
|
|
57
|
+
if (parts.length !== 3) {
|
|
58
|
+
throw new Error(
|
|
59
|
+
'Token is not a valid JWT format (expected 3 parts separated by dots). '
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const verifyOptions: { issuer: string; audience?: string } = {
|
|
64
|
+
issuer: normalizedIssuerUrl,
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
// Only validate audience if configured
|
|
68
|
+
if (CONFIG.oauth.audience) {
|
|
69
|
+
verifyOptions.audience = CONFIG.oauth.audience;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const { payload } = await jwtVerify(token, JWKS, verifyOptions);
|
|
73
|
+
const jwtPayload = payload as OAuthJWTPayload;
|
|
74
|
+
|
|
75
|
+
return {
|
|
76
|
+
token,
|
|
77
|
+
// Use azp (authorized party), client_id, or sub as the client identifier
|
|
78
|
+
clientId: jwtPayload.azp || jwtPayload.client_id || jwtPayload.sub || 'unknown',
|
|
79
|
+
scopes: jwtPayload.scope ? jwtPayload.scope.split(' ') : [],
|
|
80
|
+
expiresAt: jwtPayload.exp,
|
|
81
|
+
};
|
|
82
|
+
} catch (error) {
|
|
83
|
+
if (error instanceof Error) {
|
|
84
|
+
console.error('[auth] JWT verification failed:', error.message);
|
|
85
|
+
}
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
// Setup OAuth metadata router on the Express app
|
|
92
|
+
// Must be called AFTER validateOAuthConfig() to ensure oauthMetadata is populated
|
|
93
|
+
export function setupAuthMetadataRouter(app: Express): void {
|
|
94
|
+
if (!oauthMetadata) {
|
|
95
|
+
throw new Error('OAuth metadata not initialized. Call validateOAuthConfig() first.');
|
|
96
|
+
}
|
|
97
|
+
app.use(
|
|
98
|
+
mcpAuthMetadataRouter({
|
|
99
|
+
oauthMetadata,
|
|
100
|
+
resourceServerUrl: mcpServerUrl,
|
|
101
|
+
scopesSupported: ['mcp:tools'],
|
|
102
|
+
resourceName: 'MCP Server',
|
|
103
|
+
})
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Export auth middleware for protecting routes
|
|
108
|
+
export const authMiddleware: RequestHandler = requireBearerAuth({
|
|
109
|
+
verifier: tokenVerifier,
|
|
110
|
+
requiredScopes: [],
|
|
111
|
+
resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(mcpServerUrl),
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
// Export for logging on startup
|
|
115
|
+
export function getOAuthMetadataUrl(): string {
|
|
116
|
+
return getOAuthProtectedResourceMetadataUrl(mcpServerUrl).toString();
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Validate OAuth configuration and fetch OIDC discovery document at startup
|
|
120
|
+
export async function validateOAuthConfig(): Promise<void> {
|
|
121
|
+
console.log(\`[auth] Validating OAuth configuration for issuer: \${normalizedIssuerUrl}\`);
|
|
122
|
+
|
|
123
|
+
const wellKnownUrl = \`\${normalizedIssuerUrl}/.well-known/openid-configuration\`;
|
|
124
|
+
|
|
125
|
+
// Fetch the OIDC discovery document to get the correct endpoints
|
|
126
|
+
let discovery: OIDCDiscoveryDocument;
|
|
127
|
+
try {
|
|
128
|
+
const response = await fetch(wellKnownUrl, {
|
|
129
|
+
method: 'GET',
|
|
130
|
+
signal: AbortSignal.timeout(5000),
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
if (!response.ok) {
|
|
134
|
+
throw new Error(\`HTTP \${response.status}: \${response.statusText}\`);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
discovery = (await response.json()) as OIDCDiscoveryDocument;
|
|
138
|
+
console.log('[auth] Successfully fetched OIDC discovery document');
|
|
139
|
+
|
|
140
|
+
// Build OAuth metadata from the discovery document
|
|
141
|
+
oauthMetadata = {
|
|
142
|
+
issuer: discovery.issuer,
|
|
143
|
+
authorization_endpoint: discovery.authorization_endpoint,
|
|
144
|
+
token_endpoint: discovery.token_endpoint,
|
|
145
|
+
response_types_supported: discovery.response_types_supported || ['code'],
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
console.log(\`[auth] Authorization endpoint: \${discovery.authorization_endpoint}\`);
|
|
149
|
+
console.log(\`[auth] Token endpoint: \${discovery.token_endpoint}\`);
|
|
150
|
+
} catch (e) {
|
|
151
|
+
const error = e instanceof Error ? e : new Error(String(e));
|
|
152
|
+
const errorMessage = [
|
|
153
|
+
'Failed to fetch OIDC discovery document',
|
|
154
|
+
\` Discovery URL: \${wellKnownUrl}\`,
|
|
155
|
+
\` Error: \${error.message}\`,
|
|
156
|
+
'',
|
|
157
|
+
'Please ensure:',
|
|
158
|
+
' 1. The OAUTH_ISSUER_URL environment variable is correct',
|
|
159
|
+
' 2. The OAuth server is running and accessible',
|
|
160
|
+
' 3. The OAuth server supports OIDC discovery (.well-known/openid-configuration)',
|
|
161
|
+
' 4. Network/firewall settings allow the connection',
|
|
162
|
+
].join('\\n');
|
|
163
|
+
|
|
164
|
+
throw new Error(errorMessage);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// Create JWKS from the discovery document's jwks_uri
|
|
168
|
+
const jwksUri = discovery.jwks_uri;
|
|
169
|
+
console.log(\`[auth] JWKS URI: \${jwksUri}\`);
|
|
170
|
+
JWKS = createRemoteJWKSet(new URL(jwksUri));
|
|
171
|
+
|
|
172
|
+
// Verify the JWKS endpoint is accessible
|
|
173
|
+
try {
|
|
174
|
+
const jwksResponse = await fetch(jwksUri, {
|
|
175
|
+
method: 'GET',
|
|
176
|
+
signal: AbortSignal.timeout(5000),
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
if (!jwksResponse.ok) {
|
|
180
|
+
throw new Error(\`HTTP \${jwksResponse.status}: \${jwksResponse.statusText}\`);
|
|
181
|
+
}
|
|
182
|
+
console.log('[auth] JWKS endpoint is accessible');
|
|
183
|
+
} catch (e) {
|
|
184
|
+
const error = e instanceof Error ? e : new Error(String(e));
|
|
185
|
+
const errorMessage = [
|
|
186
|
+
'Failed to fetch JWKS from OAuth server',
|
|
187
|
+
\` JWKS URI: \${jwksUri}\`,
|
|
188
|
+
\` Error: \${error.message}\`,
|
|
189
|
+
'',
|
|
190
|
+
'Please ensure the OAuth server is properly configured.',
|
|
191
|
+
].join('\\n');
|
|
192
|
+
|
|
193
|
+
throw new Error(errorMessage);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
console.log('[auth] OAuth configuration validated successfully');
|
|
197
|
+
}
|
|
198
|
+
`;
|
|
199
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import { getAuthTemplate } from './auth.js';
|
|
3
|
+
describe('auth template', () => {
|
|
4
|
+
describe('getAuthTemplate', () => {
|
|
5
|
+
it('should include OAuth configuration from environment variables', () => {
|
|
6
|
+
const template = getAuthTemplate();
|
|
7
|
+
expect(template).toContain('OAUTH_ISSUER_URL');
|
|
8
|
+
expect(template).toContain('OAUTH_AUDIENCE');
|
|
9
|
+
});
|
|
10
|
+
it('should include dotenv import', () => {
|
|
11
|
+
const template = getAuthTemplate();
|
|
12
|
+
expect(template).toContain("import 'dotenv/config'");
|
|
13
|
+
});
|
|
14
|
+
it('should import jose for JWT verification', () => {
|
|
15
|
+
const template = getAuthTemplate();
|
|
16
|
+
expect(template).toContain("from 'jose'");
|
|
17
|
+
expect(template).toContain('createRemoteJWKSet');
|
|
18
|
+
expect(template).toContain('jwtVerify');
|
|
19
|
+
});
|
|
20
|
+
it('should use SDK auth imports', () => {
|
|
21
|
+
const template = getAuthTemplate();
|
|
22
|
+
expect(template).toContain("from '@modelcontextprotocol/sdk/server/auth/router.js'");
|
|
23
|
+
expect(template).toContain("from '@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js'");
|
|
24
|
+
expect(template).toContain("from '@modelcontextprotocol/sdk/shared/auth.js'");
|
|
25
|
+
});
|
|
26
|
+
it('should export setupAuthMetadataRouter function', () => {
|
|
27
|
+
const template = getAuthTemplate();
|
|
28
|
+
expect(template).toContain('export function setupAuthMetadataRouter');
|
|
29
|
+
expect(template).toContain('mcpAuthMetadataRouter');
|
|
30
|
+
});
|
|
31
|
+
it('should export authMiddleware', () => {
|
|
32
|
+
const template = getAuthTemplate();
|
|
33
|
+
expect(template).toContain('export const authMiddleware');
|
|
34
|
+
expect(template).toContain('requireBearerAuth');
|
|
35
|
+
});
|
|
36
|
+
it('should export getOAuthMetadataUrl helper', () => {
|
|
37
|
+
const template = getAuthTemplate();
|
|
38
|
+
expect(template).toContain('export function getOAuthMetadataUrl');
|
|
39
|
+
expect(template).toContain('getOAuthProtectedResourceMetadataUrl');
|
|
40
|
+
});
|
|
41
|
+
it('should include token verifier using JWKS/JWT', () => {
|
|
42
|
+
const template = getAuthTemplate();
|
|
43
|
+
expect(template).toContain('tokenVerifier');
|
|
44
|
+
expect(template).toContain('verifyAccessToken');
|
|
45
|
+
expect(template).toContain('jwtVerify(token, JWKS');
|
|
46
|
+
});
|
|
47
|
+
it('should create remote JWKS from discovery document jwks_uri', () => {
|
|
48
|
+
const template = getAuthTemplate();
|
|
49
|
+
expect(template).toContain('createRemoteJWKSet');
|
|
50
|
+
expect(template).toContain('discovery.jwks_uri');
|
|
51
|
+
expect(template).toContain('JWKS = createRemoteJWKSet');
|
|
52
|
+
});
|
|
53
|
+
it('should validate issuer and audience claims', () => {
|
|
54
|
+
const template = getAuthTemplate();
|
|
55
|
+
expect(template).toContain('issuer:');
|
|
56
|
+
expect(template).toContain('audience:');
|
|
57
|
+
});
|
|
58
|
+
it('should use Express types', () => {
|
|
59
|
+
const template = getAuthTemplate();
|
|
60
|
+
expect(template).toContain("from 'express'");
|
|
61
|
+
expect(template).toContain('Express');
|
|
62
|
+
expect(template).toContain('RequestHandler');
|
|
63
|
+
});
|
|
64
|
+
it('should export validateOAuthConfig function', () => {
|
|
65
|
+
const template = getAuthTemplate();
|
|
66
|
+
expect(template).toContain('export async function validateOAuthConfig');
|
|
67
|
+
});
|
|
68
|
+
it('should check well-known endpoint for OAuth server availability', () => {
|
|
69
|
+
const template = getAuthTemplate();
|
|
70
|
+
expect(template).toContain('.well-known/openid-configuration');
|
|
71
|
+
});
|
|
72
|
+
it('should throw detailed error when OIDC discovery fails', () => {
|
|
73
|
+
const template = getAuthTemplate();
|
|
74
|
+
expect(template).toContain('Failed to fetch OIDC discovery document');
|
|
75
|
+
expect(template).toContain('OAUTH_ISSUER_URL environment variable');
|
|
76
|
+
expect(template).toContain('OAuth server is running and accessible');
|
|
77
|
+
});
|
|
78
|
+
it('should fetch OAuth metadata from OIDC discovery endpoint', () => {
|
|
79
|
+
const template = getAuthTemplate();
|
|
80
|
+
expect(template).toContain('OIDCDiscoveryDocument');
|
|
81
|
+
expect(template).toContain('authorization_endpoint');
|
|
82
|
+
expect(template).toContain('token_endpoint');
|
|
83
|
+
expect(template).toContain('oauthMetadata = {');
|
|
84
|
+
});
|
|
85
|
+
it('should use timeout for OAuth server validation requests', () => {
|
|
86
|
+
const template = getAuthTemplate();
|
|
87
|
+
expect(template).toContain('AbortSignal.timeout(5000)');
|
|
88
|
+
});
|
|
89
|
+
it('should extract client ID from JWT claims', () => {
|
|
90
|
+
const template = getAuthTemplate();
|
|
91
|
+
expect(template).toContain('azp');
|
|
92
|
+
expect(template).toContain('client_id');
|
|
93
|
+
expect(template).toContain('sub');
|
|
94
|
+
});
|
|
95
|
+
it('should extract scopes from JWT scope claim', () => {
|
|
96
|
+
const template = getAuthTemplate();
|
|
97
|
+
expect(template).toContain("jwtPayload.scope.split(' ')");
|
|
98
|
+
});
|
|
99
|
+
});
|
|
100
|
+
});
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
-
export
|
|
1
|
+
export interface TemplateOptions {
|
|
2
|
+
withOAuth?: boolean;
|
|
3
|
+
}
|
|
4
|
+
export declare function getIndexTemplate(options?: TemplateOptions): string;
|
|
2
5
|
export { getServerTemplate } from './server.js';
|
|
3
6
|
export { getReadmeTemplate } from './readme.js';
|
|
7
|
+
export { getAuthTemplate } from './auth.js';
|
|
@@ -1,17 +1,46 @@
|
|
|
1
|
-
export function getIndexTemplate() {
|
|
2
|
-
|
|
1
|
+
export function getIndexTemplate(options) {
|
|
2
|
+
const withOAuth = options?.withOAuth ?? false;
|
|
3
|
+
const imports = withOAuth
|
|
4
|
+
? `import { type Request, type Response } from 'express';
|
|
3
5
|
import { randomUUID } from 'node:crypto';
|
|
4
6
|
import { createMcpExpressApp } from '@modelcontextprotocol/sdk/server/express.js';
|
|
5
7
|
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
6
8
|
import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
|
|
7
9
|
import { getServer } from './server.js';
|
|
8
|
-
|
|
9
|
-
|
|
10
|
+
import {
|
|
11
|
+
setupAuthMetadataRouter,
|
|
12
|
+
authMiddleware,
|
|
13
|
+
getOAuthMetadataUrl,
|
|
14
|
+
validateOAuthConfig,
|
|
15
|
+
} from './auth.js';`
|
|
16
|
+
: `import { type Request, type Response } from 'express';
|
|
17
|
+
import { randomUUID } from 'node:crypto';
|
|
18
|
+
import { createMcpExpressApp } from '@modelcontextprotocol/sdk/server/express.js';
|
|
19
|
+
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
20
|
+
import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
|
|
21
|
+
import { getServer } from './server.js';`;
|
|
22
|
+
const appSetup = `const app = createMcpExpressApp();`;
|
|
23
|
+
const postRoute = withOAuth
|
|
24
|
+
? `app.post('/mcp', authMiddleware, async (req: Request, res: Response) => {`
|
|
25
|
+
: `app.post('/mcp', async (req: Request, res: Response) => {`;
|
|
26
|
+
const getRoute = withOAuth
|
|
27
|
+
? `app.get('/mcp', authMiddleware, async (req: Request, res: Response) => {`
|
|
28
|
+
: `app.get('/mcp', async (req: Request, res: Response) => {`;
|
|
29
|
+
const deleteRoute = withOAuth
|
|
30
|
+
? `app.delete('/mcp', authMiddleware, async (req: Request, res: Response) => {`
|
|
31
|
+
: `app.delete('/mcp', async (req: Request, res: Response) => {`;
|
|
32
|
+
const startupLog = withOAuth
|
|
33
|
+
? `console.log(\`MCP Stateful HTTP Server listening on port \${PORT}\`);
|
|
34
|
+
console.log(\`OAuth metadata available at \${getOAuthMetadataUrl()}\`);`
|
|
35
|
+
: `console.log(\`MCP Stateful HTTP Server listening on port \${PORT}\`);`;
|
|
36
|
+
return `${imports}
|
|
37
|
+
|
|
38
|
+
${appSetup}
|
|
10
39
|
|
|
11
40
|
// Map to store transports by session ID
|
|
12
41
|
const transports: { [sessionId: string]: StreamableHTTPServerTransport } = {};
|
|
13
42
|
|
|
14
|
-
|
|
43
|
+
${postRoute}
|
|
15
44
|
const sessionId = req.headers['mcp-session-id'] as string | undefined;
|
|
16
45
|
if (sessionId) {
|
|
17
46
|
console.log(\`Received MCP request for session: \${sessionId}\`);
|
|
@@ -79,7 +108,7 @@ app.post('/mcp', async (req: Request, res: Response) => {
|
|
|
79
108
|
}
|
|
80
109
|
});
|
|
81
110
|
|
|
82
|
-
|
|
111
|
+
${getRoute}
|
|
83
112
|
const sessionId = req.headers['mcp-session-id'] as string | undefined;
|
|
84
113
|
if (!sessionId || !transports[sessionId]) {
|
|
85
114
|
res.status(400).send('Invalid or missing session ID');
|
|
@@ -91,7 +120,7 @@ app.get('/mcp', async (req: Request, res: Response) => {
|
|
|
91
120
|
await transport.handleRequest(req, res);
|
|
92
121
|
});
|
|
93
122
|
|
|
94
|
-
|
|
123
|
+
${deleteRoute}
|
|
95
124
|
const sessionId = req.headers['mcp-session-id'] as string | undefined;
|
|
96
125
|
if (!sessionId || !transports[sessionId]) {
|
|
97
126
|
res.status(400).send('Invalid or missing session ID');
|
|
@@ -111,11 +140,31 @@ app.delete('/mcp', async (req: Request, res: Response) => {
|
|
|
111
140
|
}
|
|
112
141
|
});
|
|
113
142
|
|
|
114
|
-
|
|
143
|
+
${withOAuth
|
|
144
|
+
? `// Start the server
|
|
145
|
+
const PORT = process.env.PORT || 3000;
|
|
146
|
+
|
|
147
|
+
async function main() {
|
|
148
|
+
// Validate OAuth configuration and fetch OIDC discovery document
|
|
149
|
+
await validateOAuthConfig();
|
|
150
|
+
|
|
151
|
+
// Setup OAuth metadata routes (must be after validateOAuthConfig)
|
|
152
|
+
setupAuthMetadataRouter(app);
|
|
153
|
+
|
|
154
|
+
app.listen(PORT, () => {
|
|
155
|
+
${startupLog}
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
main().catch((error) => {
|
|
160
|
+
console.error('Failed to start server:', error.message);
|
|
161
|
+
process.exit(1);
|
|
162
|
+
});`
|
|
163
|
+
: `// Start the server
|
|
115
164
|
const PORT = process.env.PORT || 3000;
|
|
116
165
|
app.listen(PORT, () => {
|
|
117
|
-
|
|
118
|
-
})
|
|
166
|
+
${startupLog}
|
|
167
|
+
});`}
|
|
119
168
|
|
|
120
169
|
// Handle server shutdown
|
|
121
170
|
process.on('SIGINT', async () => {
|
|
@@ -138,3 +187,4 @@ process.on('SIGINT', async () => {
|
|
|
138
187
|
}
|
|
139
188
|
export { getServerTemplate } from './server.js';
|
|
140
189
|
export { getReadmeTemplate } from './readme.js';
|
|
190
|
+
export { getAuthTemplate } from './auth.js';
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import type { TemplateOptions } from './index.js';
|
|
2
|
+
export declare function getReadmeTemplate(projectName: string, options?: TemplateOptions): string;
|
|
@@ -1,7 +1,81 @@
|
|
|
1
|
-
export function getReadmeTemplate(projectName) {
|
|
1
|
+
export function getReadmeTemplate(projectName, options) {
|
|
2
|
+
const withOAuth = options?.withOAuth ?? false;
|
|
3
|
+
const description = withOAuth
|
|
4
|
+
? 'A stateful streamable HTTP MCP (Model Context Protocol) server with session management and OAuth authentication.'
|
|
5
|
+
: 'A stateful streamable HTTP MCP (Model Context Protocol) server with session management.';
|
|
6
|
+
const oauthSection = withOAuth
|
|
7
|
+
? `
|
|
8
|
+
## OAuth Authentication
|
|
9
|
+
|
|
10
|
+
This server uses OAuth 2.0 with JWT tokens for authentication. It works with any OIDC-compliant provider including:
|
|
11
|
+
- Auth0
|
|
12
|
+
- Keycloak
|
|
13
|
+
- Azure AD / Entra ID
|
|
14
|
+
- Okta
|
|
15
|
+
- And more...
|
|
16
|
+
|
|
17
|
+
### Environment Variables
|
|
18
|
+
|
|
19
|
+
| Variable | Description | Example |
|
|
20
|
+
|----------|-------------|---------|
|
|
21
|
+
| \`OAUTH_ISSUER_URL\` | Base URL of your OAuth provider | \`https://your-tenant.auth0.com\` |
|
|
22
|
+
| \`OAUTH_AUDIENCE\` | API identifier / audience claim (optional) | \`https://your-api.com\` |
|
|
23
|
+
|
|
24
|
+
### Provider-Specific Issuer URLs
|
|
25
|
+
|
|
26
|
+
| Provider | Issuer URL Format |
|
|
27
|
+
|----------|-------------------|
|
|
28
|
+
| Auth0 | \`https://{tenant}.auth0.com\` |
|
|
29
|
+
| Keycloak | \`http://{host}:{port}/realms/{realm}\` |
|
|
30
|
+
| Azure AD | \`https://login.microsoftonline.com/{tenant}/v2.0\` |
|
|
31
|
+
| Okta | \`https://{domain}.okta.com/oauth2/default\` |
|
|
32
|
+
|
|
33
|
+
### How It Works
|
|
34
|
+
|
|
35
|
+
1. The server fetches public keys from \`{OAUTH_ISSUER_URL}/.well-known/jwks.json\`
|
|
36
|
+
2. Incoming JWT tokens are verified locally using these keys
|
|
37
|
+
3. The token's \`iss\` (issuer) and optionally \`aud\` (audience) claims are validated
|
|
38
|
+
|
|
39
|
+
### Protected Resource Metadata
|
|
40
|
+
|
|
41
|
+
- **GET /.well-known/oauth-protected-resource** - OAuth protected resource metadata
|
|
42
|
+
|
|
43
|
+
### Token Requirements
|
|
44
|
+
|
|
45
|
+
- All MCP endpoints require a valid JWT Bearer token in the \`Authorization\` header
|
|
46
|
+
- Tokens must be signed by the configured OAuth provider
|
|
47
|
+
- If \`OAUTH_AUDIENCE\` is set, the token's \`aud\` claim must match
|
|
48
|
+
`
|
|
49
|
+
: '';
|
|
50
|
+
const apiEndpointsOAuthNote = withOAuth
|
|
51
|
+
? '\n - Requires valid Bearer token in Authorization header'
|
|
52
|
+
: '';
|
|
53
|
+
const projectStructure = withOAuth
|
|
54
|
+
? `\`\`\`
|
|
55
|
+
${projectName}/
|
|
56
|
+
├── src/
|
|
57
|
+
│ ├── server.ts # MCP server definition (tools, prompts, resources)
|
|
58
|
+
│ ├── index.ts # Express app and stateful HTTP transport setup
|
|
59
|
+
│ └── auth.ts # OAuth configuration and middleware
|
|
60
|
+
├── package.json
|
|
61
|
+
├── tsconfig.json
|
|
62
|
+
└── README.md
|
|
63
|
+
\`\`\``
|
|
64
|
+
: `\`\`\`
|
|
65
|
+
${projectName}/
|
|
66
|
+
├── src/
|
|
67
|
+
│ ├── server.ts # MCP server definition (tools, prompts, resources)
|
|
68
|
+
│ └── index.ts # Express app and stateful HTTP transport setup
|
|
69
|
+
├── package.json
|
|
70
|
+
├── tsconfig.json
|
|
71
|
+
└── README.md
|
|
72
|
+
\`\`\``;
|
|
73
|
+
const customizationOAuthNote = withOAuth
|
|
74
|
+
? '\n- Configure OAuth scopes and token verification in `src/auth.ts`'
|
|
75
|
+
: '';
|
|
2
76
|
return `# ${projectName}
|
|
3
77
|
|
|
4
|
-
|
|
78
|
+
${description}
|
|
5
79
|
|
|
6
80
|
## About
|
|
7
81
|
|
|
@@ -22,16 +96,16 @@ npm start
|
|
|
22
96
|
\`\`\`
|
|
23
97
|
|
|
24
98
|
The server will start on port 3000 by default. You can change this by setting the \`PORT\` environment variable.
|
|
25
|
-
|
|
99
|
+
${oauthSection}
|
|
26
100
|
## API Endpoints
|
|
27
101
|
|
|
28
102
|
- **POST /mcp** - Main MCP endpoint for JSON-RPC messages
|
|
29
103
|
- First request must be an initialization request (no session ID required)
|
|
30
|
-
- Subsequent requests must include \`mcp-session-id\` header
|
|
104
|
+
- Subsequent requests must include \`mcp-session-id\` header${apiEndpointsOAuthNote}
|
|
31
105
|
- **GET /mcp** - Server-Sent Events (SSE) stream for server-initiated messages
|
|
32
|
-
- Requires \`mcp-session-id\` header
|
|
106
|
+
- Requires \`mcp-session-id\` header${apiEndpointsOAuthNote}
|
|
33
107
|
- **DELETE /mcp** - Terminate a session
|
|
34
|
-
- Requires \`mcp-session-id\` header
|
|
108
|
+
- Requires \`mcp-session-id\` header${apiEndpointsOAuthNote}
|
|
35
109
|
|
|
36
110
|
## Session Management
|
|
37
111
|
|
|
@@ -63,20 +137,12 @@ This server comes with example implementations to help you get started:
|
|
|
63
137
|
|
|
64
138
|
## Project Structure
|
|
65
139
|
|
|
66
|
-
|
|
67
|
-
${projectName}/
|
|
68
|
-
├── src/
|
|
69
|
-
│ ├── server.ts # MCP server definition (tools, prompts, resources)
|
|
70
|
-
│ └── index.ts # Express app and stateful HTTP transport setup
|
|
71
|
-
├── package.json
|
|
72
|
-
├── tsconfig.json
|
|
73
|
-
└── README.md
|
|
74
|
-
\`\`\`
|
|
140
|
+
${projectStructure}
|
|
75
141
|
|
|
76
142
|
## Customization
|
|
77
143
|
|
|
78
144
|
- Add new tools, prompts, and resources in \`src/server.ts\`
|
|
79
|
-
- Modify the HTTP transport configuration in \`src/index.ts
|
|
145
|
+
- Modify the HTTP transport configuration in \`src/index.ts\`${customizationOAuthNote}
|
|
80
146
|
|
|
81
147
|
## Learn More
|
|
82
148
|
|
|
@@ -108,4 +108,91 @@ describe('stateful-streamable-http templates', () => {
|
|
|
108
108
|
expect(template).toContain('DELETE /mcp');
|
|
109
109
|
});
|
|
110
110
|
});
|
|
111
|
+
describe('getIndexTemplate with OAuth', () => {
|
|
112
|
+
it('should include auth imports when OAuth enabled', () => {
|
|
113
|
+
const template = getIndexTemplate({ withOAuth: true });
|
|
114
|
+
expect(template).toContain("from './auth.js'");
|
|
115
|
+
expect(template).toContain('setupAuthMetadataRouter');
|
|
116
|
+
expect(template).toContain('authMiddleware');
|
|
117
|
+
expect(template).toContain('getOAuthMetadataUrl');
|
|
118
|
+
});
|
|
119
|
+
it('should import validateOAuthConfig when OAuth enabled', () => {
|
|
120
|
+
const template = getIndexTemplate({ withOAuth: true });
|
|
121
|
+
expect(template).toContain('validateOAuthConfig');
|
|
122
|
+
});
|
|
123
|
+
it('should setup auth metadata router when OAuth enabled', () => {
|
|
124
|
+
const template = getIndexTemplate({ withOAuth: true });
|
|
125
|
+
expect(template).toContain('setupAuthMetadataRouter(app)');
|
|
126
|
+
});
|
|
127
|
+
it('should apply auth middleware to routes when OAuth enabled', () => {
|
|
128
|
+
const template = getIndexTemplate({ withOAuth: true });
|
|
129
|
+
expect(template).toContain("app.post('/mcp', authMiddleware,");
|
|
130
|
+
expect(template).toContain("app.get('/mcp', authMiddleware,");
|
|
131
|
+
expect(template).toContain("app.delete('/mcp', authMiddleware,");
|
|
132
|
+
});
|
|
133
|
+
it('should log OAuth metadata URL on startup when OAuth enabled', () => {
|
|
134
|
+
const template = getIndexTemplate({ withOAuth: true });
|
|
135
|
+
expect(template).toContain('getOAuthMetadataUrl()');
|
|
136
|
+
});
|
|
137
|
+
it('should call validateOAuthConfig before starting server when OAuth enabled', () => {
|
|
138
|
+
const template = getIndexTemplate({ withOAuth: true });
|
|
139
|
+
expect(template).toContain('await validateOAuthConfig()');
|
|
140
|
+
});
|
|
141
|
+
it('should wrap server startup in async main function when OAuth enabled', () => {
|
|
142
|
+
const template = getIndexTemplate({ withOAuth: true });
|
|
143
|
+
expect(template).toContain('async function main()');
|
|
144
|
+
expect(template).toContain('main().catch');
|
|
145
|
+
});
|
|
146
|
+
it('should exit with error if OAuth validation fails', () => {
|
|
147
|
+
const template = getIndexTemplate({ withOAuth: true });
|
|
148
|
+
expect(template).toContain('Failed to start server');
|
|
149
|
+
expect(template).toContain('process.exit(1)');
|
|
150
|
+
});
|
|
151
|
+
it('should NOT include auth imports when OAuth disabled', () => {
|
|
152
|
+
const template = getIndexTemplate({ withOAuth: false });
|
|
153
|
+
expect(template).not.toContain("from './auth.js'");
|
|
154
|
+
expect(template).not.toContain('authMiddleware');
|
|
155
|
+
});
|
|
156
|
+
it('should NOT include auth imports by default', () => {
|
|
157
|
+
const template = getIndexTemplate();
|
|
158
|
+
expect(template).not.toContain("from './auth.js'");
|
|
159
|
+
});
|
|
160
|
+
it('should NOT wrap in async main when OAuth disabled', () => {
|
|
161
|
+
const template = getIndexTemplate({ withOAuth: false });
|
|
162
|
+
expect(template).not.toContain('async function main()');
|
|
163
|
+
});
|
|
164
|
+
});
|
|
165
|
+
describe('getReadmeTemplate with OAuth', () => {
|
|
166
|
+
it('should include OAuth section when enabled', () => {
|
|
167
|
+
const template = getReadmeTemplate(projectName, { withOAuth: true });
|
|
168
|
+
expect(template).toContain('## OAuth Authentication');
|
|
169
|
+
expect(template).toContain('OAUTH_ISSUER_URL');
|
|
170
|
+
expect(template).toContain('OAUTH_AUDIENCE');
|
|
171
|
+
expect(template).toContain('Bearer token');
|
|
172
|
+
});
|
|
173
|
+
it('should list supported OAuth providers', () => {
|
|
174
|
+
const template = getReadmeTemplate(projectName, { withOAuth: true });
|
|
175
|
+
expect(template).toContain('Auth0');
|
|
176
|
+
expect(template).toContain('Keycloak');
|
|
177
|
+
expect(template).toContain('Azure AD');
|
|
178
|
+
expect(template).toContain('Okta');
|
|
179
|
+
});
|
|
180
|
+
it('should document JWKS-based JWT validation', () => {
|
|
181
|
+
const template = getReadmeTemplate(projectName, { withOAuth: true });
|
|
182
|
+
expect(template).toContain('JWT');
|
|
183
|
+
expect(template).toContain('.well-known/jwks.json');
|
|
184
|
+
});
|
|
185
|
+
it('should include auth.ts in project structure when OAuth enabled', () => {
|
|
186
|
+
const template = getReadmeTemplate(projectName, { withOAuth: true });
|
|
187
|
+
expect(template).toContain('auth.ts');
|
|
188
|
+
});
|
|
189
|
+
it('should NOT include OAuth section when disabled', () => {
|
|
190
|
+
const template = getReadmeTemplate(projectName, { withOAuth: false });
|
|
191
|
+
expect(template).not.toContain('## OAuth Authentication');
|
|
192
|
+
});
|
|
193
|
+
it('should NOT include OAuth section by default', () => {
|
|
194
|
+
const template = getReadmeTemplate(projectName);
|
|
195
|
+
expect(template).not.toContain('## OAuth Authentication');
|
|
196
|
+
});
|
|
197
|
+
});
|
|
111
198
|
});
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
-
export
|
|
1
|
+
export interface TemplateOptions {
|
|
2
|
+
withOAuth?: boolean;
|
|
3
|
+
}
|
|
4
|
+
export declare function getIndexTemplate(options?: TemplateOptions): string;
|
|
2
5
|
export { getServerTemplate } from './server.js';
|
|
3
6
|
export { getReadmeTemplate } from './readme.js';
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
|
|
1
|
+
// Options parameter added for type consistency with stateful template (OAuth not supported in stateless)
|
|
2
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
3
|
+
export function getIndexTemplate(options) {
|
|
2
4
|
return `import { type Request, type Response } from 'express';
|
|
3
5
|
import { createMcpExpressApp } from '@modelcontextprotocol/sdk/server/express.js';
|
|
4
6
|
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import type { TemplateOptions } from './index.js';
|
|
2
|
+
export declare function getReadmeTemplate(projectName: string, options?: TemplateOptions): string;
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
|
|
1
|
+
// Options parameter added for type consistency with stateful template (OAuth not supported in stateless)
|
|
2
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
3
|
+
export function getReadmeTemplate(projectName, options) {
|
|
2
4
|
return `# ${projectName}
|
|
3
5
|
|
|
4
6
|
A stateless streamable HTTP MCP (Model Context Protocol) server.
|