-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_http.go
More file actions
247 lines (217 loc) · 7.01 KB
/
Copy pathserver_http.go
File metadata and controls
247 lines (217 loc) · 7.01 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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
"sync"
"time"
"github.com/google/uuid"
)
// ── HTTP Session ──────────────────────────────────────────────────────────────
type HTTPSession struct {
ID string
Created time.Time
mu sync.Mutex
}
func NewHTTPSession() *HTTPSession {
return &HTTPSession{
ID: uuid.NewString(),
Created: time.Now(),
}
}
// ── HTTP Server (Streamable HTTP transport) ───────────────────────────────────
type HTTPServer struct {
Sessions sync.Map // map[string]*HTTPSession
APIKey string
}
func NewHTTPServer(apiKey string) *HTTPServer {
return &HTTPServer{APIKey: apiKey}
}
// bearerAuth checks for a valid Bearer token.
func (s *HTTPServer) bearerAuth(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if s.APIKey == "" {
next(w, r)
return
}
auth := r.Header.Get("Authorization")
if auth == "" {
http.Error(w, `{"error":"missing Authorization header"}`, http.StatusUnauthorized)
return
}
const prefix = "Bearer "
if len(auth) < len(prefix) || auth[:len(prefix)] != prefix {
http.Error(w, `{"error":"invalid Authorization header, expected Bearer token"}`, http.StatusUnauthorized)
return
}
token := auth[len(prefix):]
if token != s.APIKey {
http.Error(w, `{"error":"invalid API key"}`, http.StatusUnauthorized)
return
}
next(w, r)
}
}
// corsMiddlewareHTTP adds CORS headers for browser-based clients.
func corsMiddlewareHTTP(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, Mcp-Session-Id, Accept")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusNoContent)
return
}
next(w, r)
}
}
// validateSession checks the Mcp-Session-Id header and returns the session if valid.
func (s *HTTPServer) validateSession(r *http.Request) (*HTTPSession, bool) {
sessionID := r.Header.Get("Mcp-Session-Id")
if sessionID == "" {
return nil, false
}
val, ok := s.Sessions.Load(sessionID)
if !ok {
return nil, false
}
return val.(*HTTPSession), true
}
// handleMCPPost handles POST /mcp — receives JSON-RPC requests and returns responses.
func (s *HTTPServer) handleMCPPost(w http.ResponseWriter, r *http.Request) {
var req JSONRPCRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `{"error":"invalid JSON: %s"}`, err.Error())
return
}
// Check if this is an initialize request
isInitialize := req.Method == "initialize"
if isInitialize {
// Create a new session
session := NewHTTPSession()
s.Sessions.Store(session.ID, session)
w.Header().Set("Mcp-Session-Id", session.ID)
} else {
// Validate session for non-initialize requests
if _, ok := s.validateSession(r); !ok {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, `{"error":"Invalid or missing Mcp-Session-Id header. Send an 'initialize' request first."}`)
return
}
}
resp := handleRequest(req)
// Check if this is a notification (no ID field)
isNotification := len(req.ID) == 0
if isNotification {
w.WriteHeader(http.StatusAccepted)
return
}
// Determine response format based on Accept header
accept := r.Header.Get("Accept")
if strings.Contains(accept, "text/event-stream") && !strings.Contains(accept, "application/json") {
// Client only accepts SSE — wrap response in SSE format
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
respBytes, _ := json.Marshal(resp)
fmt.Fprintf(w, "data: %s\n\n", respBytes)
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
} else {
// Default: return JSON directly
w.Header().Set("Content-Type", "application/json")
respBytes, err := json.Marshal(resp)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, `{"error":"failed to marshal response"}`)
return
}
w.Write(respBytes)
}
}
// handleMCPGet handles GET /mcp — opens an SSE stream for server-to-client notifications.
func (s *HTTPServer) handleMCPGet(w http.ResponseWriter, r *http.Request) {
// Validate session
if _, ok := s.validateSession(r); !ok {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, `{"error":"Invalid or missing Mcp-Session-Id header"}`)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("X-Accel-Buffering", "no")
// Heartbeat to keep connection alive
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
ctx := r.Context()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
fmt.Fprintf(w, ": heartbeat\n\n")
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
}
}
}
// handleMCPDelete handles DELETE /mcp — terminates a session.
func (s *HTTPServer) handleMCPDelete(w http.ResponseWriter, r *http.Request) {
sessionID := r.Header.Get("Mcp-Session-Id")
if sessionID == "" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, `{"error":"missing Mcp-Session-Id header"}`)
return
}
if _, ok := s.Sessions.LoadAndDelete(sessionID); !ok {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, `{"error":"invalid or expired session"}`)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, `{"status":"session terminated"}`)
}
// handleMCP routes to the appropriate handler based on HTTP method.
func (s *HTTPServer) handleMCP(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodPost:
s.handleMCPPost(w, r)
case http.MethodGet:
s.handleMCPGet(w, r)
case http.MethodDelete:
s.handleMCPDelete(w, r)
default:
w.Header().Set("Allow", "GET, POST, DELETE")
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
// Start starts the HTTP server on the given address.
func (s *HTTPServer) Start(addr string) error {
mux := http.NewServeMux()
mux.HandleFunc("/mcp", corsMiddlewareHTTP(s.bearerAuth(s.handleMCP)))
log.Printf("WordPress MCP HTTP server listening on %s", addr)
log.Printf("MCP endpoint: http://%s/mcp", addr)
if s.APIKey != "" {
log.Printf("Auth: Bearer token required")
} else {
log.Printf("WARNING: No API key set — server is open to all connections!")
}
srv := &http.Server{
Addr: addr,
Handler: mux,
ReadHeaderTimeout: 10 * time.Second,
}
return srv.ListenAndServe()
}