@agentailor/create-mcp-server 0.6.2 → 0.7.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/README.md CHANGED
@@ -31,8 +31,8 @@ npx @agentailor/create-mcp-server --name=my-server
31
31
  | `--package-manager` | `-p` | `npm` | Package manager: npm, pnpm, yarn |
32
32
  | `--framework` | `-f` | `sdk` | Framework: sdk, fastmcp |
33
33
  | `--stdio` | — | `false` | Use stdio transport (for local clients) |
34
- | `--template` | `-t` | `stateless` | Server mode: stateless, stateful (HTTP only) |
35
- | `--oauth` | — | `false` | Enable OAuth (sdk+stateful only, incompatible with --stdio) |
34
+ | `--template` | `-t` | `stateless` | Accepted for compatibility; SDK v2 serves both modes through one per-request idiom |
35
+ | `--oauth` | — | `false` | Enable OAuth (sdk HTTP only, incompatible with --stdio) |
36
36
  | `--no-git` | — | `false` | Skip git initialization |
37
37
  | `--help` | `-h` | — | Show help |
38
38
  | `--version` | `-V` | — | Show version |
@@ -54,7 +54,6 @@ npx @agentailor/create-mcp-server \
54
54
  --name=my-auth-server \
55
55
  --package-manager=pnpm \
56
56
  --framework=sdk \
57
- --template=stateful \
58
57
  --oauth
59
58
 
60
59
  # Short flags
@@ -63,9 +62,10 @@ npx @agentailor/create-mcp-server -n my-server -p yarn -f fastmcp
63
62
 
64
63
  ## Features
65
64
 
65
+ - **MCP SDK v2** — SDK projects serve protocol revision `2026-07-28` and still accept 2025-era clients
66
66
  - **Two frameworks** — Official MCP SDK or FastMCP
67
- - **Two transport types** — HTTP (streamable) or stdio (for local cllients)
68
- - **Two HTTP server modes** — stateless or stateful with session management
67
+ - **Two transport types** — HTTP (streamable) or stdio (for local clients)
68
+ - **Stateless by design** — the SDK handler builds a fresh server per request, so HTTP servers scale without sticky sessions
69
69
  - **Optional OAuth** — OIDC-compliant authentication (SDK HTTP only) ([setup guide](docs/oauth-setup.md))
70
70
  - **Package manager choice** — npm, pnpm, or yarn
71
71
  - **TypeScript ready** — ready to customize
@@ -76,13 +76,21 @@ npx @agentailor/create-mcp-server -n my-server -p yarn -f fastmcp
76
76
 
77
77
  | Framework | Description |
78
78
  |-----------|-------------|
