package server import ( "context" "encoding/json" "net/http" "net/http/httptest" "path/filepath" "strings" "testing" "time" "git.a-wan.net/alan/pipelines/internal/chattools" "git.a-wan.net/alan/pipelines/internal/pipeline" ) // The endpoint is served on the server's own listener: a harness registers // the URL the registry issues and calls show_html over it. func TestChatToolsEndpointOnTheServerListener(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() store, err := pipeline.Open(filepath.Join(t.TempDir(), "tools-http.db")) if err != nil { t.Fatal(err) } defer store.Close() handler := HandlerWithOptions(ctx, Options{}, store) defer func() { cancel(); WaitRuns(handler) }() srv := httptest.NewServer(handler) defer srv.Close() if err := ConfigureChatTools(store, strings.TrimPrefix(srv.URL, "http://")); err != nil { t.Fatal(err) } defer chattools.Configure(nil) url, err := chattools.Current().SessionURL("ses_http") if err != nil || !strings.HasPrefix(url, srv.URL+"/mcp/chat/") { t.Fatalf("session url = %q %v", url, err) } rpc := func(target, body string) (int, map[string]any) { request, _ := http.NewRequestWithContext(ctx, http.MethodPost, target, strings.NewReader(body)) request.Header.Set("Content-Type", "application/json") request.Header.Set("Accept", "application/json, text/event-stream") response, err := http.DefaultClient.Do(request) if err != nil { t.Fatal(err) } defer response.Body.Close() var out map[string]any _ = json.NewDecoder(response.Body).Decode(&out) return response.StatusCode, out } if code, out := rpc(url, `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}`); code != 200 || out["result"] == nil { t.Fatalf("initialize = %d %v", code, out) } code, out := rpc(url, `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"show_html","arguments":{"html":""}}}`) if code != 200 || out["result"].(map[string]any)["isError"] != false { t.Fatalf("tools/call = %d %v", code, out) } if items, _ := store.ChatShownItems(ctx, "ses_http"); len(items) != 1 { t.Fatalf("items = %v", items) } if code, _ := rpc(srv.URL+"/mcp/chat/"+strings.Repeat("f", 64), `{"jsonrpc":"2.0","id":1,"method":"ping"}`); code != http.StatusNotFound { t.Fatalf("unknown token = %d", code) } } func TestLoopbackBase(t *testing.T) { for addr, want := range map[string]string{ "127.0.0.1:8080": "http://127.0.0.1:8080", ":8080": "http://127.0.0.1:8080", "0.0.0.0:9": "http://127.0.0.1:9", "[::]:9": "http://127.0.0.1:9", "[::1]:9": "http://[::1]:9", "localhost:7": "http://localhost:7", } { if got, err := loopbackBase(addr); err != nil || got != want { t.Fatalf("%s = %q %v", addr, got, err) } } if _, err := loopbackBase("100.64.0.2:8080"); err == nil { t.Fatal("a non-loopback listener cannot serve the loopback-only endpoint") } }