-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp-proxy.ts
More file actions
118 lines (102 loc) · 3.6 KB
/
http-proxy.ts
File metadata and controls
118 lines (102 loc) · 3.6 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
// http-proxy.ts
// Proxy HTTP para MCP Server via stdio
import express from 'express';
import { spawn } from 'child_process';
const MCP_SERVER_CMD = 'npm';
const MCP_SERVER_ARGS = ['run', 'start:stdio']; // ou ajuste para o comando correto
// Utilitário para gerar IDs JSON-RPC
let rpcId = 1;
function nextId() {
return rpcId++;
}
// Função para enviar requisição JSON-RPC para o MCP server via stdio
function sendJsonRpc(proc: import('child_process').ChildProcess, method: string, params = {}) {
return new Promise((resolve, reject) => {
const id = nextId();
const req = JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n';
let resolved = false;
if (!proc.stdout || !proc.stdin) {
reject(new Error('MCP server process stdout ou stdin não disponível.'));
return;
}
console.log('[HTTP-PROXY] Enviando JSON-RPC:', { id, method, params });
function onData(data: { toString: () => string; }) {
const lines = data.toString().split('\n').filter(Boolean);
for (const line of lines) {
try {
const msg = JSON.parse(line);
if (msg.id === id) {
proc.stdout!.off('data', onData);
resolved = true;
console.log('[HTTP-PROXY] Resposta JSON-RPC:', msg);
resolve(msg.result);
}
} catch {}
}
}
proc.stdout.on('data', onData);
proc.stdin.write(req);
// Timeout de segurança
setTimeout(() => {
if (!resolved) {
proc.stdout!.off('data', onData);
reject(new Error('Timeout na resposta do MCP server'));
}
}, 10000);
});
}
// Inicializa o MCP server como subprocesso
const mcpProc = spawn(MCP_SERVER_CMD, MCP_SERVER_ARGS, { stdio: ['pipe', 'pipe', 'inherit'] });
const app = express();
app.use(express.json());
// Health check
app.get('/mcp/health', (req, res) => {
console.log('[HTTP-PROXY] GET /mcp/health');
res.json({ ok: true });
});
// Listar tools
app.get('/mcp/tools/list', async (req, res) => {
console.log('[HTTP-PROXY] GET /mcp/tools/list');
try {
const result = await sendJsonRpc(mcpProc, 'tools/list');
res.json({ tools: (result && Array.isArray((result as any).tools)) ? (result as any).tools : [] });
} catch (err) {
const errorMsg = err instanceof Error ? err.message : String(err);
console.log('[HTTP-PROXY] Erro /mcp/tools/list:', errorMsg);
res.status(500).json({ error: errorMsg });
}
});
// Executar tool
app.post('/mcp/tools/call', async (req, res) => {
console.log('[HTTP-PROXY] POST /mcp/tools/call', req.body);
try {
const { name, arguments: args } = req.body;
const result = await sendJsonRpc(mcpProc, 'tools/call', { name, arguments: args });
res.json({ result });
} catch (err) {
const errorMsg = err instanceof Error ? err.message : String(err);
console.log('[HTTP-PROXY] Erro /mcp/tools/call:', errorMsg);
res.status(500).json({ error: errorMsg });
}
});
// Listar resources
app.get('/mcp/resources/list', async (req, res) => {
try {
const result = await sendJsonRpc(mcpProc, 'resources/list') as any;
res.json({ resources: result && result.resources ? result.resources : [] });
} catch (err) {
const errorMsg = err instanceof Error ? err.message : String(err);
res.status(500).json({ error: errorMsg });
}
});
// Endpoint raiz para validação
app.get('/', (req, res) => {
res.json({ ok: true, message: 'MCP HTTP Proxy ativo' });
});
const PORT = 3333;
app.listen(PORT, () => {
console.log(`MCP HTTP Proxy rodando em http://localhost:${PORT}`);
});
app.listen(PORT, () => {
console.log(`MCP HTTP Proxy rodando em http://localhost:${PORT}`);
});