@agentailor/create-mcp-server 0.1.0 → 0.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.
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
- Create a new MCP (Model Context Protocol) server project.
3
+ Scaffold production-ready MCP servers in seconds.
4
4
 
5
- ## Usage
5
+ ## Quick Start
6
6
 
7
7
  ```bash
8
8
  npx @agentailor/create-mcp-server
9
9
  ```
10
10
 
11
- This will prompt you for a project name and create a new directory with a README.md file.
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
- ## License
55
+ ## Built by Agentailor
18
56
 
19
- MIT
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, packageManager };
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
- // Write all template files
87
- await Promise.all([
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 +1,5 @@
1
- export declare function getEnvExampleTemplate(): string;
1
+ export interface TemplateOptions {
2
+ withOAuth?: boolean;
3
+ packageManager?: 'npm' | 'pnpm' | 'yarn';
4
+ }
5
+ export declare function getEnvExampleTemplate(options?: TemplateOptions): string;
@@ -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 +1,5 @@
1
- export declare function getPackageJsonTemplate(projectName: string): string;
1
+ export interface TemplateOptions {
2
+ withOAuth?: boolean;
3
+ packageManager?: 'npm' | 'pnpm' | 'yarn';
4
+ }
5
+ export declare function getPackageJsonTemplate(projectName: string, options?: TemplateOptions): string;
@@ -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.0',
19
- '@types/node': '^22.15.21',
20
- typescript: '^5.8.3',
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
+ }