| 1 | package plugin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "strings" |
| 10 | "sync/atomic" |
| 11 | "testing" |
| 12 | "time" |
| 13 | |
| 14 | "reasonix/internal/tool" |
| 15 | ) |
| 16 | |
| 17 | // mcpHTTPServer is a minimal Streamable HTTP MCP server for tests. When sse is |
| 18 | // true it replies as text/event-stream (prefixing a server notification event |
| 19 | // to prove the client skips non-matching messages); otherwise application/json. |
| 20 | // It assigns a session id on initialize and fails any later request that |
| 21 | // doesn't echo it, and requires the Authorization header — so the test proves |
| 22 | // session + header plumbing, not just the happy path. |
| 23 | func mcpHTTPServer(t *testing.T, sse bool) *httptest.Server { |
| 24 | t.Helper() |
| 25 | const sessionID = "sess-xyz" |
| 26 | return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 27 | if got := r.Header.Get("Authorization"); got != "Bearer secret" { |
| 28 | http.Error(w, "missing auth", http.StatusUnauthorized) |
| 29 | return |
| 30 | } |
| 31 | var req struct { |
| 32 | ID *int `json:"id"` |
| 33 | Method string `json:"method"` |
| 34 | Params json.RawMessage `json:"params"` |
| 35 | } |
| 36 | if err := json.NewDecoder(r.Body).Decode(&req); err != nil { |
| 37 | http.Error(w, "bad body", http.StatusBadRequest) |
| 38 | return |
| 39 | } |
| 40 | |
| 41 | if req.Method == "initialize" { |
| 42 | w.Header().Set("Mcp-Session-Id", sessionID) |
| 43 | } else if got := r.Header.Get("Mcp-Session-Id"); got != sessionID { |
| 44 | http.Error(w, "missing session id", http.StatusBadRequest) |
| 45 | return |
| 46 | } |
| 47 | |
| 48 | if req.ID == nil { // notification |
| 49 | w.WriteHeader(http.StatusAccepted) |
| 50 | return |
| 51 | } |
| 52 | |
| 53 | var result any |
| 54 | progressToken := "" |
| 55 | switch req.Method { |
| 56 | case "initialize": |
| 57 | result = map[string]any{"protocolVersion": protocolVersion, "serverInfo": map[string]any{"name": "h", "version": "0"}} |
| 58 | case "tools/list": |
| 59 | result = map[string]any{"tools": []map[string]any{{ |
| 60 | "name": "greet", |
| 61 | "description": "Greet someone.", |
| 62 | "inputSchema": map[string]any{"type": "object"}, |
| 63 | "annotations": map[string]any{"readOnlyHint": true, "destructiveHint": true}, |
| 64 | }}} |
| 65 | case "tools/call": |
| 66 | var p struct { |
| 67 | Meta map[string]any `json:"_meta"` |
| 68 | Arguments struct { |
| 69 | Name string `json:"name"` |
| 70 | } `json:"arguments"` |
| 71 | } |
| 72 | _ = json.Unmarshal(req.Params, &p) |
| 73 | progressToken, _ = p.Meta["progressToken"].(string) |
| 74 | result = map[string]any{"content": []map[string]any{{"type": "text", "text": "hello " + p.Arguments.Name}}} |
| 75 | } |
| 76 | resp := map[string]any{"jsonrpc": "2.0", "id": *req.ID, "result": result} |
| 77 | b, _ := json.Marshal(resp) |
| 78 | |
| 79 | if sse { |
| 80 | w.Header().Set("Content-Type", "text/event-stream") |
| 81 | // A server notification first: the client must skip it and keep |
| 82 | // reading for the id-matching response. |
| 83 | fmt.Fprint(w, "event: message\ndata: {\"jsonrpc\":\"2.0\",\"method\":\"notifications/message\",\"params\":{}}\n\n") |
| 84 | if progressToken != "" { |
| 85 | progress, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "method": "notifications/progress", "params": map[string]any{ |
| 86 | "progressToken": progressToken, "progress": 3, "total": 4, "message": "Streaming", |
| 87 | }}) |
| 88 | fmt.Fprintf(w, "event: message\ndata: %s\n\n", progress) |
| 89 | } |
| 90 | fmt.Fprintf(w, "event: message\ndata: %s\n\n", b) |
| 91 | return |
| 92 | } |
| 93 | w.Header().Set("Content-Type", "application/json") |
| 94 | _, _ = w.Write(b) |
| 95 | })) |
| 96 | } |
| 97 | |
| 98 | func runHTTPTransportTest(t *testing.T, sse bool) { |
| 99 | srv := mcpHTTPServer(t, sse) |
| 100 | defer srv.Close() |
| 101 | |
| 102 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 103 | defer cancel() |
| 104 | |
| 105 | host, tools, err := StartAll(ctx, []Spec{{ |
| 106 | Name: "h", |
| 107 | Type: "http", |
| 108 | URL: srv.URL, |
| 109 | Headers: map[string]string{"Authorization": "Bearer secret"}, |
| 110 | }}) |
| 111 | if err != nil { |
| 112 | t.Fatalf("StartAll: %v", err) |
| 113 | } |
| 114 | defer host.Close() |
| 115 | |
| 116 | if len(tools) != 1 || tools[0].Name() != "mcp__h__greet" { |
| 117 | t.Fatalf("tools = %v, want [mcp__h__greet]", names(tools)) |
| 118 | } |
| 119 | if !tools[0].ReadOnly() { |
| 120 | t.Error("readOnlyHint not honoured over HTTP") |
| 121 | } |
| 122 | annotations, ok := tools[0].(tool.MCPAnnotations) |
| 123 | if !ok || !annotations.MCPDestructiveHint() { |
| 124 | t.Error("destructiveHint not honoured over HTTP") |
| 125 | } |
| 126 | progress := make(chan string, 1) |
| 127 | executeCtx := tool.WithProgress(ctx, func(chunk string) { progress <- chunk }) |
| 128 | got, err := tools[0].Execute(executeCtx, json.RawMessage(`{"name":"sam"}`)) |
| 129 | if err != nil { |
| 130 | t.Fatalf("Execute: %v", err) |
| 131 | } |
| 132 | if got != "hello sam" { |
| 133 | t.Errorf("Execute = %q, want %q", got, "hello sam") |
| 134 | } |
| 135 | if sse { |
| 136 | select { |
| 137 | case chunk := <-progress: |
| 138 | if chunk != "Streaming (3/4)\n" { |
| 139 | t.Fatalf("progress = %q", chunk) |
| 140 | } |
| 141 | case <-time.After(time.Second): |
| 142 | t.Fatal("Streamable HTTP progress notification was not routed") |
| 143 | } |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | func TestStreamableHTTPAnswersRootsRequestInSSEResponse(t *testing.T) { |
| 148 | workspaceRoot := t.TempDir() |
| 149 | reply := make(chan struct { |
| 150 | ID string `json:"id"` |
| 151 | Result struct { |
| 152 | Roots []mcpRoot `json:"roots"` |
| 153 | } `json:"result"` |
| 154 | }, 1) |
| 155 | server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 156 | var response struct { |
| 157 | ID string `json:"id"` |
| 158 | Result struct { |
| 159 | Roots []mcpRoot `json:"roots"` |
| 160 | } `json:"result"` |
| 161 | } |
| 162 | if err := json.NewDecoder(r.Body).Decode(&response); err != nil { |
| 163 | http.Error(w, err.Error(), http.StatusBadRequest) |
| 164 | return |
| 165 | } |
| 166 | reply <- response |
| 167 | w.WriteHeader(http.StatusAccepted) |
| 168 | })) |
| 169 | defer server.Close() |
| 170 | transport, err := newHTTPTransport(Spec{Name: "roots", URL: server.URL, WorkspaceRoot: workspaceRoot}) |
| 171 | if err != nil { |
| 172 | t.Fatal(err) |
| 173 | } |
| 174 | defer transport.close() |
| 175 | stream := strings.NewReader("data: {\"jsonrpc\":\"2.0\",\"id\":\"server-roots\",\"method\":\"roots/list\"}\n\n" + |
| 176 | "data: {\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{}}\n\n") |
| 177 | if _, err := transport.readSSEResponse(context.Background(), stream, 1); err != nil { |
| 178 | t.Fatal(err) |
| 179 | } |
| 180 | got := <-reply |
| 181 | want := mcpRoots(workspaceRoot) |
| 182 | if got.ID != "server-roots" || len(got.Result.Roots) != 1 || got.Result.Roots[0] != want[0] { |
| 183 | t.Fatalf("roots response = %+v, want %+v", got, want) |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | func TestHTTPTransportJSON(t *testing.T) { runHTTPTransportTest(t, false) } |
| 188 | func TestHTTPTransportSSE(t *testing.T) { runHTTPTransportTest(t, true) } |
| 189 | |
| 190 | func TestHTTPTransportDoesNotRedirectCredentialsAcrossOrigins(t *testing.T) { |
| 191 | var targetCalls atomic.Int32 |
| 192 | target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 193 | targetCalls.Add(1) |
| 194 | if got := r.Header.Get("X-API-Key"); got != "" { |
| 195 | t.Errorf("redirect target received credential header %q", got) |
| 196 | } |
| 197 | w.WriteHeader(http.StatusOK) |
| 198 | })) |
| 199 | defer target.Close() |
| 200 | source := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 201 | http.Redirect(w, r, target.URL+"/mcp", http.StatusTemporaryRedirect) |
| 202 | })) |
| 203 | defer source.Close() |
| 204 | |
| 205 | transport, err := newHTTPTransport(Spec{ |
| 206 | Name: "redirect", Type: "http", URL: source.URL, |
| 207 | Headers: map[string]string{"X-API-Key": "secret"}, |
| 208 | }) |
| 209 | if err != nil { |
| 210 | t.Fatal(err) |
| 211 | } |
| 212 | resp, err := transport.do(context.Background(), []byte(`{}`)) |
| 213 | if err != nil { |
| 214 | t.Fatal(err) |
| 215 | } |
| 216 | defer resp.Body.Close() |
| 217 | if resp.StatusCode != http.StatusTemporaryRedirect { |
| 218 | t.Fatalf("cross-origin redirect status = %d, want %d", resp.StatusCode, http.StatusTemporaryRedirect) |
| 219 | } |
| 220 | if targetCalls.Load() != 0 { |
| 221 | t.Fatalf("cross-origin redirect target received %d requests", targetCalls.Load()) |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | func TestHTTPTransportReinitializesExpiredSession(t *testing.T) { |
| 226 | var initializeCount atomic.Int32 |
| 227 | var toolCallCount atomic.Int32 |
| 228 | |
| 229 | srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 230 | var req struct { |
| 231 | ID *int `json:"id"` |
| 232 | Method string `json:"method"` |
| 233 | Params json.RawMessage `json:"params"` |
| 234 | } |
| 235 | if err := json.NewDecoder(r.Body).Decode(&req); err != nil { |
| 236 | http.Error(w, "bad body", http.StatusBadRequest) |
| 237 | return |
| 238 | } |
| 239 | |
| 240 | if req.Method == "initialize" { |
| 241 | n := initializeCount.Add(1) |
| 242 | w.Header().Set("Mcp-Session-Id", fmt.Sprintf("sess-%d", n)) |
| 243 | writeHTTPRPCResult(w, req.ID, map[string]any{ |
| 244 | "protocolVersion": protocolVersion, |
| 245 | "serverInfo": map[string]any{"name": "h", "version": "0"}, |
| 246 | }) |
| 247 | return |
| 248 | } |
| 249 | |
| 250 | expectedSession := fmt.Sprintf("sess-%d", initializeCount.Load()) |
| 251 | if got := r.Header.Get("Mcp-Session-Id"); got != expectedSession { |
| 252 | http.Error(w, "missing session id", http.StatusBadRequest) |
| 253 | return |
| 254 | } |
| 255 | |
| 256 | if req.ID == nil { // notifications/initialized |
| 257 | w.WriteHeader(http.StatusAccepted) |
| 258 | return |
| 259 | } |
| 260 | |
| 261 | switch req.Method { |
| 262 | case "tools/list": |
| 263 | writeHTTPRPCResult(w, req.ID, map[string]any{"tools": []map[string]any{{ |
| 264 | "name": "greet", |
| 265 | "description": "Greet someone.", |
| 266 | "inputSchema": map[string]any{"type": "object"}, |
| 267 | }}}) |
| 268 | case "tools/call": |
| 269 | n := toolCallCount.Add(1) |
| 270 | if n == 1 { |
| 271 | w.Header().Set("Content-Type", "application/json") |
| 272 | w.WriteHeader(http.StatusNotFound) |
| 273 | fmt.Fprintf(w, `{"jsonrpc":"2.0","id":%d,"error":{"code":-32001,"message":"Session not found"}}`, *req.ID) |
| 274 | return |
| 275 | } |
| 276 | if got := r.Header.Get("Mcp-Session-Id"); got != "sess-2" { |
| 277 | http.Error(w, "retry did not use the new session", http.StatusBadRequest) |
| 278 | return |
| 279 | } |
| 280 | writeHTTPRPCResult(w, req.ID, map[string]any{ |
| 281 | "content": []map[string]any{{"type": "text", "text": "hello retry"}}, |
| 282 | }) |
| 283 | default: |
| 284 | http.Error(w, "unknown method", http.StatusBadRequest) |
| 285 | } |
| 286 | })) |
| 287 | defer srv.Close() |
| 288 | |
| 289 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 290 | defer cancel() |
| 291 | |
| 292 | host, tools, err := StartAll(ctx, []Spec{{Name: "h", Type: "http", URL: srv.URL}}) |
| 293 | if err != nil { |
| 294 | t.Fatalf("StartAll: %v", err) |
| 295 | } |
| 296 | defer host.Close() |
| 297 | host.mu.RLock() |
| 298 | client := host.clients[0] |
| 299 | host.mu.RUnlock() |
| 300 | |
| 301 | done := make(chan struct{}) |
| 302 | readerDone := make(chan struct{}) |
| 303 | go func() { |
| 304 | defer close(readerDone) |
| 305 | for { |
| 306 | select { |
| 307 | case <-done: |
| 308 | return |
| 309 | default: |
| 310 | _, _ = client.hasPrompts, client.hasResources |
| 311 | } |
| 312 | } |
| 313 | }() |
| 314 | defer func() { |
| 315 | close(done) |
| 316 | <-readerDone |
| 317 | }() |
| 318 | |
| 319 | got, err := tools[0].Execute(ctx, json.RawMessage(`{"name":"sam"}`)) |
| 320 | if err != nil { |
| 321 | t.Fatalf("Execute after expired session: %v", err) |
| 322 | } |
| 323 | if got != "hello retry" { |
| 324 | t.Errorf("Execute = %q, want %q", got, "hello retry") |
| 325 | } |
| 326 | if got := initializeCount.Load(); got != 2 { |
| 327 | t.Errorf("initialize count = %d, want 2", got) |
| 328 | } |
| 329 | if got := toolCallCount.Load(); got != 2 { |
| 330 | t.Errorf("tools/call count = %d, want 2", got) |
| 331 | } |
| 332 | } |
| 333 | |
| 334 | // TestHTTPTransportRPCError checks a JSON-RPC error response surfaces as an |
| 335 | // error rather than an empty result. |
| 336 | func TestHTTPTransportRPCError(t *testing.T) { |
| 337 | srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 338 | var req struct { |
| 339 | ID *int `json:"id"` |
| 340 | } |
| 341 | _ = json.NewDecoder(r.Body).Decode(&req) |
| 342 | if req.ID == nil { |
| 343 | w.WriteHeader(http.StatusAccepted) |
| 344 | return |
| 345 | } |
| 346 | w.Header().Set("Content-Type", "application/json") |
| 347 | fmt.Fprintf(w, `{"jsonrpc":"2.0","id":%d,"error":{"code":-32000,"message":"boom"}}`, *req.ID) |
| 348 | })) |
| 349 | defer srv.Close() |
| 350 | |
| 351 | ctx := context.Background() |
| 352 | _, _, err := StartAll(ctx, []Spec{{Name: "e", Type: "http", URL: srv.URL}}) |
| 353 | if err == nil || !strings.Contains(err.Error(), "boom") { |
| 354 | t.Fatalf("want initialize to fail with rpc error, got %v", err) |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | // TestSSETransportUnsupported documents that the legacy sse transport is |
| 359 | // recognised but deferred with a clear, actionable error. |
| 360 | func TestSSETransportUnsupported(t *testing.T) { |
| 361 | _, _, err := StartAll(context.Background(), []Spec{{Name: "legacy", Type: "sse", URL: "http://x"}}) |
| 362 | if err == nil || !strings.Contains(err.Error(), "http") { |
| 363 | t.Fatalf("sse should error pointing to http, got %v", err) |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | func writeHTTPRPCResult(w http.ResponseWriter, id *int, result any) { |
| 368 | if id == nil { |
| 369 | w.WriteHeader(http.StatusAccepted) |
| 370 | return |
| 371 | } |
| 372 | resp := map[string]any{"jsonrpc": "2.0", "id": *id, "result": result} |
| 373 | w.Header().Set("Content-Type", "application/json") |
| 374 | _ = json.NewEncoder(w).Encode(resp) |
| 375 | } |
| 376 | |
| 377 | func names(ts []tool.Tool) []string { |
| 378 | out := make([]string, len(ts)) |
| 379 | for i, t := range ts { |
| 380 | out[i] = t.Name() |
| 381 | } |
| 382 | return out |
| 383 | } |
| 384 |