@berthojoris/mcp-mysql-server 1.44.0 → 1.45.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +39 -0
- package/DOCUMENTATIONS.md +674 -524
- package/README.md +468 -382
- package/bin/mcp-mysql.js +49 -3
- package/dist/config/runtimeConfig.d.ts +50 -0
- package/dist/config/runtimeConfig.js +173 -0
- package/dist/db/connection.d.ts +32 -0
- package/dist/db/connection.js +169 -8
- package/dist/mcp-server.js +219 -74
- package/dist/security/grantInspector.d.ts +5 -0
- package/dist/security/grantInspector.js +32 -0
- package/dist/server/auditLogger.d.ts +24 -0
- package/dist/server/auditLogger.js +60 -0
- package/dist/server/auth.d.ts +56 -0
- package/dist/server/auth.js +274 -0
- package/dist/server/httpServer.d.ts +22 -0
- package/dist/server/httpServer.js +320 -0
- package/dist/server/rateLimiter.d.ts +15 -0
- package/dist/server/rateLimiter.js +41 -0
- package/dist/server/requestContext.d.ts +12 -0
- package/dist/server/requestContext.js +9 -0
- package/dist/tools/toolAnnotations.d.ts +4 -0
- package/dist/tools/toolAnnotations.js +73 -0
- package/manifest.json +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.protectedResourceMetadataUrl = exports.protectedResourceMetadata = exports.createAuthenticator = exports.OAuthAuthenticator = exports.TokenAuthenticator = exports.NoAuthenticator = exports.AuthError = void 0;
|
|
7
|
+
const crypto_1 = __importDefault(require("crypto"));
|
|
8
|
+
/** Authentication failure mapped to an HTTP status and OAuth error code. */
|
|
9
|
+
class AuthError extends Error {
|
|
10
|
+
constructor(message, status, oauthError) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.status = status;
|
|
13
|
+
this.oauthError = oauthError;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
exports.AuthError = AuthError;
|
|
17
|
+
const extractBearer = (authorization) => {
|
|
18
|
+
if (!authorization) {
|
|
19
|
+
throw new AuthError("Missing Authorization header", 401, "invalid_request");
|
|
20
|
+
}
|
|
21
|
+
const match = /^Bearer\s+(\S+)\s*$/i.exec(authorization);
|
|
22
|
+
if (!match) {
|
|
23
|
+
throw new AuthError("Authorization header must use the Bearer scheme", 401, "invalid_request");
|
|
24
|
+
}
|
|
25
|
+
return match[1];
|
|
26
|
+
};
|
|
27
|
+
const sha256 = (value) => crypto_1.default.createHash("sha256").update(value).digest();
|
|
28
|
+
class NoAuthenticator {
|
|
29
|
+
async authenticate() {
|
|
30
|
+
return { token: "", clientId: "anonymous", scopes: [] };
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
exports.NoAuthenticator = NoAuthenticator;
|
|
34
|
+
/** Static bearer tokens, compared by SHA-256 digest in constant time. */
|
|
35
|
+
class TokenAuthenticator {
|
|
36
|
+
constructor(tokens) {
|
|
37
|
+
this.digests = tokens.map(sha256);
|
|
38
|
+
}
|
|
39
|
+
async authenticate(authorization) {
|
|
40
|
+
const token = extractBearer(authorization);
|
|
41
|
+
const digest = sha256(token);
|
|
42
|
+
// Compare against every token so timing does not reveal which one matched
|
|
43
|
+
let matched = false;
|
|
44
|
+
for (const candidate of this.digests) {
|
|
45
|
+
if (crypto_1.default.timingSafeEqual(candidate, digest))
|
|
46
|
+
matched = true;
|
|
47
|
+
}
|
|
48
|
+
if (!matched) {
|
|
49
|
+
throw new AuthError("Invalid bearer token", 401, "invalid_token");
|
|
50
|
+
}
|
|
51
|
+
return {
|
|
52
|
+
token,
|
|
53
|
+
clientId: `token-${digest.toString("hex").slice(0, 12)}`,
|
|
54
|
+
scopes: [],
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
exports.TokenAuthenticator = TokenAuthenticator;
|
|
59
|
+
const defaultFetcher = async (url) => {
|
|
60
|
+
const response = await fetch(url, { headers: { Accept: "application/json" } });
|
|
61
|
+
if (!response.ok) {
|
|
62
|
+
throw new Error(`GET ${url} returned ${response.status}`);
|
|
63
|
+
}
|
|
64
|
+
return response.json();
|
|
65
|
+
};
|
|
66
|
+
const ALGORITHMS = {
|
|
67
|
+
RS256: { kty: "RSA", hash: "sha256" },
|
|
68
|
+
RS384: { kty: "RSA", hash: "sha384" },
|
|
69
|
+
RS512: { kty: "RSA", hash: "sha512" },
|
|
70
|
+
PS256: { kty: "RSA", hash: "sha256", pss: true },
|
|
71
|
+
PS384: { kty: "RSA", hash: "sha384", pss: true },
|
|
72
|
+
PS512: { kty: "RSA", hash: "sha512", pss: true },
|
|
73
|
+
ES256: { kty: "EC", hash: "sha256", curve: "P-256", ecdsa: true },
|
|
74
|
+
ES384: { kty: "EC", hash: "sha384", curve: "P-384", ecdsa: true },
|
|
75
|
+
ES512: { kty: "EC", hash: "sha512", curve: "P-521", ecdsa: true },
|
|
76
|
+
EdDSA: { kty: "OKP", hash: null },
|
|
77
|
+
};
|
|
78
|
+
const CLOCK_SKEW_SECONDS = 60;
|
|
79
|
+
const JWKS_TTL_MS = 10 * 60 * 1000;
|
|
80
|
+
const JWKS_MIN_REFRESH_MS = 30 * 1000;
|
|
81
|
+
const decodeSegment = (segment) => {
|
|
82
|
+
try {
|
|
83
|
+
return JSON.parse(Buffer.from(segment, "base64url").toString("utf8"));
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
throw new AuthError("Malformed access token", 401, "invalid_token");
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
const normalizeIssuer = (issuer) => issuer.replace(/\/+$/, "");
|
|
90
|
+
/**
|
|
91
|
+
* OAuth 2.1 resource server: validates JWT access tokens issued by an external
|
|
92
|
+
* authorization server against its JWKS. Tokens are never issued here.
|
|
93
|
+
*/
|
|
94
|
+
class OAuthAuthenticator {
|
|
95
|
+
constructor(config, fetcher = defaultFetcher, now = Date.now) {
|
|
96
|
+
this.config = config;
|
|
97
|
+
this.fetcher = fetcher;
|
|
98
|
+
this.now = now;
|
|
99
|
+
this.keys = [];
|
|
100
|
+
this.keysFetchedAt = Number.NEGATIVE_INFINITY;
|
|
101
|
+
this.lastAttemptAt = Number.NEGATIVE_INFINITY;
|
|
102
|
+
this.jwksUri = config.jwksUri;
|
|
103
|
+
}
|
|
104
|
+
async authenticate(authorization) {
|
|
105
|
+
const token = extractBearer(authorization);
|
|
106
|
+
const parts = token.split(".");
|
|
107
|
+
if (parts.length !== 3) {
|
|
108
|
+
throw new AuthError("Access token is not a JWT", 401, "invalid_token");
|
|
109
|
+
}
|
|
110
|
+
const [headerSegment, payloadSegment, signatureSegment] = parts;
|
|
111
|
+
const header = decodeSegment(headerSegment);
|
|
112
|
+
const payload = decodeSegment(payloadSegment);
|
|
113
|
+
const algorithm = ALGORITHMS[header?.alg];
|
|
114
|
+
if (!algorithm) {
|
|
115
|
+
throw new AuthError(`Unsupported token algorithm: ${header?.alg}`, 401, "invalid_token");
|
|
116
|
+
}
|
|
117
|
+
const jwk = await this.findKey(header.kid, header.alg, algorithm.kty);
|
|
118
|
+
const signature = Buffer.from(signatureSegment, "base64url");
|
|
119
|
+
const signedData = Buffer.from(`${headerSegment}.${payloadSegment}`);
|
|
120
|
+
if (!this.verifySignature(jwk, algorithm, signedData, signature)) {
|
|
121
|
+
throw new AuthError("Invalid token signature", 401, "invalid_token");
|
|
122
|
+
}
|
|
123
|
+
this.validateClaims(payload);
|
|
124
|
+
const scopes = this.extractScopes(payload);
|
|
125
|
+
const missing = this.config.requiredScopes.filter((scope) => !scopes.includes(scope));
|
|
126
|
+
if (missing.length > 0) {
|
|
127
|
+
throw new AuthError(`Token is missing required scope(s): ${missing.join(", ")}`, 403, "insufficient_scope");
|
|
128
|
+
}
|
|
129
|
+
const clientId = String(payload.client_id || payload.azp || payload.sub || "unknown");
|
|
130
|
+
return {
|
|
131
|
+
token,
|
|
132
|
+
clientId,
|
|
133
|
+
scopes,
|
|
134
|
+
expiresAt: typeof payload.exp === "number" ? payload.exp : undefined,
|
|
135
|
+
extra: { subject: payload.sub },
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
verifySignature(jwk, algorithm, data, signature) {
|
|
139
|
+
try {
|
|
140
|
+
const key = crypto_1.default.createPublicKey({ key: jwk, format: "jwk" });
|
|
141
|
+
if (algorithm.pss) {
|
|
142
|
+
return crypto_1.default.verify(algorithm.hash, data, { key, padding: crypto_1.default.constants.RSA_PKCS1_PSS_PADDING, saltLength: crypto_1.default.constants.RSA_PSS_SALTLEN_DIGEST }, signature);
|
|
143
|
+
}
|
|
144
|
+
if (algorithm.ecdsa) {
|
|
145
|
+
return crypto_1.default.verify(algorithm.hash, data, { key, dsaEncoding: "ieee-p1363" }, signature);
|
|
146
|
+
}
|
|
147
|
+
return crypto_1.default.verify(algorithm.hash, data, key, signature);
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
return false;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
validateClaims(payload) {
|
|
154
|
+
if (!payload || typeof payload !== "object") {
|
|
155
|
+
throw new AuthError("Malformed token payload", 401, "invalid_token");
|
|
156
|
+
}
|
|
157
|
+
const nowSeconds = Math.floor(this.now() / 1000);
|
|
158
|
+
if (typeof payload.iss !== "string" || normalizeIssuer(payload.iss) !== normalizeIssuer(this.config.issuer)) {
|
|
159
|
+
throw new AuthError("Token issuer does not match", 401, "invalid_token");
|
|
160
|
+
}
|
|
161
|
+
const audiences = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
|
|
162
|
+
if (!this.config.audience || !audiences.includes(this.config.audience)) {
|
|
163
|
+
throw new AuthError("Token audience does not match this server", 401, "invalid_token");
|
|
164
|
+
}
|
|
165
|
+
if (typeof payload.exp !== "number" || payload.exp + CLOCK_SKEW_SECONDS < nowSeconds) {
|
|
166
|
+
throw new AuthError("Token is expired", 401, "invalid_token");
|
|
167
|
+
}
|
|
168
|
+
if (typeof payload.nbf === "number" && payload.nbf - CLOCK_SKEW_SECONDS > nowSeconds) {
|
|
169
|
+
throw new AuthError("Token is not valid yet", 401, "invalid_token");
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
extractScopes(payload) {
|
|
173
|
+
if (typeof payload.scope === "string")
|
|
174
|
+
return payload.scope.split(" ").filter(Boolean);
|
|
175
|
+
if (Array.isArray(payload.scp))
|
|
176
|
+
return payload.scp.map(String);
|
|
177
|
+
if (typeof payload.scp === "string")
|
|
178
|
+
return payload.scp.split(" ").filter(Boolean);
|
|
179
|
+
return [];
|
|
180
|
+
}
|
|
181
|
+
async findKey(kid, alg, kty) {
|
|
182
|
+
const canRetry = () => this.now() - this.lastAttemptAt > JWKS_MIN_REFRESH_MS;
|
|
183
|
+
if (this.now() - this.keysFetchedAt > JWKS_TTL_MS && canRetry()) {
|
|
184
|
+
await this.refreshKeys();
|
|
185
|
+
}
|
|
186
|
+
let key = this.selectKey(kid, alg, kty);
|
|
187
|
+
// Unknown kid usually means the authorization server rotated its keys
|
|
188
|
+
if (!key && canRetry()) {
|
|
189
|
+
await this.refreshKeys();
|
|
190
|
+
key = this.selectKey(kid, alg, kty);
|
|
191
|
+
}
|
|
192
|
+
if (!key) {
|
|
193
|
+
throw new AuthError("No matching signing key for token", 401, "invalid_token");
|
|
194
|
+
}
|
|
195
|
+
return key;
|
|
196
|
+
}
|
|
197
|
+
selectKey(kid, alg, kty) {
|
|
198
|
+
const candidates = this.keys.filter((key) => key.kty === kty &&
|
|
199
|
+
(!key.use || key.use === "sig") &&
|
|
200
|
+
(!key.alg || key.alg === alg) &&
|
|
201
|
+
(!ALGORITHMS[alg].curve || key.crv === ALGORITHMS[alg].curve));
|
|
202
|
+
if (kid)
|
|
203
|
+
return candidates.find((key) => key.kid === kid);
|
|
204
|
+
return candidates.length === 1 ? candidates[0] : undefined;
|
|
205
|
+
}
|
|
206
|
+
refreshKeys() {
|
|
207
|
+
if (!this.refreshing) {
|
|
208
|
+
this.refreshing = (async () => {
|
|
209
|
+
this.lastAttemptAt = this.now();
|
|
210
|
+
try {
|
|
211
|
+
const uri = await this.resolveJwksUri();
|
|
212
|
+
const jwks = await this.fetcher(uri);
|
|
213
|
+
if (!jwks || !Array.isArray(jwks.keys)) {
|
|
214
|
+
throw new Error(`JWKS at ${uri} has no "keys" array`);
|
|
215
|
+
}
|
|
216
|
+
this.keys = jwks.keys;
|
|
217
|
+
this.keysFetchedAt = this.now();
|
|
218
|
+
}
|
|
219
|
+
catch (error) {
|
|
220
|
+
// Keep any previously fetched keys; lastAttemptAt throttles the next retry
|
|
221
|
+
console.error(`OAuth: failed to load signing keys: ${error.message}`);
|
|
222
|
+
}
|
|
223
|
+
finally {
|
|
224
|
+
this.refreshing = undefined;
|
|
225
|
+
}
|
|
226
|
+
})();
|
|
227
|
+
}
|
|
228
|
+
return this.refreshing;
|
|
229
|
+
}
|
|
230
|
+
async resolveJwksUri() {
|
|
231
|
+
if (this.jwksUri)
|
|
232
|
+
return this.jwksUri;
|
|
233
|
+
const issuer = normalizeIssuer(this.config.issuer);
|
|
234
|
+
const issuerUrl = new URL(issuer);
|
|
235
|
+
// OpenID Connect discovery, then RFC 8414 (path inserted after the well-known prefix)
|
|
236
|
+
const candidates = [
|
|
237
|
+
`${issuer}/.well-known/openid-configuration`,
|
|
238
|
+
`${issuerUrl.origin}/.well-known/oauth-authorization-server${issuerUrl.pathname === "/" ? "" : issuerUrl.pathname}`,
|
|
239
|
+
];
|
|
240
|
+
for (const url of candidates) {
|
|
241
|
+
try {
|
|
242
|
+
const metadata = await this.fetcher(url);
|
|
243
|
+
if (metadata && typeof metadata.jwks_uri === "string") {
|
|
244
|
+
this.jwksUri = metadata.jwks_uri;
|
|
245
|
+
return metadata.jwks_uri;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
catch {
|
|
249
|
+
// try the next discovery document
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
throw new Error(`Could not discover jwks_uri for issuer ${this.config.issuer}; set MCP_OAUTH_JWKS_URI`);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
exports.OAuthAuthenticator = OAuthAuthenticator;
|
|
256
|
+
const createAuthenticator = (http) => {
|
|
257
|
+
if (http.auth === "token")
|
|
258
|
+
return new TokenAuthenticator(http.tokens);
|
|
259
|
+
if (http.auth === "oauth" && http.oauth)
|
|
260
|
+
return new OAuthAuthenticator(http.oauth);
|
|
261
|
+
return new NoAuthenticator();
|
|
262
|
+
};
|
|
263
|
+
exports.createAuthenticator = createAuthenticator;
|
|
264
|
+
/** RFC 9728 Protected Resource Metadata for this server. */
|
|
265
|
+
const protectedResourceMetadata = (http) => ({
|
|
266
|
+
resource: http.resourceUrl,
|
|
267
|
+
authorization_servers: http.oauth ? [http.oauth.issuer] : [],
|
|
268
|
+
bearer_methods_supported: ["header"],
|
|
269
|
+
...(http.oauth && http.oauth.requiredScopes.length > 0 ? { scopes_supported: http.oauth.requiredScopes } : {}),
|
|
270
|
+
resource_name: "MySQL MCP Server",
|
|
271
|
+
});
|
|
272
|
+
exports.protectedResourceMetadata = protectedResourceMetadata;
|
|
273
|
+
const protectedResourceMetadataUrl = (http) => http.publicUrl ? `${http.publicUrl}/.well-known/oauth-protected-resource${http.path}` : undefined;
|
|
274
|
+
exports.protectedResourceMetadataUrl = protectedResourceMetadataUrl;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import http from "http";
|
|
2
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
3
|
+
import { HttpConfig } from "../config/runtimeConfig";
|
|
4
|
+
import { Authenticator } from "./auth";
|
|
5
|
+
import { AuditLogger } from "./auditLogger";
|
|
6
|
+
export interface HttpServerOptions {
|
|
7
|
+
config: HttpConfig;
|
|
8
|
+
/** Builds a fresh MCP server (with handlers) for each session */
|
|
9
|
+
createServer: () => Server;
|
|
10
|
+
auditLogger: AuditLogger;
|
|
11
|
+
/** Called once when a session ends (closed, deleted, or expired) */
|
|
12
|
+
onSessionClosed?: (sessionId: string) => void;
|
|
13
|
+
authenticator?: Authenticator;
|
|
14
|
+
}
|
|
15
|
+
export interface RunningHttpServer {
|
|
16
|
+
server: http.Server;
|
|
17
|
+
/** Address actually bound (port is resolved when 0 was requested) */
|
|
18
|
+
url: string;
|
|
19
|
+
sessionCount: () => number;
|
|
20
|
+
close: () => Promise<void>;
|
|
21
|
+
}
|
|
22
|
+
export declare const startHttpServer: (options: HttpServerOptions) => Promise<RunningHttpServer>;
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.startHttpServer = void 0;
|
|
7
|
+
const http_1 = __importDefault(require("http"));
|
|
8
|
+
const crypto_1 = require("crypto");
|
|
9
|
+
const streamableHttp_js_1 = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
|
|
10
|
+
const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
|
|
11
|
+
const runtimeConfig_1 = require("../config/runtimeConfig");
|
|
12
|
+
const auth_1 = require("./auth");
|
|
13
|
+
class RequestBodyError extends Error {
|
|
14
|
+
constructor(message, status) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.status = status;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
const sendJson = (res, status, body, headers = {}) => {
|
|
20
|
+
if (res.headersSent) {
|
|
21
|
+
res.end();
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
res.writeHead(status, { "Content-Type": "application/json", ...headers });
|
|
25
|
+
res.end(JSON.stringify(body));
|
|
26
|
+
};
|
|
27
|
+
const jsonRpcError = (code, message) => ({
|
|
28
|
+
jsonrpc: "2.0",
|
|
29
|
+
error: { code, message },
|
|
30
|
+
id: null,
|
|
31
|
+
});
|
|
32
|
+
const readJsonBody = (req, maxBytes) => new Promise((resolve, reject) => {
|
|
33
|
+
const chunks = [];
|
|
34
|
+
let size = 0;
|
|
35
|
+
let failed = false;
|
|
36
|
+
req.on("data", (chunk) => {
|
|
37
|
+
if (failed)
|
|
38
|
+
return;
|
|
39
|
+
size += chunk.length;
|
|
40
|
+
if (maxBytes > 0 && size > maxBytes) {
|
|
41
|
+
failed = true;
|
|
42
|
+
reject(new RequestBodyError(`Request body exceeds ${maxBytes} bytes`, 413));
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
chunks.push(chunk);
|
|
46
|
+
});
|
|
47
|
+
req.on("end", () => {
|
|
48
|
+
if (failed)
|
|
49
|
+
return;
|
|
50
|
+
try {
|
|
51
|
+
resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
reject(new RequestBodyError("Parse error: request body is not valid JSON", 400));
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
req.on("error", (error) => {
|
|
58
|
+
if (!failed)
|
|
59
|
+
reject(error);
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
/** Hostname from a Host header value, without the port ("[::1]:3000" -> "[::1]"). */
|
|
63
|
+
const hostnameOf = (hostHeader) => {
|
|
64
|
+
const value = hostHeader.trim().toLowerCase();
|
|
65
|
+
if (value.startsWith("[")) {
|
|
66
|
+
const end = value.indexOf("]");
|
|
67
|
+
return end === -1 ? value : value.slice(0, end + 1);
|
|
68
|
+
}
|
|
69
|
+
return value.split(":")[0];
|
|
70
|
+
};
|
|
71
|
+
const startHttpServer = async (options) => {
|
|
72
|
+
const { config, createServer, auditLogger } = options;
|
|
73
|
+
const authenticator = options.authenticator || (0, auth_1.createAuthenticator)(config);
|
|
74
|
+
const sessions = new Map();
|
|
75
|
+
const metadataPaths = new Set(["/.well-known/oauth-protected-resource", `/.well-known/oauth-protected-resource${config.path}`]);
|
|
76
|
+
const resourceMetadataUrl = (0, auth_1.protectedResourceMetadataUrl)(config);
|
|
77
|
+
const allowedOrigins = new Set(config.allowedOrigins.map((origin) => origin.replace(/\/+$/, "").toLowerCase()));
|
|
78
|
+
const clientIpOf = (req) => {
|
|
79
|
+
if (config.trustProxy) {
|
|
80
|
+
const forwarded = req.headers["x-forwarded-for"];
|
|
81
|
+
const first = (Array.isArray(forwarded) ? forwarded[0] : forwarded || "").split(",")[0].trim();
|
|
82
|
+
if (first)
|
|
83
|
+
return first;
|
|
84
|
+
}
|
|
85
|
+
return req.socket.remoteAddress || "unknown";
|
|
86
|
+
};
|
|
87
|
+
const isHostAllowed = (hostHeader) => {
|
|
88
|
+
if (config.allowedHosts.length === 0)
|
|
89
|
+
return true;
|
|
90
|
+
if (!hostHeader)
|
|
91
|
+
return false;
|
|
92
|
+
return config.allowedHosts.includes(hostnameOf(hostHeader));
|
|
93
|
+
};
|
|
94
|
+
const isOriginAllowed = (origin) => {
|
|
95
|
+
const normalized = origin.replace(/\/+$/, "").toLowerCase();
|
|
96
|
+
if (allowedOrigins.size > 0)
|
|
97
|
+
return allowedOrigins.has(normalized);
|
|
98
|
+
// Default: only local browser tools may call a loopback-bound server
|
|
99
|
+
if (!(0, runtimeConfig_1.isLoopbackHost)(config.host))
|
|
100
|
+
return false;
|
|
101
|
+
try {
|
|
102
|
+
return (0, runtimeConfig_1.isLoopbackHost)(new URL(normalized).hostname);
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
const setCorsHeaders = (res, origin) => {
|
|
109
|
+
res.setHeader("Access-Control-Allow-Origin", origin);
|
|
110
|
+
res.setHeader("Vary", "Origin");
|
|
111
|
+
res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
|
|
112
|
+
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID");
|
|
113
|
+
res.setHeader("Access-Control-Expose-Headers", "Mcp-Session-Id, WWW-Authenticate");
|
|
114
|
+
};
|
|
115
|
+
const authenticateHeader = (error) => {
|
|
116
|
+
const parts = ['Bearer realm="mysql-mcp"'];
|
|
117
|
+
if (resourceMetadataUrl && config.auth === "oauth") {
|
|
118
|
+
parts.push(`resource_metadata="${resourceMetadataUrl}"`);
|
|
119
|
+
}
|
|
120
|
+
// RFC 6750: no error code when the request carried no credentials
|
|
121
|
+
if (error && error.oauthError !== "invalid_request") {
|
|
122
|
+
parts.push(`error="${error.oauthError}"`, `error_description="${error.message.replace(/"/g, "'")}"`);
|
|
123
|
+
}
|
|
124
|
+
if (error?.oauthError === "insufficient_scope" && config.oauth?.requiredScopes.length) {
|
|
125
|
+
parts.push(`scope="${config.oauth.requiredScopes.join(" ")}"`);
|
|
126
|
+
}
|
|
127
|
+
return parts.join(", ");
|
|
128
|
+
};
|
|
129
|
+
const closeSession = (sessionId, reason) => {
|
|
130
|
+
const session = sessions.get(sessionId);
|
|
131
|
+
if (!session)
|
|
132
|
+
return;
|
|
133
|
+
sessions.delete(sessionId);
|
|
134
|
+
try {
|
|
135
|
+
options.onSessionClosed?.(sessionId);
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
console.error(`Session ${sessionId} cleanup failed: ${error.message}`);
|
|
139
|
+
}
|
|
140
|
+
auditLogger.log({ event: "session_closed", session: sessionId, client: session.clientId, reason });
|
|
141
|
+
// server.close() closes the transport, whose onclose re-enters here as a no-op
|
|
142
|
+
session.server.close().catch(() => undefined);
|
|
143
|
+
};
|
|
144
|
+
const findSession = (req, res, authInfo) => {
|
|
145
|
+
const header = req.headers["mcp-session-id"];
|
|
146
|
+
const sessionId = Array.isArray(header) ? header[0] : header;
|
|
147
|
+
if (!sessionId) {
|
|
148
|
+
sendJson(res, 400, jsonRpcError(-32000, "Bad Request: Mcp-Session-Id header is required"));
|
|
149
|
+
return undefined;
|
|
150
|
+
}
|
|
151
|
+
const session = sessions.get(sessionId);
|
|
152
|
+
if (!session) {
|
|
153
|
+
sendJson(res, 404, jsonRpcError(-32001, "Session not found"));
|
|
154
|
+
return undefined;
|
|
155
|
+
}
|
|
156
|
+
if (session.clientId !== authInfo.clientId) {
|
|
157
|
+
sendJson(res, 403, jsonRpcError(-32000, "Forbidden: session belongs to another client"));
|
|
158
|
+
return undefined;
|
|
159
|
+
}
|
|
160
|
+
session.lastSeen = Date.now();
|
|
161
|
+
return session;
|
|
162
|
+
};
|
|
163
|
+
const startSession = async (req, res, authInfo, body) => {
|
|
164
|
+
if (config.maxSessions > 0 && sessions.size >= config.maxSessions) {
|
|
165
|
+
sendJson(res, 503, jsonRpcError(-32000, "Too many active sessions, try again later"), { "Retry-After": "60" });
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
const server = createServer();
|
|
169
|
+
const transport = new streamableHttp_js_1.StreamableHTTPServerTransport({
|
|
170
|
+
sessionIdGenerator: () => (0, crypto_1.randomUUID)(),
|
|
171
|
+
onsessioninitialized: (sessionId) => {
|
|
172
|
+
sessions.set(sessionId, { transport, server, clientId: authInfo.clientId, lastSeen: Date.now() });
|
|
173
|
+
auditLogger.log({
|
|
174
|
+
event: "session_opened",
|
|
175
|
+
session: sessionId,
|
|
176
|
+
client: authInfo.clientId,
|
|
177
|
+
ip: authInfo.extra?.clientIp,
|
|
178
|
+
});
|
|
179
|
+
},
|
|
180
|
+
onsessionclosed: (sessionId) => closeSession(sessionId, "deleted by client"),
|
|
181
|
+
});
|
|
182
|
+
transport.onclose = () => {
|
|
183
|
+
if (transport.sessionId)
|
|
184
|
+
closeSession(transport.sessionId, "transport closed");
|
|
185
|
+
};
|
|
186
|
+
await server.connect(transport);
|
|
187
|
+
req.auth = authInfo;
|
|
188
|
+
await transport.handleRequest(req, res, body);
|
|
189
|
+
// A rejected initialize never creates a session; release its server
|
|
190
|
+
if (!transport.sessionId || !sessions.has(transport.sessionId)) {
|
|
191
|
+
await server.close().catch(() => undefined);
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
const handleMcpRequest = async (req, res, clientIp) => {
|
|
195
|
+
let authInfo;
|
|
196
|
+
try {
|
|
197
|
+
authInfo = await authenticator.authenticate(req.headers.authorization);
|
|
198
|
+
}
|
|
199
|
+
catch (error) {
|
|
200
|
+
if (!(error instanceof auth_1.AuthError))
|
|
201
|
+
throw error;
|
|
202
|
+
auditLogger.log({ event: "auth_failed", ip: clientIp, reason: error.message });
|
|
203
|
+
sendJson(res, error.status, { error: error.oauthError, error_description: error.message }, { "WWW-Authenticate": authenticateHeader(error) });
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
authInfo = { ...authInfo, extra: { ...(authInfo.extra || {}), clientIp } };
|
|
207
|
+
if (req.method === "POST") {
|
|
208
|
+
let body;
|
|
209
|
+
try {
|
|
210
|
+
body = await readJsonBody(req, config.maxBodyBytes);
|
|
211
|
+
}
|
|
212
|
+
catch (error) {
|
|
213
|
+
const status = error instanceof RequestBodyError ? error.status : 400;
|
|
214
|
+
sendJson(res, status, jsonRpcError(status === 413 ? -32000 : -32700, error.message), { Connection: "close" });
|
|
215
|
+
if (status === 413)
|
|
216
|
+
res.on("finish", () => req.destroy());
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
if (req.headers["mcp-session-id"]) {
|
|
220
|
+
const session = findSession(req, res, authInfo);
|
|
221
|
+
if (!session)
|
|
222
|
+
return;
|
|
223
|
+
req.auth = authInfo;
|
|
224
|
+
await session.transport.handleRequest(req, res, body);
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
const initializing = Array.isArray(body) ? body.some(types_js_1.isInitializeRequest) : (0, types_js_1.isInitializeRequest)(body);
|
|
228
|
+
if (!initializing) {
|
|
229
|
+
sendJson(res, 400, jsonRpcError(-32000, "Bad Request: No valid session ID provided"));
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
await startSession(req, res, authInfo, body);
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
if (req.method === "GET" || req.method === "DELETE") {
|
|
236
|
+
const session = findSession(req, res, authInfo);
|
|
237
|
+
if (!session)
|
|
238
|
+
return;
|
|
239
|
+
req.auth = authInfo;
|
|
240
|
+
await session.transport.handleRequest(req, res);
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
sendJson(res, 405, jsonRpcError(-32000, "Method not allowed"), { Allow: "GET, POST, DELETE, OPTIONS" });
|
|
244
|
+
};
|
|
245
|
+
const handleRequest = async (req, res) => {
|
|
246
|
+
const pathname = (new URL(req.url || "/", "http://localhost").pathname.replace(/\/+$/, "") || "/");
|
|
247
|
+
if (pathname === "/health" && req.method === "GET") {
|
|
248
|
+
sendJson(res, 200, { status: "ok" });
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
// DNS-rebinding protection: reject unexpected Host and Origin headers
|
|
252
|
+
if (!isHostAllowed(req.headers.host)) {
|
|
253
|
+
sendJson(res, 403, jsonRpcError(-32000, "Forbidden: Host header is not allowed"));
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
const origin = req.headers.origin;
|
|
257
|
+
if (origin) {
|
|
258
|
+
if (!isOriginAllowed(origin)) {
|
|
259
|
+
sendJson(res, 403, jsonRpcError(-32000, "Forbidden: Origin is not allowed"));
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
setCorsHeaders(res, origin);
|
|
263
|
+
}
|
|
264
|
+
if (req.method === "OPTIONS") {
|
|
265
|
+
res.writeHead(204);
|
|
266
|
+
res.end();
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
if (config.auth === "oauth" && req.method === "GET" && metadataPaths.has(pathname)) {
|
|
270
|
+
sendJson(res, 200, (0, auth_1.protectedResourceMetadata)(config));
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
if (pathname !== config.path) {
|
|
274
|
+
sendJson(res, 404, { error: "Not found" });
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
await handleMcpRequest(req, res, clientIpOf(req));
|
|
278
|
+
};
|
|
279
|
+
const server = http_1.default.createServer((req, res) => {
|
|
280
|
+
handleRequest(req, res).catch((error) => {
|
|
281
|
+
console.error(`HTTP request failed: ${error?.message || error}`);
|
|
282
|
+
sendJson(res, 500, jsonRpcError(-32603, "Internal server error"));
|
|
283
|
+
});
|
|
284
|
+
});
|
|
285
|
+
const sweepInterval = Math.max(1000, Math.min(60 * 1000, config.sessionIdleTimeoutMs || 60 * 1000));
|
|
286
|
+
const sweeper = setInterval(() => {
|
|
287
|
+
if (config.sessionIdleTimeoutMs <= 0)
|
|
288
|
+
return;
|
|
289
|
+
const now = Date.now();
|
|
290
|
+
for (const [sessionId, session] of sessions) {
|
|
291
|
+
if (now - session.lastSeen > config.sessionIdleTimeoutMs)
|
|
292
|
+
closeSession(sessionId, "idle timeout");
|
|
293
|
+
}
|
|
294
|
+
}, sweepInterval);
|
|
295
|
+
sweeper.unref();
|
|
296
|
+
await new Promise((resolve, reject) => {
|
|
297
|
+
server.once("error", reject);
|
|
298
|
+
server.listen(config.port, config.host, () => {
|
|
299
|
+
server.off("error", reject);
|
|
300
|
+
resolve();
|
|
301
|
+
});
|
|
302
|
+
});
|
|
303
|
+
const address = server.address();
|
|
304
|
+
const port = typeof address === "object" && address ? address.port : config.port;
|
|
305
|
+
const displayHost = config.host.includes(":") ? `[${config.host}]` : config.host;
|
|
306
|
+
return {
|
|
307
|
+
server,
|
|
308
|
+
url: `http://${displayHost}:${port}${config.path}`,
|
|
309
|
+
sessionCount: () => sessions.size,
|
|
310
|
+
close: async () => {
|
|
311
|
+
clearInterval(sweeper);
|
|
312
|
+
for (const sessionId of [...sessions.keys()])
|
|
313
|
+
closeSession(sessionId, "server shutdown");
|
|
314
|
+
const closed = new Promise((resolve) => server.close(() => resolve()));
|
|
315
|
+
server.closeAllConnections();
|
|
316
|
+
await closed;
|
|
317
|
+
},
|
|
318
|
+
};
|
|
319
|
+
};
|
|
320
|
+
exports.startHttpServer = startHttpServer;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sliding-window limiter: at most `limit` events per key in any 60 s window.
|
|
3
|
+
* A limit of 0 disables it.
|
|
4
|
+
*/
|
|
5
|
+
export declare class RateLimiter {
|
|
6
|
+
private readonly limit;
|
|
7
|
+
private readonly now;
|
|
8
|
+
private readonly hits;
|
|
9
|
+
constructor(limit: number, now?: () => number);
|
|
10
|
+
get enabled(): boolean;
|
|
11
|
+
/** Records a hit; returns 0 when allowed, otherwise the milliseconds until the next slot frees up. */
|
|
12
|
+
consume(key: string): number;
|
|
13
|
+
/** Drops keys with no hits in the current window. */
|
|
14
|
+
prune(): void;
|
|
15
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.RateLimiter = void 0;
|
|
4
|
+
const WINDOW_MS = 60 * 1000;
|
|
5
|
+
/**
|
|
6
|
+
* Sliding-window limiter: at most `limit` events per key in any 60 s window.
|
|
7
|
+
* A limit of 0 disables it.
|
|
8
|
+
*/
|
|
9
|
+
class RateLimiter {
|
|
10
|
+
constructor(limit, now = Date.now) {
|
|
11
|
+
this.limit = limit;
|
|
12
|
+
this.now = now;
|
|
13
|
+
this.hits = new Map();
|
|
14
|
+
}
|
|
15
|
+
get enabled() {
|
|
16
|
+
return this.limit > 0;
|
|
17
|
+
}
|
|
18
|
+
/** Records a hit; returns 0 when allowed, otherwise the milliseconds until the next slot frees up. */
|
|
19
|
+
consume(key) {
|
|
20
|
+
if (!this.enabled)
|
|
21
|
+
return 0;
|
|
22
|
+
const now = this.now();
|
|
23
|
+
const recent = (this.hits.get(key) || []).filter((time) => now - time < WINDOW_MS);
|
|
24
|
+
if (recent.length >= this.limit) {
|
|
25
|
+
this.hits.set(key, recent);
|
|
26
|
+
return WINDOW_MS - (now - recent[0]);
|
|
27
|
+
}
|
|
28
|
+
recent.push(now);
|
|
29
|
+
this.hits.set(key, recent);
|
|
30
|
+
return 0;
|
|
31
|
+
}
|
|
32
|
+
/** Drops keys with no hits in the current window. */
|
|
33
|
+
prune() {
|
|
34
|
+
const now = this.now();
|
|
35
|
+
for (const [key, times] of this.hits) {
|
|
36
|
+
if (times.every((time) => now - time >= WINDOW_MS))
|
|
37
|
+
this.hits.delete(key);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
exports.RateLimiter = RateLimiter;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Identity of the caller for the tool call currently executing. Over stdio
|
|
3
|
+
* there is a single local caller and no session id.
|
|
4
|
+
*/
|
|
5
|
+
export interface RequestContext {
|
|
6
|
+
transport: "stdio" | "http";
|
|
7
|
+
sessionId?: string;
|
|
8
|
+
clientId?: string;
|
|
9
|
+
clientIp?: string;
|
|
10
|
+
}
|
|
11
|
+
export declare const runWithRequestContext: <T>(context: RequestContext, fn: () => Promise<T>) => Promise<T>;
|
|
12
|
+
export declare const getRequestContext: () => RequestContext | undefined;
|