package chattools import ( "context" "encoding/json" "net/http" "net/http/httptest" "strings" "testing" ) type fakeService struct { known map[string]bool calls []string } func (f *fakeService) Known(_ context.Context, token string) bool { return f.known[token] } func (f *fakeService) Call(_ context.Context, token, tool string, arguments json.RawMessage) Result { f.calls = append(f.calls, token+" "+tool+" "+string(arguments)) return Result{Text: "ok " + tool} } func post(t *testing.T, h Handler, token, body string, mutate func(*http.Request)) *httptest.ResponseRecorder { t.Helper() request := httptest.NewRequest(http.MethodPost, "/mcp/chat/"+token, strings.NewReader(body)) request.RemoteAddr = "127.0.0.1:50000" request.Header.Set("Content-Type", "application/json") request.Header.Set("Accept", "application/json, text/event-stream") if mutate != nil { mutate(request) } recorder := httptest.NewRecorder() h.ServeHTTP(recorder, request, token) return recorder } func decode(t *testing.T, recorder *httptest.ResponseRecorder) map[string]any { t.Helper() var out map[string]any if err := json.Unmarshal(recorder.Body.Bytes(), &out); err != nil { t.Fatalf("response %d %q: %v", recorder.Code, recorder.Body.String(), err) } return out } func TestHandshakeListAndCall(t *testing.T) { service := &fakeService{known: map[string]bool{"tok": true}} h := Handler{Service: service, Version: "1.2.3"} init := decode(t, post(t, h, "tok", `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"x","version":"1"}}}`, nil)) result := init["result"].(map[string]any) if result["protocolVersion"] != "2025-03-26" { t.Fatalf("a supported requested version must be echoed: %v", result) } if result["serverInfo"].(map[string]any)["name"] != ServerName || result["capabilities"].(map[string]any)["tools"] == nil { t.Fatalf("initialize result = %v", result) } unknown := decode(t, post(t, h, "tok", `{"jsonrpc":"2.0","id":2,"method":"initialize","params":{"protocolVersion":"1999-01-01"}}`, nil)) if unknown["result"].(map[string]any)["protocolVersion"] != LatestProtocolVersion { t.Fatalf("an unknown version must get the latest: %v", unknown) } if got := post(t, h, "tok", `{"jsonrpc":"2.0","method":"notifications/initialized"}`, nil); got.Code != http.StatusAccepted || got.Body.Len() != 0 { t.Fatalf("a notification must be 202 with no body: %d %q", got.Code, got.Body.String()) } list := decode(t, post(t, h, "tok", `{"jsonrpc":"2.0","id":"l","method":"tools/list"}`, nil)) tools := list["result"].(map[string]any)["tools"].([]any) var names []string for _, tool := range tools { entry := tool.(map[string]any) names = append(names, entry["name"].(string)) if entry["description"] == "" || entry["inputSchema"].(map[string]any)["type"] != "object" { t.Fatalf("tool without description or schema: %v", entry) } } if strings.Join(names, ",") != "show_file,show_image,show_html,notify" { t.Fatalf("tools = %v", names) } if list["id"] != "l" { t.Fatalf("a string id must be echoed: %v", list) } call := decode(t, post(t, h, "tok", `{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"show_html","arguments":{"html":"x"}}}`, nil)) content := call["result"].(map[string]any)["content"].([]any)[0].(map[string]any) if content["type"] != "text" || content["text"] != "ok show_html" || call["result"].(map[string]any)["isError"] != false { t.Fatalf("call result = %v", call) } if len(service.calls) != 1 || service.calls[0] != `tok show_html {"html":"x"}` { t.Fatalf("service calls = %v", service.calls) } bad := decode(t, post(t, h, "tok", `{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"rm_rf"}}`, nil)) if bad["error"].(map[string]any)["code"].(float64) != -32602 { t.Fatalf("an unknown tool must be invalid params: %v", bad) } missing := decode(t, post(t, h, "tok", `{"jsonrpc":"2.0","id":5,"method":"resources/list"}`, nil)) if missing["error"].(map[string]any)["code"].(float64) != -32601 { t.Fatalf("an unknown method must be method-not-found: %v", missing) } parse := decode(t, post(t, h, "tok", `[{"jsonrpc":"2.0","id":6,"method":"ping"}]`, nil)) if parse["error"].(map[string]any)["code"].(float64) != -32700 { t.Fatalf("a batch is refused: %v", parse) } if len(service.calls) != 1 { t.Fatalf("refused requests must not call tools: %v", service.calls) } } func TestEndpointRefusesUnknownTokensBrowsersRemotePeersAndGET(t *testing.T) { service := &fakeService{known: map[string]bool{"tok": true}} h := Handler{Service: service} ping := `{"jsonrpc":"2.0","id":1,"method":"ping"}` if got := post(t, h, "other", ping, nil); got.Code != http.StatusNotFound { t.Fatalf("unknown token = %d", got.Code) } if got := post(t, h, "tok", ping, func(r *http.Request) { r.Header.Set("Origin", "https://evil.example") }); got.Code != http.StatusForbidden { t.Fatalf("browser origin = %d", got.Code) } if got := post(t, h, "tok", ping, func(r *http.Request) { r.RemoteAddr = "100.64.0.9:4000" }); got.Code != http.StatusForbidden { t.Fatalf("remote peer = %d", got.Code) } if got := post(t, h, "tok", ping, func(r *http.Request) { r.RemoteAddr = "[::1]:4000" }); got.Code != http.StatusOK { t.Fatalf("IPv6 loopback = %d", got.Code) } if got := post(t, h, "tok", "", func(r *http.Request) { r.Method = http.MethodGet }); got.Code != http.StatusMethodNotAllowed { t.Fatalf("GET = %d", got.Code) } large := `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"show_html","arguments":{"html":"` + strings.Repeat("a", MaxRequestBytes) + `"}}}` if got := decode(t, post(t, h, "tok", large, nil)); got["error"] == nil { t.Fatalf("an oversized request must be refused: %v", got) } if len(service.calls) != 0 { t.Fatalf("refused requests reached the service: %v", service.calls) } } func TestHarnessRegistrationConfig(t *testing.T) { url := "http://127.0.0.1:8080/mcp/chat/abc" var claude map[string]map[string]map[string]string if err := json.Unmarshal([]byte(ClaudeMCPConfig(url)), &claude); err != nil { t.Fatal(err) } if got := claude["mcpServers"]["pipelines"]; got["type"] != "http" || got["url"] != url { t.Fatalf("claude config = %v", claude) } if ClaudeAllowedTools() != "mcp__pipelines" { t.Fatalf("claude allowed tools = %q", ClaudeAllowedTools()) } codex := CodexConfig(url)["mcp_servers"].(map[string]any)["pipelines"].(map[string]any) if codex["url"] != url { t.Fatalf("codex config = %v", codex) } open := OpenCodeConfig(url)["mcp"].(map[string]any)["pipelines"].(map[string]any) if open["type"] != "remote" || open["url"] != url || open["enabled"] != true { t.Fatalf("opencode config = %v", open) } for _, name := range HarnessToolNames(ToolShowFile) { if tool, ok := ToolFromHarnessName(name); !ok || tool != ToolShowFile { t.Fatalf("%s not recognised", name) } } for _, name := range []string{"pipelines_rm", "mcp__other__show_file", "show_file", "bash"} { if _, ok := ToolFromHarnessName(name); ok { t.Fatalf("%s must not be a Pipelines tool", name) } } }