Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 | 9x 9x 9x 9x 9x 13x 3x 3x 2x 1x 10x 2x 8x 8x 8x 3x 4x 1x 3x 12x 12x 2x 10x 2x 8x 8x 8x 4x 4x 4x 4x 12x 12x 1x 3x 12x 3x 3x 3x 9x 7x 7x 7x 5x 5x 5x 5x 2x 7x 2x 7x 7x 7x 7x 7x 7x 6x 2x 4x 4x 2x 4x 7x 4x 4x 4x 3x 3x 3x 19x 19x 19x 19x 19x 1x 19x 19x 2x 19x 19x 10x 9x 9x 2x 9x 19x 9x 3x 3x 1x 2x 1x 1x 6x 6x 1x 5x | // SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
/**
* @module MCP/transport/gateway
* @description MCP Gateway HTTP transport helpers — connection initialisation,
* request dispatch, response validation, and Authorization header construction.
*
* Extracted from `connection.ts` to keep individual file sizes under 600 LOC.
* Operates on an explicit {@link GatewayContext} adapter rather than `this`.
*/
import type { JSONRPCRequest, JSONRPCResponse } from '../../types/index.js';
import { MCPSessionExpiredError, MCPRateLimitError } from './errors.js';
import {
parseRetryAfterMs,
formatRetryAfter,
RETRY_AFTER_HEADER,
RATE_LIMIT_MSG,
} from './retry-policy.js';
import { parseSSEResponse } from './sse-parser.js';
/** Default request timeout in milliseconds (EU Parliament APIs can take 30-120+ s). */
const DEFAULT_REQUEST_TIMEOUT_MS = 180_000;
/**
* Effective request timeout, configurable via `EP_REQUEST_TIMEOUT_MS` env var.
*/
export const GATEWAY_REQUEST_TIMEOUT_MS: number = (() => {
const envVal = process.env['EP_REQUEST_TIMEOUT_MS'];
Iif (envVal) {
const parsed = Number(envVal);
if (!Number.isNaN(parsed) && parsed > 0) return parsed;
}
return DEFAULT_REQUEST_TIMEOUT_MS;
})();
/**
* Adapter passed by MCPConnection to gateway helpers. Lets the helpers
* read & mutate the few connection-level fields they care about without
* pulling in the whole connection class.
*/
export interface GatewayContext {
readonly gatewayUrl: string | null;
readonly gatewayApiKey: string | null;
readonly serverLabel: string;
/** Current MCP session ID (may be updated by helpers via setMcpSessionId) */
readonly getMcpSessionId: () => string | null;
/** Increment the JSON-RPC request counter and return the next ID */
readonly nextRequestId: () => number;
/** Persist a new session ID (or clear it on 401) */
readonly setMcpSessionId: (id: string | null) => void;
/** Mark the underlying connection as (dis)connected */
readonly setConnected: (v: boolean) => void;
}
/**
* Validate a gateway response body, throwing on JSON-RPC errors.
*
* @param contentType - Response content-type header
* @param body - Raw response body text
*/
export function validateGatewayResponseBody(contentType: string, body: string): void {
if (contentType.includes('text/event-stream')) {
const parsed = parseSSEResponse(body);
if (parsed?.error) {
throw new Error(parsed.error.message ?? 'MCP gateway initialization error');
}
return;
}
if (!body) {
return;
}
try {
const jsonResponse = JSON.parse(body) as JSONRPCResponse;
if (jsonResponse.error) {
throw new Error(jsonResponse.error.message ?? 'MCP gateway initialization error');
}
} catch (e) {
if (e instanceof SyntaxError) {
// Non-JSON body — not a protocol error, safe to ignore
return;
}
throw e;
}
}
/**
* Build the Authorization header value for gateway requests.
*
* Keys that already contain a valid RFC 7235 scheme token followed by
* whitespace (e.g. "Bearer …", "Token …", "AWS4-HMAC-SHA256 …") are passed
* through unchanged. Otherwise the raw key is sent directly unless
* `EP_MCP_GATEWAY_AUTH_SCHEME` is set to a valid token, in which case that
* scheme prefix is prepended. The EP MCP gateway expects raw-token auth by
* default (no "Bearer " prefix).
*
* @param apiKey - Raw or pre-prefixed gateway API key
* @returns Authorization header value, or empty string for empty keys
* @throws {Error} When the API key contains CR or LF (header injection risk)
*/
export function buildAuthorizationHeader(apiKey: string): string {
const trimmedKey = apiKey.trim();
if (!trimmedKey) {
return '';
}
if (/[\r\n]/.test(trimmedKey)) {
throw new Error(
'Invalid gateway API key: control characters (CR/LF) are not allowed in Authorization header values.'
);
}
const tokenRegex = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
const firstSpaceIndex = trimmedKey.indexOf(' ');
if (firstSpaceIndex > 0) {
const possibleScheme = trimmedKey.slice(0, firstSpaceIndex);
Eif (tokenRegex.test(possibleScheme)) {
return trimmedKey;
}
}
const rawScheme = typeof process !== 'undefined' && process.env?.['EP_MCP_GATEWAY_AUTH_SCHEME'];
const scheme = typeof rawScheme === 'string' ? rawScheme.trim() : '';
if (scheme && tokenRegex.test(scheme)) {
return `${scheme} ${trimmedKey}`;
}
return trimmedKey;
}
/**
* Throw an appropriate error for a non-OK gateway response. Extracted to
* keep `sendGatewayRequest`'s cognitive complexity manageable.
*
* @param response - The non-OK fetch Response
* @param ctx - Gateway context (used to clear session on 401)
*/
export function throwGatewayResponseError(response: Response, ctx: GatewayContext): never {
if (response.status === 401) {
ctx.setMcpSessionId(null);
ctx.setConnected(false);
throw new MCPSessionExpiredError(response.statusText);
}
if (response.status === 429) {
const rawRetryAfter =
response.headers.get(RETRY_AFTER_HEADER) ?? response.headers.get('Retry-After');
const retryAfter = (rawRetryAfter ?? '').trim();
if (retryAfter !== '') {
const retryMessage = formatRetryAfter(retryAfter);
const retryAfterMs = parseRetryAfterMs(retryAfter);
console.warn(`⏳ ${RATE_LIMIT_MSG} ${retryMessage}`);
throw new MCPRateLimitError(retryAfterMs, `${RATE_LIMIT_MSG} ${retryMessage}`);
}
const statusText = response.statusText || 'Too Many Requests';
throw new MCPRateLimitError(
0,
`${RATE_LIMIT_MSG} (status ${response.status} ${statusText}; ${RETRY_AFTER_HEADER}/Retry-After header missing)`
);
}
throw new Error(`Gateway error ${response.status}: ${response.statusText}`);
}
/**
* Attempt a single connection via MCP Gateway (HTTP transport).
*
* @param ctx - Gateway context adapter from MCPConnection
*/
export async function attemptGatewayConnection(ctx: GatewayContext): Promise<void> {
Iif (!ctx.gatewayUrl) {
throw new Error(
'Gateway URL not configured. Set the EP_MCP_GATEWAY_URL environment variable or provide the gatewayUrl constructor option.'
);
}
try {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
};
Iif (ctx.gatewayApiKey) {
headers['Authorization'] = buildAuthorizationHeader(ctx.gatewayApiKey);
}
const initRequest: JSONRPCRequest = {
jsonrpc: '2.0',
id: ctx.nextRequestId(),
method: 'initialize',
params: {
protocolVersion: '2024-11-05',
capabilities: {},
clientInfo: { name: 'ep-mcp-client', version: '1.0.0' },
},
};
const response = await fetch(ctx.gatewayUrl, {
method: 'POST',
headers,
body: JSON.stringify(initRequest),
signal: AbortSignal.timeout(GATEWAY_REQUEST_TIMEOUT_MS),
});
if (!response.ok) {
throwGatewayResponseError(response, ctx);
}
const sessionId = response.headers.get('mcp-session-id');
if (sessionId) {
ctx.setMcpSessionId(sessionId);
}
const contentType = response.headers.get('content-type') ?? '';
const body = await response.text();
validateGatewayResponseBody(contentType, body);
ctx.setConnected(true);
console.log(`✅ Connected to ${ctx.serverLabel} via gateway`);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.error('❌ Failed to connect to MCP gateway:', message);
throw error;
}
}
/**
* Send a request via MCP Gateway (HTTP transport).
*
* @param method - RPC method name
* @param params - Method parameters
* @param ctx - Gateway context adapter
* @returns Server result payload
*/
export async function sendGatewayRequest(
method: string,
params: Record<string, unknown>,
ctx: GatewayContext
): Promise<unknown> {
Iif (!ctx.gatewayUrl) {
throw new Error(
'Gateway URL not configured. Set EP_MCP_GATEWAY_URL or provide gatewayUrl in MCP client options.'
);
}
const id = ctx.nextRequestId();
const request: JSONRPCRequest = {
jsonrpc: '2.0',
id,
method,
params,
};
const headers: Record<string, string> = {
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
};
if (ctx.gatewayApiKey) {
headers['Authorization'] = buildAuthorizationHeader(ctx.gatewayApiKey);
}
const sid = ctx.getMcpSessionId();
if (sid) {
headers['Mcp-Session-Id'] = sid;
}
const response = await fetch(ctx.gatewayUrl, {
method: 'POST',
headers,
body: JSON.stringify(request),
signal: AbortSignal.timeout(GATEWAY_REQUEST_TIMEOUT_MS),
});
if (!response.ok) {
throwGatewayResponseError(response, ctx);
}
const sessionId = response.headers.get('mcp-session-id');
if (sessionId) {
ctx.setMcpSessionId(sessionId);
}
const contentType = response.headers.get('content-type') ?? '';
const body = await response.text();
if (contentType.includes('text/event-stream')) {
const parsed = parseSSEResponse(body);
if (!parsed) {
throw new Error('Failed to parse SSE response from gateway');
}
if (parsed.error) {
throw new Error(parsed.error.message ?? 'MCP gateway error');
}
return parsed.result;
}
const jsonResponse = JSON.parse(body) as JSONRPCResponse;
if (jsonResponse.error) {
throw new Error(jsonResponse.error.message ?? 'MCP gateway error');
}
return jsonResponse.result;
}
|