79
- | **Official MCP SDK** (default) | Full control with Express.js, supports OAuth |
80
- | **FastMCP** | Simpler API with less boilerplate |
79
+ | **Official MCP SDK** (default) | SDK v2, full control with Express.js, supports OAuth |
80
+ | **FastMCP** | Simpler API with less boilerplate (still on SDK v1) |
81
+
82
+ ### Official MCP SDK
83
+
84
+ SDK projects are generated against the [MCP TypeScript SDK v2](https://ts.sdk.modelcontextprotocol.io/v2/) — the split `@modelcontextprotocol/server`, `@modelcontextprotocol/express`, and `@modelcontextprotocol/node` packages, rather than the v1 `@modelcontextprotocol/sdk` monolith.
85
+
86
+ HTTP servers are built on `createMcpHandler`, which runs the server factory once per request. They serve protocol revision `2026-07-28` and also accept 2025-era clients. stdio servers use `serveStdio`, which negotiates the era per connection.
81
87
 
82
88
  ### FastMCP
83
89
 
84
90
  [FastMCP](https://github.com/punkpeye/fastmcp) is a TypeScript framework built on top of the official MCP SDK that provides a simpler, more intuitive API for building MCP servers.
85
91
 
92
+ > **Note:** FastMCP has not migrated to SDK v2 — it still depends on `@modelcontextprotocol/sdk` v1 internally, so FastMCP projects speak the 2025-era protocol. Choose the Official MCP SDK if you need protocol revision `2026-07-28`.
93
+
86
94
  ```typescript
87
95
  import { FastMCP } from "fastmcp";
88
96
  import { z } from "zod";
@@ -106,28 +114,20 @@ Learn more: [FastMCP Documentation](https://github.com/punkpeye/fastmcp)
106
114
  | Feature | HTTP (Streamable HTTP) | stdio |
107
115
  |---------|------------------------|-------|
108
116
  | Use case | Remote access, cloud deployment | Local clients (Claude Desktop) |
109
- | Protocol | HTTP/SSE | stdin/stdout |
110
- | Session management | ✓ (stateful mode) | — |
111
- | OAuth support | ✓ (SDK stateful) | — |
117
+ | Protocol | HTTP | stdin/stdout |
118
+ | OAuth support | ✓ (SDK only) | — |
112
119
  | Docker deployment | ✓ | — |
113
120
  | Port configuration | ✓ | — |
114
121
 
115
- **HTTP**: Deploy as an HTTP server accessible remotely. Choose stateless or stateful mode.
122
+ **HTTP**: Deploy as an HTTP server accessible remotely.
116
123
 
117
124
  **stdio**: Run as a local process. Communicates over stdin/stdout. Ideal for local clients. No HTTP server, no port, no Dockerfile generated.
118
125
 
119
126
  ## Server Modes (HTTP only)
120
127
 
121
- | Feature | Stateless (default) | Stateful |
122
- |---------|---------------------|----------|
123
- | Session management | — | ✓ |
124
- | SSE support | — | ✓ |
125
- | OAuth option (SDK only) | — | ✓ |
126
- | Endpoints | POST /mcp | POST, GET, DELETE /mcp |
127
-
128
- **Stateless**: Simple HTTP server — each request creates a new transport instance.
128
+ SDK v2 serves every HTTP request through a single per-request idiom: `createMcpHandler` builds a fresh `McpServer` for each call, and 2025-era clients are served through the same path. The `stateless`/`stateful` distinction that v1 required no longer changes the generated project.
129
129
 
130
- **Stateful**: Session-based server with transport reuse, Server-Sent Events for real-time updates, and optional OAuth authentication (SDK only).
130
+ `--template` is still accepted so existing invocations keep working, but both values produce the same output. If you need session-based serving with SSE resumability, the SDK still offers `NodeStreamableHTTPServerTransport` — see the [SDK v2 sessions guide](https://ts.sdk.modelcontextprotocol.io/v2/serving/sessions-state-scaling.html).
131
131
 
132
132
  ## Generated Project
133
133
 
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Command, Option, InvalidArgumentError } from 'commander';
2
2
  const NAME_REGEX = /^[a-z0-9-_]+$/i;
3
- const VERSION = '0.4.1';
3
+ const VERSION = '0.7.1';
4
4
  function validateName(value) {
5
5
  if (!NAME_REGEX.test(value)) {
6
6
  throw new InvalidArgumentError('Project name can only contain letters, numbers, hyphens, and underscores');
@@ -20,11 +20,11 @@ export function parseArguments() {
20
20
  .addOption(new Option('-f, --framework <framework>', 'Framework to use')
21
21
  .choices(['sdk', 'fastmcp'])
22
22
  .default('sdk'))
23
- .addOption(new Option('-t, --template <type>', 'Template type')
23
+ .addOption(new Option('-t, --template <type>', 'Template type (no effect on SDK projects; both generate the same server)')
24
24
  .choices(['stateless', 'stateful'])
25
25
  .default('stateless'))
26
26
  .option('--stdio', 'Use stdio transport instead of HTTP', false)
27
- .option('--oauth', 'Enable OAuth authentication (sdk+stateful only)', false)
27
+ .option('--oauth', 'Enable OAuth authentication (sdk HTTP only)', false)
28
28
  .option('--no-git', 'Skip git repository initialization');
29
29
  program.parse();
30
30
  const opts = program.opts();
@@ -52,8 +52,8 @@ export function parseArguments() {
52
52
  process.exit(1);
53
53
  }
54
54
  // Validate OAuth constraint
55
- if (opts.oauth && (opts.framework !== 'sdk' || opts.template !== 'stateful')) {
56
- console.error('\nError: --oauth is only valid with --framework=sdk and --template=stateful\n');
55
+ if (opts.oauth && opts.framework !== 'sdk') {
56
+ console.error('\nError: --oauth is only valid with --framework=sdk\n');
57
57
  process.exit(1);
58
58
  }
59
59
  return {
package/dist/cli.test.js CHANGED
@@ -94,6 +94,16 @@ describe('CLI argument parsing', () => {
94
94
  expect(result.options?.framework).toBe('sdk');
95
95
  expect(result.options?.template).toBe('stateful');
96
96
  });
97
+ // SDK v2 collapsed the stateless/stateful distinction, and OAuth is
98
+ // orthogonal to sessions, so --oauth no longer requires --template=stateful.
99
+ it('parses oauth flag correctly for sdk without --template=stateful', async () => {
100
+ process.argv = ['node', 'create-mcp-server', '--name=my-auth-server', '--oauth'];
101
+ const { parseArguments } = await import('./cli.js');
102
+ const result = parseArguments();
103
+ expect(result.options?.oauth).toBe(true);
104
+ expect(result.options?.framework).toBe('sdk');
105
+ expect(result.options?.template).toBe('stateless');
106
+ });
97
107
  it('exits with error when --name is missing in CLI mode', async () => {
98
108
  process.argv = ['node', 'create-mcp-server', '--package-manager=npm'];
99
109
  let exitCode;
@@ -108,7 +118,7 @@ describe('CLI argument parsing', () => {
108
118
  expect(consoleError).toHaveBeenCalledWith(expect.stringContaining('--name is required when using CLI arguments'));
109
119
  consoleError.mockRestore();
110
120
  });
111
- it('exits with error when --oauth used without sdk+stateful', async () => {
121
+ it('exits with error when --oauth used without sdk framework', async () => {
112
122
  process.argv = ['node', 'create-mcp-server', '--name=test', '--oauth', '--framework=fastmcp'];
113
123
  let exitCode;
114
124
  process.exit = vi.fn((code) => {
@@ -119,7 +129,7 @@ describe('CLI argument parsing', () => {
119
129
  const { parseArguments } = await import('./cli.js');
120
130
  expect(() => parseArguments()).toThrow('process.exit called');
121
131
  expect(exitCode).toBe(1);
122
- expect(consoleError).toHaveBeenCalledWith(expect.stringContaining('--oauth is only valid with --framework=sdk and --template=stateful'));
132
+ expect(consoleError).toHaveBeenCalledWith(expect.stringContaining('--oauth is only valid with --framework=sdk'));
123
133
  consoleError.mockRestore();
124
134
  });
125
135
  it('exits with error for invalid project name', async () => {
@@ -77,15 +77,21 @@ export async function runInteractiveMode() {
77
77
  initial: 0,
78
78
  }, { onCancel });
79
79
  const transport = transportResponse.transport || 'http';
80
- // Server mode selection - only for HTTP transport
80
+ // Only asked for FastMCP HTTP, where it maps to a real `stateless` config
81
+ // flag. SDK projects generate the same server either way, so asking would be
82
+ // a meaningless choice.
81
83
  let templateType = 'stateless';
82
- if (transport === 'http') {
84
+ if (transport === 'http' && framework === 'fastmcp') {
83
85
  const templateTypeResponse = await prompts({
84
86
  type: 'select',
85
87
  name: 'templateType',
86
88
  message: 'Server mode:',
87
89
  choices: [
88
- { title: 'Stateless', value: 'stateless', description: 'Simple HTTP server' },
90
+ {
91
+ title: 'Stateless',
92
+ value: 'stateless',
93
+ description: 'No session state between requests',
94
+ },
89
95
  {
90
96
  title: 'Stateful',
91
97
  value: 'stateful',
@@ -96,9 +102,9 @@ export async function runInteractiveMode() {
96
102
  }, { onCancel });
97
103
  templateType = templateTypeResponse.templateType || 'stateless';
98
104
  }
99
- // OAuth prompt - only for SDK stateful HTTP template
105
+ // OAuth prompt - available for any SDK HTTP project
100
106
  let withOAuth = false;
101
- if (transport === 'http' && framework === 'sdk' && templateType === 'stateful') {
107
+ if (transport === 'http' && framework === 'sdk') {
102
108
  const oauthResponse = await prompts({
103
109
  type: 'confirm',
104
110
  name: 'withOAuth',
@@ -6,22 +6,17 @@ import { getTsconfigTemplate } from './templates/common/tsconfig.json.js';
6
6
  import { getGitignoreTemplate } from './templates/common/gitignore.js';
7
7
  import { getEnvExampleTemplate } from './templates/common/env.example.js';
8
8
  import { getServerTemplate as getSdkStatelessServerTemplate, getIndexTemplate as getSdkStatelessIndexTemplate, getReadmeTemplate as getSdkStatelessReadmeTemplate, } from './templates/sdk/stateless/index.js';
9
- import { getServerTemplate as getSdkStatefulServerTemplate, getIndexTemplate as getSdkStatefulIndexTemplate, getReadmeTemplate as getSdkStatefulReadmeTemplate, getAuthTemplate as getSdkAuthTemplate, } from './templates/sdk/stateful/index.js';
9
+ import { getAuthTemplate as getSdkAuthTemplate } from './templates/sdk/stateful/index.js';
10
10
  import { getServerTemplate as getFastMCPServerTemplate, getIndexTemplate as getFastMCPIndexTemplate, getReadmeTemplate as getFastMCPReadmeTemplate, } from './templates/fastmcp/index.js';
11
11
  import { getServerTemplate as getSdkStdioServerTemplate, getIndexTemplate as getSdkStdioIndexTemplate, getReadmeTemplate as getSdkStdioReadmeTemplate, } from './templates/sdk/stdio/index.js';
12
12
  import { getDockerfileTemplate, getDockerignoreTemplate } from './templates/deployment/index.js';
13
- const sdkTemplateFunctions = {
14
- stateless: {
15
- getServerTemplate: getSdkStatelessServerTemplate,
16
- getIndexTemplate: getSdkStatelessIndexTemplate,
17
- getReadmeTemplate: getSdkStatelessReadmeTemplate,
18
- },
19
- stateful: {
20
- getServerTemplate: getSdkStatefulServerTemplate,
21
- getIndexTemplate: getSdkStatefulIndexTemplate,
22
- getReadmeTemplate: getSdkStatefulReadmeTemplate,
23
- getAuthTemplate: getSdkAuthTemplate,
24
- },
13
+ // Auth is keyed off `withOAuth`, never off the template type - see
14
+ // "Why stateless and stateful are identical" in CLAUDE.md.
15
+ const sdkHttpTemplateFunctions = {
16
+ getServerTemplate: getSdkStatelessServerTemplate,
17
+ getIndexTemplate: getSdkStatelessIndexTemplate,
18
+ getReadmeTemplate: getSdkStatelessReadmeTemplate,
19
+ getAuthTemplate: getSdkAuthTemplate,
25
20
  };
26
21
  const fastmcpTemplateFunctions = {
27
22
  getServerTemplate: getFastMCPServerTemplate,
@@ -57,11 +52,9 @@ export async function generateProject(config) {
57
52
  filesToWrite.push(writeFile(join(srcPath, 'server.ts'), getSdkStdioServerTemplate(projectName)), writeFile(join(srcPath, 'index.ts'), getSdkStdioIndexTemplate(templateOptions)), writeFile(join(projectPath, 'README.md'), getSdkStdioReadmeTemplate(projectName, templateOptions)));
58
53
  }
59
54
  else {
60
- // SDK HTTP templates (stateless or stateful)
61
- const templates = sdkTemplateFunctions[templateType];
55
+ const templates = sdkHttpTemplateFunctions;
62
56
  filesToWrite.push(writeFile(join(srcPath, 'server.ts'), templates.getServerTemplate(projectName)), writeFile(join(srcPath, 'index.ts'), templates.getIndexTemplate(templateOptions)), writeFile(join(projectPath, 'README.md'), templates.getReadmeTemplate(projectName, templateOptions)));
63
- // Conditionally add auth.ts for OAuth-enabled stateful template
64
- if (withOAuth && templates.getAuthTemplate) {
57
+ if (withOAuth) {
65
58
  filesToWrite.push(writeFile(join(srcPath, 'auth.ts'), templates.getAuthTemplate()));
66
59
  }
67
60
  }
@@ -6,13 +6,14 @@ export function getPackageJsonTemplate(projectName, options) {
6
6
  let devDependencies;
7
7
  const commonDevDependencies = {
8
8
  typescript: '^6.0.3',
9
- '@modelcontextprotocol/inspector': '^0.22.0',
9
+ '@modelcontextprotocol/inspector': '^2.0.0',
10
10
  '@types/node': '^26.0.0',
11
11
  };
12
12
  const zodDependency = { zod: '^4.4.3' };
13
13
  const dotEnvDependency = { dotenv: '^17.4.2' };
14
14
  if (framework === 'fastmcp') {
15
- // FastMCP dependencies - simpler setup
15
+ // FastMCP pulls in @modelcontextprotocol/sdk v1 itself, so this branch
16
+ // stays on v1 and must not gain the v2 packages.
16
17
  dependencies = {
17
18
  fastmcp: '^4.3.2',
18
19
  ...zodDependency,
@@ -23,9 +24,9 @@ export function getPackageJsonTemplate(projectName, options) {
23
24
  };
24
25
  }
25
26
  else if (transport === 'stdio') {
26
- // Official SDK stdio - no express needed
27
+ // Official SDK v2 stdio - no express needed
27
28
  dependencies = {
28
- '@modelcontextprotocol/sdk': '^1.29.0',
29
+ '@modelcontextprotocol/server': '^2.0.0',
29
30
  ...zodDependency,
30
31
  ...dotEnvDependency,
31
32
  };
@@ -34,10 +35,14 @@ export function getPackageJsonTemplate(projectName, options) {
34
35
  };
35
36
  }
36
37
  else {
37
- // Official SDK HTTP dependencies
38
+ // hono is a peer dependency of @modelcontextprotocol/node, so the generated
39
+ // project must declare it even though no template code imports it.
38
40
  dependencies = {
39
- '@modelcontextprotocol/sdk': '^1.29.0',
41
+ '@modelcontextprotocol/server': '^2.0.0',
42
+ '@modelcontextprotocol/express': '^2.0.0',
43
+ '@modelcontextprotocol/node': '^2.0.0',
40
44
  express: '^5.2.1',
45
+ hono: '^4.11.5',
41
46
  ...zodDependency,
42
47
  ...dotEnvDependency,
43
48
  };
@@ -70,7 +75,9 @@ export function getPackageJsonTemplate(projectName, options) {
70
75
  dependencies,
71
76
  devDependencies,
72
77
  engines: {
73
- node: '>=20',
78
+ // Floor set by @modelcontextprotocol/inspector, which requires >=22.19.0.
79
+ // The SDK v2 packages themselves only need >=20.
80
+ node: '>=22.19.0',
74
81
  },
75
82
  };
76
83
  return JSON.stringify(packageJson, null, 2) + '\n';
@@ -11,11 +11,20 @@ describe('common templates', () => {
11
11
  const pkg = JSON.parse(template);
12
12
  expect(pkg.name).toBe(projectName);
13
13
  });
14
- it('should use SDK package by default', () => {
14
+ it('should use SDK v2 packages by default', () => {
15
15
  const template = getPackageJsonTemplate(projectName);
16
16
  const pkg = JSON.parse(template);
17
- expect(pkg.dependencies['@modelcontextprotocol/sdk']).toBeDefined();
17
+ expect(pkg.dependencies['@modelcontextprotocol/server']).toBeDefined();
18
+ expect(pkg.dependencies['@modelcontextprotocol/express']).toBeDefined();
19
+ expect(pkg.dependencies['@modelcontextprotocol/node']).toBeDefined();
18
20
  expect(pkg.dependencies['express']).toBeDefined();
21
+ // v1 monolith must not be pulled into SDK projects
22
+ expect(pkg.dependencies['@modelcontextprotocol/sdk']).toBeUndefined();
23
+ });
24
+ it('should include hono for SDK HTTP (peer dependency of @modelcontextprotocol/node)', () => {
25
+ const template = getPackageJsonTemplate(projectName);
26
+ const pkg = JSON.parse(template);
27
+ expect(pkg.dependencies['hono']).toBeDefined();
19
28
  });
20
29
  it('should include dotenv for SDK', () => {
21
30
  const template = getPackageJsonTemplate(projectName);
@@ -26,9 +35,17 @@ describe('common templates', () => {
26
35
  const template = getPackageJsonTemplate(projectName, { framework: 'fastmcp' });
27
36
  const pkg = JSON.parse(template);
28
37
  expect(pkg.dependencies['fastmcp']).toBeDefined();
38
+ // FastMCP depends on the v1 SDK transitively, never directly
29
39
  expect(pkg.dependencies['@modelcontextprotocol/sdk']).toBeUndefined();
30
40
  expect(pkg.dependencies['express']).toBeUndefined();
31
41
  });
42
+ it('should NOT pull SDK v2 packages into FastMCP projects', () => {
43
+ const template = getPackageJsonTemplate(projectName, { framework: 'fastmcp' });
44
+ const pkg = JSON.parse(template);
45
+ expect(pkg.dependencies['@modelcontextprotocol/server']).toBeUndefined();
46
+ expect(pkg.dependencies['@modelcontextprotocol/express']).toBeUndefined();
47
+ expect(pkg.dependencies['@modelcontextprotocol/node']).toBeUndefined();
48
+ });
32
49
  it('should include dotenv for FastMCP', () => {
33
50
  const template = getPackageJsonTemplate(projectName, { framework: 'fastmcp' });
34
51
  const pkg = JSON.parse(template);
@@ -57,7 +74,10 @@ describe('common templates', () => {
57
74
  const pkg = JSON.parse(template);
58
75
  expect(pkg.dependencies['express']).toBeUndefined();
59
76
  expect(pkg.devDependencies['@types/express']).toBeUndefined();
60
- expect(pkg.dependencies['@modelcontextprotocol/sdk']).toBeDefined();
77
+ expect(pkg.dependencies['hono']).toBeUndefined();
78
+ expect(pkg.dependencies['@modelcontextprotocol/server']).toBeDefined();
79
+ expect(pkg.dependencies['@modelcontextprotocol/express']).toBeUndefined();
80
+ expect(pkg.dependencies['@modelcontextprotocol/node']).toBeUndefined();
61
81
  });
62
82
  it('should use inspect:tools, inspect:prompts, inspect:resources scripts for stdio transport', () => {
63
83
  const template = getPackageJsonTemplate(projectName, {
@@ -75,6 +95,18 @@ describe('common templates', () => {
75
95
  const pkg = JSON.parse(template);
76
96
  expect(pkg.scripts.inspect).toContain('http://localhost:3000/mcp');
77
97
  });
98
+ // The inspector devDependency requires >=22.19.0; a lower floor makes npm
99
+ // emit an EBADENGINE warning on install.
100
+ it('should declare a node engine satisfying the inspector requirement', () => {
101
+ for (const options of [
102
+ { framework: 'sdk', transport: 'http' },
103
+ { framework: 'sdk', transport: 'stdio' },
104
+ { framework: 'fastmcp' },
105
+ ]) {
106
+ const pkg = JSON.parse(getPackageJsonTemplate(projectName, options));
107
+ expect(pkg.engines.node).toBe('>=22.19.0');
108
+ }
109
+ });
78
110
  it('should include required scripts', () => {
79
111
  const template = getPackageJsonTemplate(projectName);
80
112
  const pkg = JSON.parse(template);
@@ -25,7 +25,7 @@ export function getDockerfileTemplate(options) {
25
25
  const config = packageManagerConfigs[packageManager];
26
26
  const setupStep = config.setup ? `\n${config.setup}\n` : '';
27
27
  return `# Multi-stage build for production
28
- FROM node:20-alpine AS builder
28
+ FROM node:22-alpine AS builder
29
29
 
30
30
  WORKDIR /app
31
31
  ${setupStep}
@@ -42,7 +42,7 @@ COPY . .
42
42
  RUN ${config.build}
43
43
 
44
44
  # Production stage
45
- FROM node:20-alpine AS production
45
+ FROM node:22-alpine AS production
46
46
 
47
47
  WORKDIR /app
48
48
  ${setupStep}
@@ -8,9 +8,9 @@ describe('deployment templates', () => {
8
8
  expect(template).toContain('AS builder');
9
9
  expect(template).toContain('AS production');
10
10
  });
11
- it('should use Node 20 Alpine', () => {
11
+ it('should use Node 22 Alpine', () => {
12
12
  const template = getDockerfileTemplate();
13
- expect(template).toContain('FROM node:20-alpine');
13
+ expect(template).toContain('FROM node:22-alpine');
14
14
  });
15
15
  it('should copy dist folder from builder', () => {
16
16
  const template = getDockerfileTemplate();
@@ -4,9 +4,10 @@ import { createRemoteJWKSet, jwtVerify, type JWTPayload, type JWTVerifyGetKey }
4
4
  import {
5
5
  mcpAuthMetadataRouter,
6
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';
7
+ requireBearerAuth,
8
+ } from '@modelcontextprotocol/express';
9
+ import { OAuthError, OAuthErrorCode } from '@modelcontextprotocol/server';
10
+ import type { OAuthMetadata, OAuthTokenVerifier } from '@modelcontextprotocol/server';
10
11
  import type { Express, RequestHandler } from 'express';
11
12
 
12
13
  // OAuth configuration from environment variables
@@ -45,8 +46,10 @@ interface OIDCDiscoveryDocument {
45
46
  }
46
47
 
47
48
  // Token verifier using JWKS/JWT validation
48
- const tokenVerifier = {
49
+ const tokenVerifier: OAuthTokenVerifier = {
49
50
  verifyAccessToken: async (token: string) => {
51
+ // A plain Error here is intentional: an uninitialized JWKS is a server
52
+ // misconfiguration, not a bad token, so it should surface as 500 server_error.
50
53
  if (!JWKS) {
51
54
  throw new Error('JWKS not initialized. Call validateOAuthConfig() first.');
52
55
  }
@@ -55,8 +58,9 @@ const tokenVerifier = {
55
58
  // Check if the token looks like a JWT (three base64url-encoded parts separated by dots)
56
59
  const parts = token.split('.');
57
60
  if (parts.length !== 3) {
58
- throw new Error(
59
- 'Token is not a valid JWT format (expected 3 parts separated by dots). '
61
+ throw new OAuthError(
62
+ OAuthErrorCode.InvalidToken,
63
+ 'Token is not a valid JWT format (expected 3 parts separated by dots).'
60
64
  );
61
65
  }
62
66
 
@@ -83,7 +87,14 @@ const tokenVerifier = {
83
87
  if (error instanceof Error) {
84
88
  console.error('[auth] JWT verification failed:', error.message);
85
89
  }
86
- throw error;
90
+ if (error instanceof OAuthError) {
91
+ throw error;
92
+ }
93
+ // Convert jose failures (bad signature, expired, wrong issuer/audience) into
94
+ // an OAuthError so requireBearerAuth answers 401 with a WWW-Authenticate
95
+ // challenge instead of 500. The specific reason stays in the server log
96
+ // rather than the response body, so callers learn nothing beyond "invalid".
97
+ throw new OAuthError(OAuthErrorCode.InvalidToken, 'Token verification failed');
87
98
  }
88
99
  },
89
100
  };
@@ -104,7 +115,9 @@ export function setupAuthMetadataRouter(app: Express): void {
104
115
  );
105
116
  }
106
117
 
107
- // Export auth middleware for protecting routes
118
+ // Export auth middleware for protecting routes.
119
+ // requireBearerAuth attaches the validated AuthInfo to \`req.auth\`, which
120
+ // toNodeHandler forwards to MCP handlers as \`ctx.http.authInfo\`.
108
121
  export const authMiddleware: RequestHandler = requireBearerAuth({
109
122
  verifier: tokenVerifier,
110
123
  requiredScopes: [],
@@ -17,11 +17,15 @@ describe('auth template', () => {
17
17
  expect(template).toContain('createRemoteJWKSet');
18
18
  expect(template).toContain('jwtVerify');
19
19
  });
20
- it('should use SDK auth imports', () => {
20
+ it('should use SDK v2 auth imports', () => {
21
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'");
22
+ expect(template).toContain("from '@modelcontextprotocol/express'");
23
+ expect(template).toContain("from '@modelcontextprotocol/server'");
24
+ expect(template).not.toContain('@modelcontextprotocol/sdk');
25
+ });
26
+ it('should type the verifier as OAuthTokenVerifier', () => {
27
+ const template = getAuthTemplate();
28
+ expect(template).toContain('OAuthTokenVerifier');
25
29
  });
26
30
  it('should export setupAuthMetadataRouter function', () => {
27
31
  const template = getAuthTemplate();
@@ -96,5 +100,34 @@ describe('auth template', () => {
96
100
  const template = getAuthTemplate();
97
101
  expect(template).toContain("jwtPayload.scope.split(' ')");
98
102
  });
103
+ it('should import OAuthError and OAuthErrorCode as values, not types', () => {
104
+ const template = getAuthTemplate();
105
+ expect(template).toContain("import { OAuthError, OAuthErrorCode } from '@modelcontextprotocol/server'");
106
+ });
107
+ it('should reject malformed JWTs with an OAuthError so the response is 401', () => {
108
+ const template = getAuthTemplate();
109
+ expect(template).toContain('throw new OAuthError(\n OAuthErrorCode.InvalidToken,');
110
+ expect(template).not.toContain("throw new Error(\n 'Token is not a valid JWT format");
111
+ });
112
+ it('should convert jose verification failures into an OAuthError', () => {
113
+ const template = getAuthTemplate();
114
+ expect(template).toContain("throw new OAuthError(OAuthErrorCode.InvalidToken, 'Token verification failed')");
115
+ // The bare re-throw produced a 500 server_error with no WWW-Authenticate header.
116
+ expect(template).not.toMatch(/JWT verification failed:', error\.message\);\s*}\s*throw error;/);
117
+ });
118
+ it('should re-throw an existing OAuthError unchanged', () => {
119
+ const template = getAuthTemplate();
120
+ expect(template).toContain('if (error instanceof OAuthError) {');
121
+ });
122
+ it('should not leak the underlying failure reason into the error response', () => {
123
+ const template = getAuthTemplate();
124
+ // The jose message is logged server-side but must not reach error_description.
125
+ expect(template).toContain("console.error('[auth] JWT verification failed:', error.message)");
126
+ expect(template).not.toContain("error instanceof Error ? error.message : 'Token verification failed'");
127
+ });
128
+ it('should keep an uninitialized JWKS as a plain Error (server misconfiguration)', () => {
129
+ const template = getAuthTemplate();
130
+ expect(template).toContain("throw new Error('JWKS not initialized. Call validateOAuthConfig() first.')");
131
+ });
99
132
  });
100
133
  });
@@ -1,6 +1,5 @@
1
1
  export type { SdkTemplateOptions as TemplateOptions } from '../../common/types.js';
2
- import type { SdkTemplateOptions } from '../../common/types.js';
3
- export declare function getIndexTemplate(options?: SdkTemplateOptions): string;
2
+ export { getIndexTemplate } from '../stateless/index.js';
4
3
  export { getServerTemplate } from './server.js';
5
4
  export { getReadmeTemplate } from './readme.js';
6
5
  export { getAuthTemplate } from './auth.js';