package mcp_test import ( "bytes" "encoding/json" "net/http" "net/http/httptest" "strings" "testing" "github.com/mathiasbq/hyperguild/ingestion/internal/mcp" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func body(t *testing.T, v any) *bytes.Buffer { t.Helper() b, err := json.Marshal(v) require.NoError(t, err) return bytes.NewBuffer(b) } func TestServerInitialize(t *testing.T) { srv := mcp.NewServer(t.TempDir(), nil, nil) req := httptest.NewRequest(http.MethodPost, "/mcp", body(t, map[string]any{ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": map[string]any{}, })) rr := httptest.NewRecorder() srv.ServeHTTP(rr, req) assert.Equal(t, http.StatusOK, rr.Code) var resp map[string]any require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &resp)) result := resp["result"].(map[string]any) assert.Equal(t, "2024-11-05", result["protocolVersion"]) } func TestServerToolsList(t *testing.T) { srv := mcp.NewServer(t.TempDir(), nil, nil) req := httptest.NewRequest(http.MethodPost, "/mcp", body(t, map[string]any{ "jsonrpc": "2.0", "id": 2, "method": "tools/list", })) rr := httptest.NewRecorder() srv.ServeHTTP(rr, req) assert.Equal(t, http.StatusOK, rr.Code) var resp map[string]any require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &resp)) tools := resp["result"].(map[string]any)["tools"].([]any) names := make([]string, 0, len(tools)) for _, t := range tools { names = append(names, t.(map[string]any)["name"].(string)) } assert.ElementsMatch(t, []string{ "brain_query", "brain_write", "brain_ingest_raw", "brain_ingest", "session_log", }, names) } func TestServerNotificationGetsNoBody(t *testing.T) { srv := mcp.NewServer(t.TempDir(), nil, nil) req := httptest.NewRequest(http.MethodPost, "/mcp", body(t, map[string]any{ "jsonrpc": "2.0", "method": "notifications/initialized", })) rr := httptest.NewRecorder() srv.ServeHTTP(rr, req) assert.Equal(t, http.StatusOK, rr.Code) assert.Empty(t, strings.TrimSpace(rr.Body.String())) } func TestServerUnknownMethodReturnsError(t *testing.T) { srv := mcp.NewServer(t.TempDir(), nil, nil) req := httptest.NewRequest(http.MethodPost, "/mcp", body(t, map[string]any{ "jsonrpc": "2.0", "id": 3, "method": "unknown/method", })) rr := httptest.NewRecorder() srv.ServeHTTP(rr, req) assert.Equal(t, http.StatusOK, rr.Code) var resp map[string]any require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &resp)) require.NotNil(t, resp["error"]) errObj := resp["error"].(map[string]any) assert.Equal(t, float64(-32601), errObj["code"]) assert.Contains(t, errObj["message"].(string), "unknown/method") }