-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathmain.go
115 lines (98 loc) · 2.57 KB
/
main.go
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
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/anyisalin/mcp-openapi-to-mcp-adapter/utils"
"github.com/urfave/cli/v2"
)
func main() {
app := &cli.App{
Name: "mcp-link",
Usage: "Convert OpenAPI to MCP compatible endpoints",
Commands: []*cli.Command{
{
Name: "serve",
Usage: "Start the MCP Link server",
Flags: []cli.Flag{
&cli.IntFlag{
Name: "port",
Aliases: []string{"p"},
Value: 8080,
Usage: "Port to listen on",
},
&cli.StringFlag{
Name: "host",
Aliases: []string{"H"},
Value: "localhost",
Usage: "Host to listen on",
},
},
Action: func(c *cli.Context) error {
return runServer(c.String("host"), c.Int("port"))
},
},
},
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
func runServer(host string, port int) error {
// Create server address
addr := fmt.Sprintf("%s:%d", host, port)
// Configure the SSE server
ss := utils.NewSSEServer()
// Create HTTP server with CORS middleware
corsHandler := corsMiddleware(ss)
server := &http.Server{
Addr: addr,
Handler: corsHandler,
}
// Channel to listen for interrupt signals
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
// Start server in a goroutine
go func() {
fmt.Printf("Starting server on %s\n", addr)
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("Error starting server: %v\n", err)
}
}()
// Wait for interrupt signal
<-stop
// Create a deadline for graceful shutdown
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Shutdown the server
fmt.Println("Shutting down server...")
if err := ss.Shutdown(ctx); err != nil {
log.Fatalf("Error shutting down SSE server: %v\n", err)
}
if err := server.Shutdown(ctx); err != nil {
log.Fatalf("Error shutting down HTTP server: %v\n", err)
}
fmt.Println("Server gracefully stopped")
return nil
}
// corsMiddleware adds CORS headers to allow requests from any origin
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Set CORS headers
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "*")
w.Header().Set("Access-Control-Allow-Headers", "*")
// Handle preflight requests
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
// Pass the request to the next handler
next.ServeHTTP(w, r)
})
}