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 | 1x 1x 1x 1x 18x 18x 2x 16x 11x 7x 4x 8x 4x 4x 4x 2x 1x 1x 1x 2x 2x 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
* SDMX 3.0 REST API at `https://dataservices.imf.org/REST/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 `dataservices.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://dataservices.imf.org/REST/SDMX_3.0/`
* — all other URLs are rejected with an error message.
*
* ## 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 = 'dataservices.imf.org';
const IMF_ALLOWED_PATH_PREFIX = '/REST/SDMX_3.0/';
const IMF_ALLOWED_PROTOCOL = 'https:';
/** Per-request fetch timeout (ms). */
const FETCH_TIMEOUT_MS = 180_000;
// ─── 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://dataservices.imf.org/REST/SDMX_3.0/...`
*
* @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'],
},
},
],
},
};
}
/**
* 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.
*
* @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.
*/
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`,
},
};
}
try {
const response = await fetchImpl(url, {
headers: { Accept: 'application/json' },
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});
if (!response.ok) {
return {
jsonrpc: '2.0',
id,
error: { code: -1, message: `HTTP ${response.status} ${response.statusText}` },
};
}
const text = await response.text();
return {
jsonrpc: '2.0',
id,
result: { content: [{ type: 'text', text }] },
};
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
return { jsonrpc: '2.0', id, error: { code: -1, message } };
}
}
// ─── 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();
}
|