-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathmcp-proxy.mjs
More file actions
157 lines (136 loc) · 4.62 KB
/
mcp-proxy.mjs
File metadata and controls
157 lines (136 loc) · 4.62 KB
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
#!/usr/bin/env node
// Stdio-to-HTTP proxy for Claude Desktop / Claude Code.
// Translates MCP stdio transport into HTTP calls against the SSE server.
//
// Claude Desktop config (~/.claude/claude_desktop_config.json):
// {
// "mcpServers": {
// "python-build-tools": {
// "command": "node",
// "args": ["/path/to/supertokens-python/mcp-proxy.mjs"],
// "env": { "MCP_URL": "http://localhost:3000" }
// }
// }
// }
import { stdin, stdout, stderr } from "process";
import { createInterface } from "readline";
import { readFileSync } from "node:fs";
import { resolve, dirname } from "node:path";
import { fileURLToPath } from "node:url";
function getDefaultPort() {
try {
const __dirname = dirname(fileURLToPath(import.meta.url));
const content = readFileSync(resolve(__dirname, "mcp.env"), "utf8");
const match = content.match(/^MCP_PORT=(\d+)/m);
if (match) return match[1];
} catch {}
return "3001";
}
const MCP_URL = process.env.MCP_URL
|| `http://localhost:${process.env.MCP_PORT || getDefaultPort()}`;
const SSE_URL = `${MCP_URL}/sse`;
const MESSAGES_URL = `${MCP_URL}/messages`;
let sessionId = null;
// ---------------------------------------------------------------------------
// SSE client — connects to the MCP server's /sse endpoint
// ---------------------------------------------------------------------------
async function connectSSE() {
stderr.write(`[mcp-proxy] Connecting to ${SSE_URL}\n`);
const resp = await fetch(SSE_URL, {
headers: { Accept: "text/event-stream" },
});
if (!resp.ok) {
throw new Error(`SSE connection failed: ${resp.status} ${resp.statusText}`);
}
const reader = resp.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
(async () => {
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() || "";
let eventType = null;
let data = "";
for (const line of lines) {
if (line.startsWith("event:")) {
eventType = line.slice(6).trim();
} else if (line.startsWith("data:")) {
data = line.slice(5).trim();
} else if (line === "") {
// End of event
if (eventType === "endpoint") {
// Extract session ID from the endpoint URL
const match = data.match(/sessionId=([^&]+)/);
if (match) {
sessionId = match[1];
stderr.write(`[mcp-proxy] Session: ${sessionId}\n`);
}
} else if (eventType === "message") {
// Forward MCP message to stdout
try {
const msg = JSON.parse(data);
stdout.write(JSON.stringify(msg) + "\n");
} catch {
stderr.write(`[mcp-proxy] Bad SSE message: ${data}\n`);
}
}
eventType = null;
data = "";
}
}
}
} catch (err) {
stderr.write(`[mcp-proxy] SSE read error: ${err.message}\n`);
process.exit(1);
}
})();
// Wait for session ID
for (let i = 0; i < 50; i++) {
if (sessionId) return;
await new Promise((r) => setTimeout(r, 100));
}
throw new Error("Timed out waiting for SSE session ID");
}
// ---------------------------------------------------------------------------
// Forward stdin (MCP messages) to HTTP POST /messages
// ---------------------------------------------------------------------------
async function forwardStdin() {
const rl = createInterface({ input: stdin });
for await (const line of rl) {
if (!line.trim()) continue;
try {
const msg = JSON.parse(line);
const url = `${MESSAGES_URL}?sessionId=${sessionId}`;
const resp = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(msg),
});
if (!resp.ok) {
stderr.write(
`[mcp-proxy] POST error: ${resp.status} ${await resp.text()}\n`
);
}
} catch (err) {
stderr.write(`[mcp-proxy] Forward error: ${err.message}\n`);
}
}
}
// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------
async function main() {
try {
await connectSSE();
stderr.write("[mcp-proxy] Connected, forwarding stdio <-> HTTP\n");
await forwardStdin();
} catch (err) {
stderr.write(`[mcp-proxy] Fatal: ${err.message}\n`);
process.exit(1);
}
}
main();