#!/usr/bin/env node
import { fileURLToPath } from "url";
import path from "path";
import fs from "fs";
// Simple argument parser
const args = process.argv.slice(2);
const urlArgIndex = args.indexOf("--url");
const keyArgIndex = args.indexOf("--key");
const SERVER_URL =
urlArgIndex !== -1 ? args[urlArgIndex + 1] : process.env.MCP_SERVER_URL;
const API_KEY =
keyArgIndex !== -1 ? args[keyArgIndex + 1] : process.env.MCP_API_KEY;
if (!SERVER_URL) {
console.error("Error: Missing Server URL. Use --url or set MCP_SERVER_URL.");
process.exit(1);
}
if (!API_KEY) {
console.error("Error: Missing API Key. Use --key or set MCP_API_KEY.");
process.exit(1);
}
// Log to stderr so it doesn't interfere with StdIO transport
function log(msg: string) {
console.warn(`[Bridge] ${msg}`);
}
log(`Connecting to ${SERVER_URL}...`);
// Buffer for handling split chunks
let buffer = "";
process.stdin.on("data", async (chunk) => {
buffer += chunk.toString();
// Process full lines (JSON-RPC messages are usually newline delimited)
const lines = buffer.split("\n");
buffer = lines.pop() || ""; // Keep the last incomplete chunk
for (const line of lines) {
if (!line.trim()) continue;
try {
const message = JSON.parse(line);
// Forward to Remote Server
// We use the /mcp endpoint strictly for JSON-RPC
await forwardMessage(message);
} catch (err) {
log(`Error parsing JSON: ${(err as Error).message}`);
}
}
});
async function forwardMessage(message: any) {
try {
const response = await fetch(`${SERVER_URL}/mcp`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": API_KEY || "",
},
body: JSON.stringify(message),
});
if (!response.ok) {
const text = await response.text();
throw new Error(`Server returned ${response.status}: ${text}`);
}
const json = await response.json();
// Write response to stdout
process.stdout.write(JSON.stringify(json) + "\n");
} catch (err) {
log(`Error forwarding message: ${(err as Error).message}`);
// Try to report error back to client if it's a request
if (message.id) {
const errorResponse = {
jsonrpc: "2.0",
id: message.id,
error: {
code: -32603,
message: `Bridge Error: ${(err as Error).message}`,
},
};
process.stdout.write(JSON.stringify(errorResponse) + "\n");
}
}
}
log("Bridge Ready. Waiting for input...");