keryx 0.39.2 → 0.40.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/classes/Action.ts +9 -3
- package/initializers/actionts.ts +6 -1
- package/initializers/mcp.ts +110 -16
- package/initializers/pubsub.ts +4 -2
- package/package.json +1 -1
- package/util/http.ts +8 -1
- package/util/mcpServer.ts +158 -2
- package/util/webResponse.ts +8 -2
package/classes/Action.ts
CHANGED
|
@@ -91,7 +91,11 @@ export type OAuthActionResponse = {
|
|
|
91
91
|
};
|
|
92
92
|
|
|
93
93
|
export type McpActionConfig = {
|
|
94
|
-
/**
|
|
94
|
+
/**
|
|
95
|
+
* Expose this action as an MCP tool. Tools are **opt-in** (default `false`):
|
|
96
|
+
* set `tool: true` to publish the action to MCP clients. Declaring an MCP App
|
|
97
|
+
* via `ui` implies a tool unless `tool` is explicitly `false`.
|
|
98
|
+
*/
|
|
95
99
|
tool?: boolean;
|
|
96
100
|
/** Tag as the OAuth login action */
|
|
97
101
|
isLoginAction?: boolean;
|
|
@@ -147,7 +151,7 @@ export type ActionConstructorInputs = {
|
|
|
147
151
|
/** Middleware hooks to run before/after `run()` */
|
|
148
152
|
middleware?: ActionMiddleware[];
|
|
149
153
|
|
|
150
|
-
/** Expose this action via the MCP server
|
|
154
|
+
/** Expose this action via the MCP server. Tools are opt-in — set `mcp: { tool: true }` to publish one. */
|
|
151
155
|
mcp?: McpActionConfig;
|
|
152
156
|
|
|
153
157
|
/** Expose this action via HTTP (defaults: route `/${name}`, method `GET`) */
|
|
@@ -234,7 +238,9 @@ export abstract class Action {
|
|
|
234
238
|
this.inputs = args.inputs;
|
|
235
239
|
this.middleware = args.middleware ?? [];
|
|
236
240
|
this.timeout = args.timeout;
|
|
237
|
-
|
|
241
|
+
// MCP tools are opt-in — see the actions initializer for rationale. An action
|
|
242
|
+
// becomes a tool only when it sets `mcp.tool = true` (or declares `mcp.ui`).
|
|
243
|
+
this.mcp = { tool: false, ...args.mcp };
|
|
238
244
|
this.web = {
|
|
239
245
|
route: args.web?.route ?? `/${this.name}`,
|
|
240
246
|
method: args.web?.method ?? HTTP_METHOD.GET,
|
package/initializers/actionts.ts
CHANGED
|
@@ -716,7 +716,12 @@ export class Actions extends Initializer {
|
|
|
716
716
|
|
|
717
717
|
for (const a of actions) {
|
|
718
718
|
if (!a.description) a.description = `An Action: ${a.name}`;
|
|
719
|
-
|
|
719
|
+
// MCP tools are opt-in: an action is exposed as a tool only when it
|
|
720
|
+
// explicitly sets `mcp.tool = true` (or declares an MCP App via `mcp.ui`).
|
|
721
|
+
// Defaulting to `false` prevents actions — especially destructive or
|
|
722
|
+
// maintenance ones — from being silently reachable by any authenticated
|
|
723
|
+
// MCP client just because they exist.
|
|
724
|
+
a.mcp = { tool: false, ...a.mcp };
|
|
720
725
|
}
|
|
721
726
|
|
|
722
727
|
logger.info(
|
package/initializers/mcp.ts
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
2
|
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
isInitializeRequest,
|
|
5
|
+
LATEST_PROTOCOL_VERSION,
|
|
6
|
+
SUPPORTED_PROTOCOL_VERSIONS,
|
|
7
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
4
8
|
import { randomUUID } from "crypto";
|
|
5
9
|
import { api, logger } from "../api";
|
|
6
10
|
import { Initializer } from "../classes/Initializer";
|
|
@@ -20,13 +24,18 @@ import {
|
|
|
20
24
|
forgetMcpSession,
|
|
21
25
|
formatToolName,
|
|
22
26
|
handleTransportRequest,
|
|
27
|
+
isMcpSessionAuthorizedForChannel,
|
|
28
|
+
MCP_JSONRPC_ERROR,
|
|
23
29
|
type McpAuthInfo,
|
|
30
|
+
type McpSessionAuth,
|
|
24
31
|
mcpJsonResponse,
|
|
32
|
+
mcpJsonRpcErrorResponse,
|
|
25
33
|
parseToolName,
|
|
26
34
|
readMcpSessionRecord,
|
|
27
35
|
refreshMcpSessionTtl,
|
|
28
36
|
sanitizeSchemaForMcp,
|
|
29
37
|
terminateMcpSession,
|
|
38
|
+
validateJsonRpcPayload,
|
|
30
39
|
writeMcpSessionRecord,
|
|
31
40
|
} from "../util/mcpServer";
|
|
32
41
|
import type { PubSubMessage } from "./pubsub";
|
|
@@ -59,18 +68,34 @@ export type OnMcpDisconnectHook = (sessionId: string) => Promise<void> | void;
|
|
|
59
68
|
const namespace = "mcp";
|
|
60
69
|
|
|
61
70
|
/**
|
|
62
|
-
*
|
|
63
|
-
*
|
|
71
|
+
* Resolve the protocol version an `initialize` request body (single message or
|
|
72
|
+
* batch) actually negotiates, so it can be stored in the shared session registry
|
|
64
73
|
* and replayed when the session is adopted on another node.
|
|
74
|
+
*
|
|
75
|
+
* This is the *negotiated* version, not the requested one: a client on a newer
|
|
76
|
+
* spec revision than the SDK supports (e.g. `2026-07-28`) is answered with the
|
|
77
|
+
* newest version the server does support, exactly as the SDK's `initialize`
|
|
78
|
+
* handler does. Persisting the raw request instead would leave the registry
|
|
79
|
+
* holding a version no node can replay, and the session would silently fall back
|
|
80
|
+
* to the 2025-03-26 default the first time it was adopted elsewhere.
|
|
81
|
+
*
|
|
82
|
+
* @param body - The parsed POST body.
|
|
83
|
+
* @returns The negotiated version, or `undefined` when the body contains no
|
|
84
|
+
* `initialize` request.
|
|
65
85
|
*/
|
|
66
|
-
function
|
|
86
|
+
function negotiateInitProtocolVersion(body: unknown): string | undefined {
|
|
67
87
|
const messages = Array.isArray(body) ? body : [body];
|
|
68
88
|
for (const message of messages) {
|
|
69
89
|
if (isInitializeRequest(message)) {
|
|
70
90
|
const protocolVersion = (
|
|
71
91
|
message as { params?: { protocolVersion?: unknown } }
|
|
72
92
|
).params?.protocolVersion;
|
|
73
|
-
if (typeof protocolVersion
|
|
93
|
+
if (typeof protocolVersion !== "string") continue;
|
|
94
|
+
return (SUPPORTED_PROTOCOL_VERSIONS as readonly string[]).includes(
|
|
95
|
+
protocolVersion,
|
|
96
|
+
)
|
|
97
|
+
? protocolVersion
|
|
98
|
+
: LATEST_PROTOCOL_VERSION;
|
|
74
99
|
}
|
|
75
100
|
}
|
|
76
101
|
return undefined;
|
|
@@ -85,11 +110,21 @@ declare module "keryx" {
|
|
|
85
110
|
export class McpInitializer extends Initializer {
|
|
86
111
|
constructor() {
|
|
87
112
|
super(namespace);
|
|
88
|
-
this.dependsOn = [
|
|
113
|
+
this.dependsOn = [
|
|
114
|
+
"hooks",
|
|
115
|
+
"actions",
|
|
116
|
+
"oauth",
|
|
117
|
+
"connections",
|
|
118
|
+
"pubsub",
|
|
119
|
+
"channels",
|
|
120
|
+
];
|
|
89
121
|
}
|
|
90
122
|
|
|
91
123
|
async initialize() {
|
|
92
124
|
const mcpServers: McpServer[] = [];
|
|
125
|
+
// Per-session auth context, so a broadcast is delivered only to sessions
|
|
126
|
+
// whose user is authorized for its channel (see sendNotification).
|
|
127
|
+
const mcpServerAuth = new Map<McpServer, McpSessionAuth>();
|
|
93
128
|
const transports = new Map<
|
|
94
129
|
string,
|
|
95
130
|
{
|
|
@@ -98,8 +133,21 @@ export class McpInitializer extends Initializer {
|
|
|
98
133
|
}
|
|
99
134
|
>();
|
|
100
135
|
|
|
101
|
-
|
|
136
|
+
// Deliver a PubSub broadcast to MCP sessions as a logging notification, but
|
|
137
|
+
// ONLY to sessions whose user is authorized to subscribe to the broadcast's
|
|
138
|
+
// channel. Without this gate every session on the node would receive every
|
|
139
|
+
// broadcast — a cross-user/cross-tenant data leak — because MCP sessions
|
|
140
|
+
// have no per-channel subscription of their own. Sessions with no captured
|
|
141
|
+
// auth context are skipped (fail closed).
|
|
142
|
+
async function sendNotification(payload: PubSubMessage) {
|
|
102
143
|
for (const server of mcpServers) {
|
|
144
|
+
const auth = mcpServerAuth.get(server);
|
|
145
|
+
if (!auth) continue;
|
|
146
|
+
const authorized = await isMcpSessionAuthorizedForChannel(
|
|
147
|
+
auth,
|
|
148
|
+
payload.channel,
|
|
149
|
+
);
|
|
150
|
+
if (!authorized) continue;
|
|
103
151
|
try {
|
|
104
152
|
server.server
|
|
105
153
|
.sendLoggingMessage({
|
|
@@ -121,6 +169,7 @@ export class McpInitializer extends Initializer {
|
|
|
121
169
|
|
|
122
170
|
return {
|
|
123
171
|
mcpServers,
|
|
172
|
+
mcpServerAuth,
|
|
124
173
|
transports,
|
|
125
174
|
handleRequest: null as McpHandleRequest | null,
|
|
126
175
|
sendNotification,
|
|
@@ -247,17 +296,41 @@ export class McpInitializer extends Initializer {
|
|
|
247
296
|
|
|
248
297
|
const sessionId = req.headers.get("mcp-session-id");
|
|
249
298
|
|
|
299
|
+
// Validate the JSON-RPC envelope of every POST before it reaches a
|
|
300
|
+
// transport. The SDK transport answers both "not JSON" and "not a
|
|
301
|
+
// JSON-RPC message" with `-32700 Parse error`; JSON-RPC 2.0 reserves that
|
|
302
|
+
// code for unparseable input and requires `-32600 Invalid Request` for a
|
|
303
|
+
// payload that parses but isn't a valid message. Parsing here also means
|
|
304
|
+
// the body is read exactly once — the result is handed to the transport as
|
|
305
|
+
// `parsedBody`.
|
|
306
|
+
let body: unknown;
|
|
307
|
+
if (method === "POST") {
|
|
308
|
+
try {
|
|
309
|
+
body = await req.json();
|
|
310
|
+
} catch {
|
|
311
|
+
return mcpJsonRpcErrorResponse(
|
|
312
|
+
MCP_JSONRPC_ERROR.PARSE_ERROR,
|
|
313
|
+
"Parse error: body is not valid JSON",
|
|
314
|
+
400,
|
|
315
|
+
corsHeaders,
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
const invalid = validateJsonRpcPayload(body);
|
|
319
|
+
if (invalid) {
|
|
320
|
+
return mcpJsonRpcErrorResponse(
|
|
321
|
+
invalid.code,
|
|
322
|
+
invalid.message,
|
|
323
|
+
400,
|
|
324
|
+
corsHeaders,
|
|
325
|
+
);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
250
329
|
if (method === "POST" && !sessionId) {
|
|
251
330
|
// Only an `initialize` request may create a new session. Any other
|
|
252
331
|
// request without a session id is a protocol error → 400. We must gate
|
|
253
332
|
// here rather than delegating, otherwise a non-initialize POST spins up
|
|
254
333
|
// an McpServer that never initializes and leaks into `mcpServers`.
|
|
255
|
-
let body: unknown;
|
|
256
|
-
try {
|
|
257
|
-
body = await req.clone().json();
|
|
258
|
-
} catch {
|
|
259
|
-
return mcpJsonResponse({ error: "Invalid JSON" }, 400, corsHeaders);
|
|
260
|
-
}
|
|
261
334
|
const isInit = Array.isArray(body)
|
|
262
335
|
? body.some(isInitializeRequest)
|
|
263
336
|
: isInitializeRequest(body);
|
|
@@ -268,11 +341,18 @@ export class McpInitializer extends Initializer {
|
|
|
268
341
|
corsHeaders,
|
|
269
342
|
);
|
|
270
343
|
}
|
|
271
|
-
const protocolVersion =
|
|
344
|
+
const protocolVersion = negotiateInitProtocolVersion(body);
|
|
272
345
|
|
|
273
346
|
// New session — create a new McpServer + transport
|
|
274
347
|
const mcpServer = createMcpServer();
|
|
275
348
|
mcpServers.push(mcpServer);
|
|
349
|
+
// Capture the session's auth context so channel-broadcast delivery can
|
|
350
|
+
// authorize this session (see sendNotification).
|
|
351
|
+
api.mcp.mcpServerAuth.set(mcpServer, {
|
|
352
|
+
clientId: authInfo.clientId,
|
|
353
|
+
userId: authInfo.extra?.userId,
|
|
354
|
+
ip,
|
|
355
|
+
});
|
|
276
356
|
|
|
277
357
|
const sessionClientId = authInfo.clientId;
|
|
278
358
|
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
@@ -305,7 +385,13 @@ export class McpInitializer extends Initializer {
|
|
|
305
385
|
for (const hook of api.hooks.mcp.onMessageHooks) {
|
|
306
386
|
await hook(undefined);
|
|
307
387
|
}
|
|
308
|
-
return handleTransportRequest(
|
|
388
|
+
return handleTransportRequest(
|
|
389
|
+
transport,
|
|
390
|
+
req,
|
|
391
|
+
authInfo,
|
|
392
|
+
corsHeaders,
|
|
393
|
+
body,
|
|
394
|
+
);
|
|
309
395
|
}
|
|
310
396
|
|
|
311
397
|
if (sessionId) {
|
|
@@ -344,6 +430,7 @@ export class McpInitializer extends Initializer {
|
|
|
344
430
|
sessionId,
|
|
345
431
|
record.clientId,
|
|
346
432
|
record.protocolVersion,
|
|
433
|
+
{ userId: authInfo.extra?.userId, ip },
|
|
347
434
|
);
|
|
348
435
|
}
|
|
349
436
|
|
|
@@ -352,7 +439,13 @@ export class McpInitializer extends Initializer {
|
|
|
352
439
|
for (const hook of api.hooks.mcp.onMessageHooks) {
|
|
353
440
|
await hook(sessionId);
|
|
354
441
|
}
|
|
355
|
-
return handleTransportRequest(
|
|
442
|
+
return handleTransportRequest(
|
|
443
|
+
transport,
|
|
444
|
+
req,
|
|
445
|
+
authInfo,
|
|
446
|
+
corsHeaders,
|
|
447
|
+
body,
|
|
448
|
+
);
|
|
356
449
|
}
|
|
357
450
|
|
|
358
451
|
// GET/DELETE without session ID
|
|
@@ -390,6 +483,7 @@ export class McpInitializer extends Initializer {
|
|
|
390
483
|
}
|
|
391
484
|
}
|
|
392
485
|
api.mcp.mcpServers.length = 0;
|
|
486
|
+
api.mcp.mcpServerAuth.clear();
|
|
393
487
|
|
|
394
488
|
api.mcp.handleRequest = null;
|
|
395
489
|
}
|
package/initializers/pubsub.ts
CHANGED
|
@@ -88,9 +88,11 @@ export class PubSub extends Initializer {
|
|
|
88
88
|
}
|
|
89
89
|
}
|
|
90
90
|
|
|
91
|
-
// Forward to MCP as notifications
|
|
91
|
+
// Forward to MCP as notifications (authorized per-session; fire-and-forget).
|
|
92
92
|
if (config.server.mcp.enabled && api.mcp?.sendNotification) {
|
|
93
|
-
api.mcp.sendNotification(payload)
|
|
93
|
+
void api.mcp.sendNotification(payload).catch(() => {
|
|
94
|
+
// notification delivery is best-effort
|
|
95
|
+
});
|
|
94
96
|
}
|
|
95
97
|
}
|
|
96
98
|
}
|
package/package.json
CHANGED
package/util/http.ts
CHANGED
|
@@ -65,7 +65,14 @@ export function buildCorsHeaders(
|
|
|
65
65
|
const headers: Record<string, string> = { ...extra };
|
|
66
66
|
const allowedOrigins = config.server.web.allowedOrigins;
|
|
67
67
|
|
|
68
|
-
if (allowedOrigins === "*"
|
|
68
|
+
if (allowedOrigins === "*") {
|
|
69
|
+
// Wildcard: always emit a literal "*" and never reflect the specific request
|
|
70
|
+
// origin. Reflecting the origin sets `Vary: Origin`, which downstream (see
|
|
71
|
+
// buildHeaders in webResponse.ts) adds `Access-Control-Allow-Credentials:
|
|
72
|
+
// true` — and reflecting an *arbitrary* origin together with credentials lets
|
|
73
|
+
// any website read a victim's authenticated cross-origin responses. A literal
|
|
74
|
+
// "*" can never carry credentials (browsers forbid the combination), so this
|
|
75
|
+
// stays a safe permissive default for public, non-credentialed endpoints.
|
|
69
76
|
headers["Access-Control-Allow-Origin"] = "*";
|
|
70
77
|
} else if (
|
|
71
78
|
requestOrigin &&
|
package/util/mcpServer.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/
|
|
|
6
6
|
import type { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/protocol.js";
|
|
7
7
|
import {
|
|
8
8
|
DEFAULT_NEGOTIATED_PROTOCOL_VERSION,
|
|
9
|
+
JSONRPCMessageSchema,
|
|
9
10
|
type ServerNotification,
|
|
10
11
|
type ServerRequest,
|
|
11
12
|
SUPPORTED_PROTOCOL_VERSIONS,
|
|
@@ -79,18 +80,85 @@ export async function createMcpConnection(extra: {
|
|
|
79
80
|
return connection;
|
|
80
81
|
}
|
|
81
82
|
|
|
83
|
+
/**
|
|
84
|
+
* Auth context captured for a live MCP session (`McpServer`), used to authorize
|
|
85
|
+
* which channel broadcasts that session is allowed to receive. Keyed by
|
|
86
|
+
* `McpServer` in `api.mcp.mcpServerAuth`.
|
|
87
|
+
*/
|
|
88
|
+
export type McpSessionAuth = {
|
|
89
|
+
/** OAuth client id that owns the session. */
|
|
90
|
+
clientId: string;
|
|
91
|
+
/** Authenticated user id from the session's access token, if any. */
|
|
92
|
+
userId?: unknown;
|
|
93
|
+
/** Remote IP captured at session creation (best-effort). */
|
|
94
|
+
ip?: string;
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Decide whether an MCP session's user is allowed to receive broadcasts for a
|
|
99
|
+
* channel. Runs the channel's real subscription authorization
|
|
100
|
+
* ({@link api.channels.authorizeSubscription}) against a throwaway in-memory
|
|
101
|
+
* probe connection so app-defined channel middleware/`authorize()` rules apply
|
|
102
|
+
* exactly as they do for WebSocket subscribers.
|
|
103
|
+
*
|
|
104
|
+
* The probe's session is populated in memory (never persisted to Redis) so this
|
|
105
|
+
* check adds no session writes on the broadcast hot path. Fails closed: returns
|
|
106
|
+
* `false` on any authorization error or unknown channel.
|
|
107
|
+
*
|
|
108
|
+
* @param auth - The session's captured auth context.
|
|
109
|
+
* @param channelName - The channel the broadcast targets.
|
|
110
|
+
* @returns `true` only if the session's user may subscribe to `channelName`.
|
|
111
|
+
*/
|
|
112
|
+
export async function isMcpSessionAuthorizedForChannel(
|
|
113
|
+
auth: McpSessionAuth,
|
|
114
|
+
channelName: string,
|
|
115
|
+
): Promise<boolean> {
|
|
116
|
+
const probe = new Connection(
|
|
117
|
+
CONNECTION_TYPE.MCP,
|
|
118
|
+
auth.ip ?? "unknown",
|
|
119
|
+
randomUUID(),
|
|
120
|
+
);
|
|
121
|
+
probe.session = {
|
|
122
|
+
id: probe.sessionId,
|
|
123
|
+
cookieName: config.session.cookieName,
|
|
124
|
+
createdAt: new Date().getTime(),
|
|
125
|
+
data: auth.userId != null ? { userId: auth.userId } : {},
|
|
126
|
+
};
|
|
127
|
+
probe.sessionLoaded = true;
|
|
128
|
+
try {
|
|
129
|
+
await api.channels.authorizeSubscription(channelName, probe);
|
|
130
|
+
return true;
|
|
131
|
+
} catch {
|
|
132
|
+
return false;
|
|
133
|
+
} finally {
|
|
134
|
+
probe.destroy();
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
82
138
|
/**
|
|
83
139
|
* Forward a request to an MCP transport and return the response with CORS headers.
|
|
84
140
|
* Handles the try/catch + error response pattern shared by new-session and existing-session paths.
|
|
141
|
+
*
|
|
142
|
+
* @param transport - The session's Streamable HTTP transport.
|
|
143
|
+
* @param req - The inbound MCP request.
|
|
144
|
+
* @param authInfo - Verified bearer-token context for the request, if any.
|
|
145
|
+
* @param corsHeaders - CORS headers to append to whatever the transport returns.
|
|
146
|
+
* @param parsedBody - The already-parsed POST body, so the transport doesn't
|
|
147
|
+
* re-read (and re-parse) a stream Keryx has already consumed while validating
|
|
148
|
+
* the JSON-RPC envelope. Omit for GET/DELETE.
|
|
85
149
|
*/
|
|
86
150
|
export async function handleTransportRequest(
|
|
87
151
|
transport: WebStandardStreamableHTTPServerTransport,
|
|
88
152
|
req: Request,
|
|
89
153
|
authInfo: McpAuthInfo | undefined,
|
|
90
154
|
corsHeaders: Record<string, string>,
|
|
155
|
+
parsedBody?: unknown,
|
|
91
156
|
): Promise<Response> {
|
|
92
157
|
try {
|
|
93
|
-
const response = await transport.handleRequest(req, {
|
|
158
|
+
const response = await transport.handleRequest(req, {
|
|
159
|
+
authInfo,
|
|
160
|
+
parsedBody,
|
|
161
|
+
});
|
|
94
162
|
return appendHeaders(response, corsHeaders);
|
|
95
163
|
} catch (e) {
|
|
96
164
|
logger.error(`MCP transport error: ${e}`);
|
|
@@ -126,6 +194,79 @@ export function mcpJsonResponse(
|
|
|
126
194
|
});
|
|
127
195
|
}
|
|
128
196
|
|
|
197
|
+
/**
|
|
198
|
+
* The JSON-RPC 2.0 error codes the MCP endpoint returns for a POST body it
|
|
199
|
+
* refuses to dispatch. `PARSE_ERROR` means the body was not JSON at all;
|
|
200
|
+
* `INVALID_REQUEST` means it was JSON but not a well-formed JSON-RPC message.
|
|
201
|
+
* The distinction matters: the MCP SDK transport reports both as `PARSE_ERROR`,
|
|
202
|
+
* which conformance checkers flag, so Keryx validates the envelope itself
|
|
203
|
+
* before handing the body to the transport.
|
|
204
|
+
*/
|
|
205
|
+
export const MCP_JSONRPC_ERROR = {
|
|
206
|
+
PARSE_ERROR: -32700,
|
|
207
|
+
INVALID_REQUEST: -32600,
|
|
208
|
+
} as const;
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Build a JSON-RPC *error response* for a message that could never be
|
|
212
|
+
* dispatched. `id` is always `null`: JSON-RPC 2.0 requires a null id when the
|
|
213
|
+
* request's id can't be determined, and the Streamable HTTP transport spec says
|
|
214
|
+
* the body of a rejected POST may carry an error response with no id.
|
|
215
|
+
*
|
|
216
|
+
* @param code - JSON-RPC error code (see {@link MCP_JSONRPC_ERROR}).
|
|
217
|
+
* @param message - Human-readable explanation, surfaced to the client verbatim.
|
|
218
|
+
* @param status - HTTP status to pair with it (400 for malformed input).
|
|
219
|
+
* @param corsHeaders - CORS headers for the MCP endpoint.
|
|
220
|
+
*/
|
|
221
|
+
export function mcpJsonRpcErrorResponse(
|
|
222
|
+
code: number,
|
|
223
|
+
message: string,
|
|
224
|
+
status: number,
|
|
225
|
+
corsHeaders: Record<string, string>,
|
|
226
|
+
): Response {
|
|
227
|
+
return mcpJsonResponse(
|
|
228
|
+
{ jsonrpc: "2.0", error: { code, message }, id: null },
|
|
229
|
+
status,
|
|
230
|
+
corsHeaders,
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Validate a parsed MCP POST body against the JSON-RPC message schema, so a
|
|
236
|
+
* structurally invalid message is rejected as `-32600 Invalid Request` rather
|
|
237
|
+
* than being mislabeled a parse error by the transport.
|
|
238
|
+
*
|
|
239
|
+
* Accepts a single request, notification, or response — and, for clients still
|
|
240
|
+
* on protocol 2025-03-26, a non-empty array of them. Every element of an array
|
|
241
|
+
* must be well-formed; one bad message rejects the whole POST, matching how the
|
|
242
|
+
* transport dispatches batches.
|
|
243
|
+
*
|
|
244
|
+
* @param body - The already-parsed JSON body of the POST.
|
|
245
|
+
* @returns `undefined` when the body is well-formed, otherwise the JSON-RPC
|
|
246
|
+
* `code`/`message` pair to return with HTTP 400.
|
|
247
|
+
*/
|
|
248
|
+
export function validateJsonRpcPayload(
|
|
249
|
+
body: unknown,
|
|
250
|
+
): { code: number; message: string } | undefined {
|
|
251
|
+
const messages = Array.isArray(body) ? body : [body];
|
|
252
|
+
if (messages.length === 0) {
|
|
253
|
+
return {
|
|
254
|
+
code: MCP_JSONRPC_ERROR.INVALID_REQUEST,
|
|
255
|
+
message: "Invalid Request: JSON-RPC batch must not be empty",
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
for (const message of messages) {
|
|
259
|
+
if (!JSONRPCMessageSchema.safeParse(message).success) {
|
|
260
|
+
return {
|
|
261
|
+
code: MCP_JSONRPC_ERROR.INVALID_REQUEST,
|
|
262
|
+
message:
|
|
263
|
+
"Invalid Request: body must be a JSON-RPC request, notification, or response",
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
return undefined;
|
|
268
|
+
}
|
|
269
|
+
|
|
129
270
|
/**
|
|
130
271
|
* A record in the shared (Redis-backed) MCP session registry. This is the
|
|
131
272
|
* cluster-wide source of truth for whether a Streamable HTTP session exists and
|
|
@@ -222,6 +363,7 @@ export function forgetMcpSession(
|
|
|
222
363
|
if (sessionId) api.mcp.transports.delete(sessionId);
|
|
223
364
|
const idx = api.mcp.mcpServers.indexOf(mcpServer);
|
|
224
365
|
if (idx !== -1) api.mcp.mcpServers.splice(idx, 1);
|
|
366
|
+
api.mcp.mcpServerAuth.delete(mcpServer);
|
|
225
367
|
}
|
|
226
368
|
|
|
227
369
|
/**
|
|
@@ -312,12 +454,15 @@ const adoptionsInFlight = new Map<
|
|
|
312
454
|
* @param sessionId - The transport session id to adopt.
|
|
313
455
|
* @param clientId - The OAuth client id that owns the session (from the registry record).
|
|
314
456
|
* @param protocolVersion - The negotiated protocol version from the registry record, if any.
|
|
457
|
+
* @param auth - The adopting request's user id / ip, captured so channel-broadcast
|
|
458
|
+
* authorization ({@link isMcpSessionAuthorizedForChannel}) works for this session too.
|
|
315
459
|
* @returns The connected, initialized transport (also registered in `api.mcp.transports`).
|
|
316
460
|
*/
|
|
317
461
|
export async function adoptMcpSession(
|
|
318
462
|
sessionId: string,
|
|
319
463
|
clientId: string,
|
|
320
464
|
protocolVersion: string | undefined,
|
|
465
|
+
auth?: Pick<McpSessionAuth, "userId" | "ip">,
|
|
321
466
|
): Promise<WebStandardStreamableHTTPServerTransport> {
|
|
322
467
|
const inFlight = adoptionsInFlight.get(sessionId);
|
|
323
468
|
if (inFlight) return inFlight;
|
|
@@ -325,6 +470,11 @@ export async function adoptMcpSession(
|
|
|
325
470
|
const promise = (async () => {
|
|
326
471
|
const mcpServer = createMcpServer();
|
|
327
472
|
api.mcp.mcpServers.push(mcpServer);
|
|
473
|
+
api.mcp.mcpServerAuth.set(mcpServer, {
|
|
474
|
+
clientId,
|
|
475
|
+
userId: auth?.userId,
|
|
476
|
+
ip: auth?.ip,
|
|
477
|
+
});
|
|
328
478
|
try {
|
|
329
479
|
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
330
480
|
sessionIdGenerator: () => sessionId,
|
|
@@ -424,7 +574,13 @@ function buildUiMeta(ui: McpUiConfig): Record<string, unknown> {
|
|
|
424
574
|
function registerTools(mcpServer: McpServer) {
|
|
425
575
|
const registered = new Set<string>();
|
|
426
576
|
for (const action of api.actions.actions) {
|
|
427
|
-
|
|
577
|
+
// Tools are opt-in: register only actions that explicitly set `mcp.tool =
|
|
578
|
+
// true`, or that declare an MCP App (`mcp.ui`) without opting out. Every
|
|
579
|
+
// other action — including those with no `mcp` config — is never exposed.
|
|
580
|
+
const isTool =
|
|
581
|
+
action.mcp?.tool === true ||
|
|
582
|
+
(action.mcp?.ui != null && action.mcp?.tool !== false);
|
|
583
|
+
if (!isTool) continue;
|
|
428
584
|
|
|
429
585
|
const toolName = formatToolName(action.name);
|
|
430
586
|
if (registered.has(toolName)) continue;
|
package/util/webResponse.ts
CHANGED
|
@@ -29,8 +29,14 @@ export const buildHeaders = (
|
|
|
29
29
|
"Access-Control-Allow-Methods": config.server.web.allowedMethods,
|
|
30
30
|
"Access-Control-Allow-Headers": config.server.web.allowedHeaders,
|
|
31
31
|
});
|
|
32
|
-
|
|
33
|
-
|
|
32
|
+
// Only attach credentials for a specific, allow-listed origin — never for the
|
|
33
|
+
// wildcard "*". Browsers forbid combining "*" with credentials, and reflecting
|
|
34
|
+
// an arbitrary origin alongside credentials would let any site read a victim's
|
|
35
|
+
// authenticated responses (see buildCorsHeaders in util/http.ts).
|
|
36
|
+
if (
|
|
37
|
+
cors["Access-Control-Allow-Origin"] &&
|
|
38
|
+
cors["Access-Control-Allow-Origin"] !== "*"
|
|
39
|
+
) {
|
|
34
40
|
cors["Access-Control-Allow-Credentials"] = "true";
|
|
35
41
|
}
|
|
36
42
|
Object.assign(headers, cors);
|