-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
303 lines (256 loc) · 7.76 KB
/
main.go
File metadata and controls
303 lines (256 loc) · 7.76 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
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
package main
import (
"bufio"
"bytes"
"context"
"embed"
"encoding/json"
"flag"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
"github.com/wailsapp/wails/v2"
"github.com/wailsapp/wails/v2/pkg/options"
"github.com/wailsapp/wails/v2/pkg/options/assetserver"
"github.com/wailsapp/wails/v2/pkg/options/mac"
"neobelt/internal/app"
)
//go:embed all:frontend/dist
var assets embed.FS
// JSON-RPC 2.0 message structures
type JSONRPCMessage struct {
JSONRPC string `json:"jsonrpc"`
ID interface{} `json:"id,omitempty"`
Method string `json:"method,omitempty"`
Params json.RawMessage `json:"params,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Error *JSONRPCError `json:"error,omitempty"`
}
type JSONRPCError struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
}
// MCPProxy handles the stdio <-> HTTP bridging
type MCPProxy struct {
targetURL string
headers map[string]string
httpClient *http.Client
}
func NewMCPProxy(targetURL string, headersList []string) *MCPProxy {
headers := make(map[string]string)
for _, header := range headersList {
parts := strings.SplitN(header, ":", 2)
if len(parts) == 2 {
headers[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1])
}
}
return &MCPProxy{
targetURL: targetURL,
headers: headers,
httpClient: &http.Client{Timeout: 30 * time.Second},
}
}
func main() {
// Check if CLI arguments are provided
if len(os.Args) > 1 {
runCLI()
return
}
// Create an instance of the app structure
application := app.NewApp()
// Create application with options
err := wails.Run(&options.App{
Title: "neobelt",
Width: 1280,
MinWidth: 1280,
Height: 768,
AssetServer: &assetserver.Options{
Assets: assets,
},
BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1},
OnStartup: application.Startup,
Bind: []interface{}{
application,
},
Mac: &mac.Options{
About: &mac.AboutInfo{
Title: "Neobelt",
Message: "Neobelt is a tool for managing your MCP servers.",
},
},
})
if err != nil {
println("Error:", err.Error())
}
}
type headerFlag []string
func (h *headerFlag) String() string {
return strings.Join(*h, ",")
}
func (h *headerFlag) Set(value string) error {
*h = append(*h, value)
return nil
}
func runCLI() {
var headers headerFlag
var mcpProxy bool
// Create a new flag set for CLI commands
cliFlags := flag.NewFlagSet("neobelt", flag.ExitOnError)
cliFlags.BoolVar(&mcpProxy, "mcp-proxy", false, "Start MCP proxy server")
cliFlags.Var(&headers, "h", "Add HTTP header (can be used multiple times)")
cliFlags.Var(&headers, "header", "Add HTTP header (can be used multiple times)")
// Parse CLI arguments (skip program name)
cliFlags.Parse(os.Args[1:])
if mcpProxy {
args := cliFlags.Args()
if len(args) == 0 {
fmt.Fprintln(os.Stderr, "Error: MCP proxy requires a target URL")
fmt.Fprintln(os.Stderr, "Usage: neobelt --mcp-proxy -h \"Authorization: Bearer TOKEN\" https://mcp-server.tld/mcp")
os.Exit(1)
}
targetURL := args[0]
startMCPProxy(targetURL, headers)
return
}
// Show help if no recognized command
fmt.Fprintln(os.Stderr, "Neobelt CLI")
fmt.Fprintln(os.Stderr, "Usage:")
fmt.Fprintln(os.Stderr, " neobelt --mcp-proxy -h \"Header: Value\" <target-url>")
}
// Start the MCP proxy server
func (p *MCPProxy) Start(ctx context.Context) error {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line := scanner.Text()
if strings.TrimSpace(line) == "" {
continue
}
// Parse JSON-RPC message from stdin
var message JSONRPCMessage
if err := json.Unmarshal([]byte(line), &message); err != nil {
// Send error response to stdout
errorResponse := JSONRPCMessage{
JSONRPC: "2.0",
ID: nil,
Error: &JSONRPCError{
Code: -32700,
Message: "Parse error",
Data: err.Error(),
},
}
p.sendResponse(errorResponse)
continue
}
// Forward message to HTTP endpoint
response, err := p.forwardToHTTP(ctx, message)
if err != nil {
// Send error response to stdout
errorResponse := JSONRPCMessage{
JSONRPC: "2.0",
ID: message.ID,
Error: &JSONRPCError{
Code: -32603,
Message: "Internal error",
Data: err.Error(),
},
}
p.sendResponse(errorResponse)
continue
}
// Send response back to stdout
p.sendResponse(response)
}
return scanner.Err()
}
// Forward JSON-RPC message to HTTP endpoint
func (p *MCPProxy) forwardToHTTP(ctx context.Context, message JSONRPCMessage) (JSONRPCMessage, error) {
// Serialize message
messageBytes, err := json.Marshal(message)
if err != nil {
return JSONRPCMessage{}, fmt.Errorf("failed to marshal message: %w", err)
}
// Create HTTP request
req, err := http.NewRequestWithContext(ctx, "POST", p.targetURL, bytes.NewReader(messageBytes))
if err != nil {
return JSONRPCMessage{}, fmt.Errorf("failed to create request: %w", err)
}
// Set headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json, text/event-stream")
for key, value := range p.headers {
req.Header.Set(key, value)
}
// Send request
resp, err := p.httpClient.Do(req)
if err != nil {
return JSONRPCMessage{}, fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()
// Read response
body, err := io.ReadAll(resp.Body)
if err != nil {
return JSONRPCMessage{}, fmt.Errorf("failed to read response: %w", err)
}
// Check HTTP status
if resp.StatusCode != http.StatusOK {
fmt.Fprintf(os.Stderr, "HTTP error %d: %s\n", resp.StatusCode, string(body))
return JSONRPCMessage{}, fmt.Errorf("HTTP error: %d %s", resp.StatusCode, string(body))
}
// Log response for debugging
fmt.Fprintf(os.Stderr, "Raw HTTP response: %s\n", string(body))
// Parse JSON-RPC response
var response JSONRPCMessage
if err := json.Unmarshal(body, &response); err != nil {
// Try parsing as SSE format
fmt.Fprintf(os.Stderr, "Direct JSON parse failed, trying SSE format...\n")
jsonData, sseErr := parseSSEResponse(body)
if sseErr != nil {
fmt.Fprintf(os.Stderr, "SSE parse error: %v, Raw response: %s\n", sseErr, string(body))
return JSONRPCMessage{}, fmt.Errorf("failed to parse response as JSON or SSE: %w", err)
}
// Try parsing the extracted JSON data
if err := json.Unmarshal(jsonData, &response); err != nil {
fmt.Fprintf(os.Stderr, "JSON parse error from SSE data: %v, Extracted JSON: %s\n", err, string(jsonData))
return JSONRPCMessage{}, fmt.Errorf("failed to parse extracted JSON from SSE: %w", err)
}
fmt.Fprintf(os.Stderr, "Successfully parsed SSE response\n")
}
return response, nil
}
// parseSSEResponse extracts JSON data from Server-Sent Events format
func parseSSEResponse(body []byte) ([]byte, error) {
bodyStr := string(body)
lines := strings.Split(bodyStr, "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "data: ") {
// Extract JSON from "data: {json...}" line
jsonData := strings.TrimPrefix(line, "data: ")
return []byte(jsonData), nil
}
}
return nil, fmt.Errorf("no data field found in SSE response")
}
// Send JSON-RPC response to stdout
func (p *MCPProxy) sendResponse(message JSONRPCMessage) {
responseBytes, err := json.Marshal(message)
if err != nil {
fmt.Fprintf(os.Stderr, "Error marshaling response: %v\n", err)
return
}
fmt.Println(string(responseBytes))
}
func startMCPProxy(targetURL string, headers []string) {
proxy := NewMCPProxy(targetURL, headers)
ctx := context.Background()
// Log to stderr that proxy is starting (for debugging)
fmt.Fprintf(os.Stderr, "MCP Proxy starting, target URL: %s\n", targetURL)
if err := proxy.Start(ctx); err != nil {
fmt.Fprintf(os.Stderr, "Proxy error: %v\n", err)
os.Exit(1)
}
}