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 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 | 1x 1x 1x 1x 1x 1x 1x 28x 28x 2x 26x 11x 7x 4x 12x 12x 12x 24x 10x 12x 15x 15x 9x 15x 11x 3x 8x 1x 7x 2x 5x 16x 4x 12x 12x 16x 15x 15x 15x 11x 11x 11x 3x 8x 3x 5x 4x 4x 4x 4x 4x 4x 5x 9x 5x 5x 5x 10x 10x 10x 10x 10x 10x 4x 5x 4x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 5x 1x | // SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
/**
* @module MCP/FetchProxyServer
* @description IMF-only MCP fetch-proxy server.
*
* Implements the Model Context Protocol (JSON-RPC 2.0 over stdio) with a
* single tool — `fetch_url` — that proxies HTTPS GET requests to the IMF
* Data Portal SDMX 3.0 REST API at `https://api.imf.org/external/sdmx/3.0/`.
*
* ## Why this exists
*
* The Agent Workflow Firewall (AWF) runs a Squid proxy that blocks outbound
* HTTPS even to allowlisted domains such as `api.imf.org`. This server is
* mounted as an MCP container in gh-aw workflows; because MCP containers
* run in a Docker network with direct outbound access (bypassing Squid),
* `fetch_url` can reach the IMF API while the main runner cannot.
*
* The server only allows calls to `https://api.imf.org/external/sdmx/3.0/`
* — SDMX 2.1 paths and any other URLs are rejected with an error message.
*
* ## Authentication
*
* The IMF Data Portal API is fronted by Azure API Management and requires
* a subscription key in the `Ocp-Apim-Subscription-Key` header for every
* request. The server reads the key from `IMF_API_PRIMARY_KEY` (with
* `IMF_API_SECONDARY_KEY` as a warm-standby fallback used on `401`/`403`
* responses to enable zero-downtime key rotation). When neither env var
* is set, the request is sent unauthenticated and IMF will return `204`
* (no subscription matched) — useful for diagnosing auth misconfiguration.
*
* The header is injected server-side; agent prompts never see the key.
*
* ## Usage
*
* ```
* node scripts/mcp/fetch-proxy-server.js
* ```
*
* Or via `node -e <inlined-code>` in the gh-aw `entrypointArgs` (see
* `.github/workflows/shared/mcp/news-mcp-servers.md`).
*
* ## MCP tools exposed
*
* - `fetch_url` — fetches an IMF SDMX URL and returns its body as text.
*
* @author Hack23 AB
* @license Apache-2.0
*/
import * as readline from 'node:readline';
// ─── Constants ────────────────────────────────────────────────────────────────
const IMF_ALLOWED_HOSTNAME = 'api.imf.org';
const IMF_ALLOWED_PATH_PREFIX = '/external/sdmx/3.0/';
const IMF_ALLOWED_PROTOCOL = 'https:';
/** Per-request fetch timeout (ms). */
const FETCH_TIMEOUT_MS = 180_000;
/** Product identifier sent to IMF SDMX endpoints. */
const IMF_USER_AGENT = 'euparliamentmonitor/0.9.0 (+https://github.com/Hack23/euparliamentmonitor)';
/** Common headers for IMF SDMX REST requests (auth header added per-request). */
const IMF_REQUEST_HEADERS: Readonly<Record<string, string>> = Object.freeze({
Accept: 'application/json, application/vnd.sdmx.data+json, */*;q=0.8',
'User-Agent': IMF_USER_AGENT,
'Accept-Language': 'en-US,en;q=0.9',
'Cache-Control': 'no-cache',
});
/** Azure APIM subscription-key header expected by `api.imf.org`. */
const IMF_SUBSCRIPTION_KEY_HEADER = 'Ocp-Apim-Subscription-Key';
// ─── Types ───────────────────────────────────────────────────────────────────
/** JSON-RPC 2.0 request (minimal surface). */
export interface JsonRpcRequest {
jsonrpc: '2.0';
id: number | string | null;
method: string;
params?: Record<string, unknown>;
}
/** JSON-RPC 2.0 response (success). */
export interface JsonRpcSuccess {
jsonrpc: '2.0';
id: number | string | null;
result: unknown;
}
/** JSON-RPC 2.0 response (error). */
export interface JsonRpcError {
jsonrpc: '2.0';
id: number | string | null;
error: { code: number; message: string };
}
/** MCP tool-call content item. */
export interface McpContentItem {
type: 'text';
text: string;
}
/** MCP tool-call result envelope. */
export interface McpToolResult {
content: McpContentItem[];
}
// ─── Allowlist check ─────────────────────────────────────────────────────────
/**
* Returns `true` when `url` is allowed by the IMF-only fetch-proxy policy.
*
* Allowed: `https://api.imf.org/external/sdmx/3.0/...` (SDMX 2.1 rejected).
*
* @param url - Raw URL string to validate.
* @returns Whether the URL is permitted.
*/
export function isAllowedImfUrl(url: string): boolean {
let parsed: URL;
try {
parsed = new URL(url);
} catch {
return false;
}
return (
parsed.protocol === IMF_ALLOWED_PROTOCOL &&
parsed.hostname === IMF_ALLOWED_HOSTNAME &&
(parsed.port === '' || parsed.port === '443') &&
parsed.username === '' &&
parsed.password === '' &&
parsed.pathname.startsWith(IMF_ALLOWED_PATH_PREFIX)
);
}
// ─── Transport helpers ───────────────────────────────────────────────────────
/**
* Serialize a JSON-RPC response to a newline-terminated string.
*
* Uses `String.fromCharCode(10)` instead of `'\n'` so that inlined
* (minified) versions of this code remain safe in single-quoted strings
* (the AWF YAML serializer rejects bare newlines in entrypointArgs).
*
* @param obj - Serializable object.
* @returns `JSON.stringify(obj) + '\n'`
*/
export function toWire(obj: unknown): string {
return JSON.stringify(obj) + String.fromCharCode(10);
}
// ─── MCP handlers ────────────────────────────────────────────────────────────
/**
* Build a success response for the `initialize` handshake.
*
* @param id - Request id to echo.
* @returns JSON-RPC success with MCP 2024-11-05 capabilities.
*/
export function handleInitialize(id: number | string | null): JsonRpcSuccess {
return {
jsonrpc: '2.0',
id,
result: {
protocolVersion: '2024-11-05',
capabilities: { tools: {} },
},
};
}
/**
* Build the `tools/list` response advertising the single `fetch_url` tool.
*
* @param id - Request id to echo.
* @returns JSON-RPC success with the tool descriptor array.
*/
export function handleToolsList(id: number | string | null): JsonRpcSuccess {
return {
jsonrpc: '2.0',
id,
result: {
tools: [
{
name: 'fetch_url',
description: 'Fetch an IMF SDMX URL and return its content',
inputSchema: {
type: 'object',
properties: {
url: {
type: 'string',
description: 'IMF SDMX URL to fetch',
},
},
required: ['url'],
},
},
],
},
};
}
/**
* Read IMF subscription keys from the environment, in priority order.
*
* Returns up to two keys: the primary (first attempt) and the secondary
* (used to retry on `401`/`403` so live key rotation never breaks a run).
* Empty / unset keys are filtered out so `[]` is returned only when no
* key is configured at all.
*
* @returns Ordered list of candidate API keys (length 0–2).
* @internal
*/
function readImfSubscriptionKeys(): readonly string[] {
const candidates = [process.env['IMF_API_PRIMARY_KEY'], process.env['IMF_API_SECONDARY_KEY']];
const keys: string[] = [];
for (const k of candidates) {
if (typeof k === 'string' && k.length > 0 && !keys.includes(k)) {
keys.push(k);
}
}
return keys;
}
/**
* Build the request headers for an outbound IMF call. The `Ocp-Apim-Subscription-Key`
* header is added when a key is supplied; otherwise the request is sent
* unauthenticated (and IMF will return `204 No Content`).
*
* @param key - Subscription key, or `undefined` to send unauthenticated.
* @returns Plain object suitable for `fetch(..., { headers })`.
* @internal
*/
function buildImfHeaders(key: string | undefined): Record<string, string> {
const headers: Record<string, string> = { ...IMF_REQUEST_HEADERS };
if (key !== undefined && key.length > 0) {
headers[IMF_SUBSCRIPTION_KEY_HEADER] = key;
}
return headers;
}
/**
* Execute the `fetch_url` tool call.
*
* Only URLs matching the IMF SDMX 3.0 allowlist are permitted. Non-matching
* or malformed URLs receive a JSON-RPC error response; HTTP errors and network
* failures also surface as errors.
*
* The `Ocp-Apim-Subscription-Key` header is injected from `IMF_API_PRIMARY_KEY`
* (with `IMF_API_SECONDARY_KEY` as a fallback retried once on `401`/`403`).
*
* @param id - Request id to echo.
* @param url - URL to fetch.
* @param fetchImpl - Injectable `fetch` implementation (defaults to global).
* @returns JSON-RPC success or error.
*/
type FetchAttemptResponse = {
ok: boolean;
status: number;
statusText: string;
text: () => Promise<string>;
};
type FetchAttemptOutcome =
| { kind: 'ok'; text: string }
| { kind: 'auth-retry'; response: FetchAttemptResponse }
| { kind: 'error'; rpcError: { code: number; message: string }; response?: FetchAttemptResponse };
/**
* Classify a single `fetch()` response from `api.imf.org` so
* {@link handleFetchUrl} can decide whether to rotate keys, return
* success, or surface an explicit error.
*
* - `204 No Content` → explicit error (Azure APIM accepted the request
* but no Ocp-Apim-Subscription-Key matched; without this guard the
* empty body would be indistinguishable from a successful 200).
* - `401`/`403` with another key available → auth-retry signal.
* - Any other non-2xx → error with the HTTP status.
*
* @internal Exported for tests.
*
* @param response - The HTTP response returned by `fetch()`.
* @param hasNextAttempt - `true` when another subscription key is available for retry.
* @returns A classified outcome — `'ok'` with body text, `'auth-retry'` to rotate keys,
* or `'error'` with a JSON-RPC error envelope.
*/
async function classifyFetchResponse(
response: FetchAttemptResponse,
hasNextAttempt: boolean
): Promise<FetchAttemptOutcome> {
if ((response.status === 401 || response.status === 403) && hasNextAttempt) {
return { kind: 'auth-retry', response };
}
if (response.status === 204) {
return {
kind: 'error',
rpcError: {
code: -1,
message: `HTTP 204 No Content from ${IMF_ALLOWED_HOSTNAME} — likely missing or invalid ${IMF_SUBSCRIPTION_KEY_HEADER} (set IMF_API_PRIMARY_KEY)`,
},
response,
};
}
if (!response.ok) {
return {
kind: 'error',
rpcError: { code: -1, message: `HTTP ${response.status} ${response.statusText}` },
response,
};
}
return { kind: 'ok', text: await response.text() };
}
/**
* JSON-RPC handler for the proxy's `fetch_url` method.
*
* Validates the requested URL against the IMF allow-list (protocol, hostname,
* path prefix), forwards it via `fetchImpl`, and returns the response body
* wrapped in a JSON-RPC success envelope. Disallowed URLs return a JSON-RPC
* error envelope rather than throwing.
*
* @param id - JSON-RPC request id to echo back in the response.
* @param url - Absolute URL the agent is requesting.
* @param fetchImpl - `fetch` implementation (overridable for tests).
* @returns A JSON-RPC success envelope with the response body, or an error
* envelope describing why the URL was rejected.
*/
export async function handleFetchUrl(
id: number | string | null,
url: string | undefined,
fetchImpl: typeof fetch = globalThis.fetch
): Promise<JsonRpcSuccess | JsonRpcError> {
if (!url || !isAllowedImfUrl(url)) {
return {
jsonrpc: '2.0',
id,
error: {
code: -1,
message: `fetch_url only allows ${IMF_ALLOWED_PROTOCOL}//${IMF_ALLOWED_HOSTNAME}${IMF_ALLOWED_PATH_PREFIX} URLs`,
},
};
}
const keys = readImfSubscriptionKeys();
const attempts: (string | undefined)[] = keys.length > 0 ? [...keys] : [undefined];
let lastResponse: FetchAttemptResponse | undefined;
let lastError: unknown;
for (let i = 0; i < attempts.length; i += 1) {
const key = attempts[i];
try {
const response = (await fetchImpl(url, {
headers: buildImfHeaders(key),
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
})) as FetchAttemptResponse;
lastResponse = response;
const outcome = await classifyFetchResponse(response, i + 1 < attempts.length);
if (outcome.kind === 'auth-retry') {
continue;
}
if (outcome.kind === 'error') {
return { jsonrpc: '2.0', id, error: outcome.rpcError };
}
return {
jsonrpc: '2.0',
id,
result: { content: [{ type: 'text', text: outcome.text }] },
};
} catch (err) {
lastError = err;
lastResponse = undefined;
break;
}
}
Eif (lastError !== undefined) {
const message = lastError instanceof Error ? lastError.message : String(lastError);
return { jsonrpc: '2.0', id, error: { code: -1, message } };
}
if (lastResponse !== undefined && !lastResponse.ok) {
return {
jsonrpc: '2.0',
id,
error: {
code: -1,
message: `HTTP ${lastResponse.status} ${lastResponse.statusText}`,
},
};
}
return {
jsonrpc: '2.0',
id,
error: { code: -1, message: 'fetch_url failed without a response' },
};
}
// ─── Main server loop ─────────────────────────────────────────────────────────
/**
* Run the fetch-proxy MCP server, reading JSON-RPC messages from `input` and
* writing responses to `output`.
*
* Does not resolve until the input stream closes.
*
* @param input - Readable stream to read JSON-RPC lines from (default: stdin).
* @param output - Writable stream to write responses to (default: stdout).
* @param fetchImpl - Injectable fetch (default: global fetch).
* @returns Promise that resolves when the input stream closes.
*/
export function runServer(
input: NodeJS.ReadableStream = process.stdin,
output: NodeJS.WritableStream = process.stdout,
fetchImpl: typeof fetch = globalThis.fetch
): Promise<void> {
const send = (obj: unknown): void => {
output.write(toWire(obj));
};
const rl = readline.createInterface({ input, terminal: false });
return new Promise((resolve) => {
rl.on('line', (line: string) => {
let requestId: number | string | null = null;
void (async () => {
try {
const msg = JSON.parse(line) as JsonRpcRequest;
requestId = msg.id ?? null;
if (msg.method === 'initialize') {
send(handleInitialize(msg.id ?? null));
} else if (msg.method === 'notifications/initialized') {
// No-op — notification, no response required.
} else if (msg.method === 'tools/list') {
send(handleToolsList(msg.id ?? null));
} else if (msg.method === 'tools/call') {
const params = msg.params as
| { name?: string; arguments?: { url?: string } }
| undefined;
if (params?.name === 'fetch_url') {
const url = params.arguments?.url;
const result = await handleFetchUrl(msg.id ?? null, url, fetchImpl);
send(result);
} else E{
send({
jsonrpc: '2.0',
id: msg.id ?? null,
result: { content: [{ type: 'text', text: 'unknown tool' }] },
});
}
} else {
send({
jsonrpc: '2.0',
id: msg.id ?? null,
result: { content: [{ type: 'text', text: 'unknown method' }] },
});
}
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
send({ jsonrpc: '2.0', id: requestId, error: { code: -1, message } });
}
})();
});
rl.on('close', resolve);
});
}
// ─── Entry point ─────────────────────────────────────────────────────────────
// Run when executed directly (not imported as a module).
Iif (
process.argv[1] !== undefined &&
(process.argv[1].endsWith('fetch-proxy-server.js') ||
process.argv[1].endsWith('fetch-proxy-server.ts'))
) {
void runServer();
}
|