package mcp import ( "encoding/json" "net/http" "net/http/httptest" "path/filepath" "reflect" "strings" "testing" "github.com/yuanyuanxiang/SimpleRemoter/server/go/logger" ) const testToken = "0123456789abcdef0123456789abcdef" func testServer(t *testing.T, readonly bool) *Server { t.Helper() log := logger.New(logger.Config{ Level: logger.LevelError, File: filepath.Join(t.TempDir(), "mcp-test.log"), }) return New(Config{ Token: testToken, Readonly: readonly, Version: "test-1.0", Log: log, }) } // rpcEnvelope decodes a JSON-RPC response without committing to a result type. type rpcEnvelope struct { JSONRPC string `json:"jsonrpc"` ID json.RawMessage `json:"id"` Result json.RawMessage `json:"result"` Error *rpcError `json:"error"` } func call(t *testing.T, s *Server, body string) *httptest.ResponseRecorder { t.Helper() req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(body)) req.Header.Set("Content-Type", "application/json") rec := httptest.NewRecorder() s.Handle(rec, req) return rec } func authedCall(t *testing.T, s *Server, body string) *httptest.ResponseRecorder { t.Helper() req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(body)) req.Header.Set("Authorization", "Bearer "+testToken) req.Header.Set("Content-Type", "application/json") rec := httptest.NewRecorder() s.Handle(rec, req) return rec } func decodeEnvelope(t *testing.T, rec *httptest.ResponseRecorder) rpcEnvelope { t.Helper() var env rpcEnvelope if err := json.Unmarshal(rec.Body.Bytes(), &env); err != nil { t.Fatalf("response is not JSON: %v\nbody: %s", err, rec.Body.String()) } return env } func TestEnabledRequiresToken(t *testing.T) { if New(Config{}).Enabled() { t.Fatal("endpoint without a token must report disabled") } if !testServer(t, false).Enabled() { t.Fatal("endpoint with a token must report enabled") } } func TestAuth(t *testing.T) { s := testServer(t, false) body := `{"jsonrpc":"2.0","id":1,"method":"ping"}` t.Run("missing", func(t *testing.T) { rec := call(t, s, body) if rec.Code != http.StatusUnauthorized { t.Fatalf("status = %d, want 401", rec.Code) } if got := rec.Header().Get("WWW-Authenticate"); !strings.Contains(got, "Bearer") { t.Fatalf("WWW-Authenticate = %q, want a Bearer challenge", got) } if strings.Contains(rec.Body.String(), "jsonrpc") { t.Fatalf("401 must not carry a JSON-RPC body: %s", rec.Body.String()) } }) t.Run("wrong same length", func(t *testing.T) { req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(body)) req.Header.Set("Authorization", "Bearer "+strings.Repeat("f", len(testToken))) rec := httptest.NewRecorder() s.Handle(rec, req) if rec.Code != http.StatusUnauthorized { t.Fatalf("status = %d, want 401", rec.Code) } }) t.Run("wrong different length", func(t *testing.T) { req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(body)) req.Header.Set("Authorization", "Bearer "+testToken+"x") rec := httptest.NewRecorder() s.Handle(rec, req) if rec.Code != http.StatusUnauthorized { t.Fatalf("status = %d, want 401", rec.Code) } }) t.Run("missing scheme", func(t *testing.T) { req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(body)) req.Header.Set("Authorization", testToken) rec := httptest.NewRecorder() s.Handle(rec, req) if rec.Code != http.StatusUnauthorized { t.Fatalf("status = %d, want 401", rec.Code) } }) t.Run("correct", func(t *testing.T) { rec := authedCall(t, s, body) if rec.Code != http.StatusOK { t.Fatalf("status = %d, want 200 (body: %s)", rec.Code, rec.Body.String()) } if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/json") { t.Fatalf("Content-Type = %q, want application/json", ct) } }) } func TestInitialize(t *testing.T) { s := testServer(t, false) rec := authedCall(t, s, `{"jsonrpc":"2.0","id":7,"method":"initialize"}`) if rec.Code != http.StatusOK { t.Fatalf("status = %d, want 200", rec.Code) } env := decodeEnvelope(t, rec) if env.Error != nil { t.Fatalf("unexpected error: %+v", env.Error) } if string(env.ID) != "7" { t.Fatalf("id = %s, want 7", env.ID) } var result struct { ProtocolVersion string `json:"protocolVersion"` Capabilities struct { Tools struct { ListChanged bool `json:"listChanged"` } `json:"tools"` } `json:"capabilities"` ServerInfo struct { Name string `json:"name"` Version string `json:"version"` } `json:"serverInfo"` Instructions string `json:"instructions"` } if err := json.Unmarshal(env.Result, &result); err != nil { t.Fatalf("decode result: %v", err) } if result.ProtocolVersion != protocolVersion { t.Fatalf("protocolVersion = %q, want %q", result.ProtocolVersion, protocolVersion) } if result.Capabilities.Tools.ListChanged { t.Fatal("tools.listChanged must be false: the list is static") } if result.ServerInfo.Name != "yama" { t.Fatalf("serverInfo.name = %q, want yama", result.ServerInfo.Name) } if result.ServerInfo.Version != "test-1.0" { t.Fatalf("serverInfo.version = %q, want test-1.0", result.ServerInfo.Version) } if strings.TrimSpace(result.Instructions) == "" { t.Fatal("instructions must not be empty") } } func TestPing(t *testing.T) { s := testServer(t, false) env := decodeEnvelope(t, authedCall(t, s, `{"jsonrpc":"2.0","id":"abc","method":"ping"}`)) if env.Error != nil { t.Fatalf("unexpected error: %+v", env.Error) } if string(env.ID) != `"abc"` { t.Fatalf("id = %s, want \"abc\" (string ids echo unchanged)", env.ID) } var result map[string]any if err := json.Unmarshal(env.Result, &result); err != nil { t.Fatalf("decode result: %v", err) } if len(result) != 0 { t.Fatalf("ping result = %v, want empty object", result) } } func listTools(t *testing.T, s *Server) []json.RawMessage { t.Helper() env := decodeEnvelope(t, authedCall(t, s, `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`)) if env.Error != nil { t.Fatalf("tools/list error: %+v", env.Error) } var result struct { Tools []json.RawMessage `json:"tools"` } if err := json.Unmarshal(env.Result, &result); err != nil { t.Fatalf("decode result: %v", err) } return result.Tools } // TestToolsListMatchesEmbedded pins the published definitions to the embedded // file: same order, same content, no annotations. tools_minimal.json in turn is // checked against mcp/tools.json by gen_go_tools.py --check. func TestToolsListMatchesEmbedded(t *testing.T) { var want []any if err := json.Unmarshal(toolsJSON, &want); err != nil { t.Fatalf("embedded tools: %v", err) } for _, readonly := range []bool{false, true} { got := listTools(t, testServer(t, readonly)) if readonly { if len(got) != 7 { t.Fatalf("readonly tools = %d, want 7", len(got)) } } else if len(got) != len(want) { t.Fatalf("tools = %d, want %d", len(got), len(want)) } wantIdx := 0 for _, raw := range got { var tool map[string]any if err := json.Unmarshal(raw, &tool); err != nil { t.Fatalf("tool is not an object: %v", err) } name, _ := tool["name"].(string) if _, ok := tool["annotations"]; ok { t.Fatalf("tool %s must not carry annotations (MFC compatibility)", name) } if readonly && (name == "terminal_exec" || name == "terminal_close") { t.Fatalf("readonly mode must hide %s", name) } // Skip over tools the filter removed, keeping the order check. for wantIdx < len(want) && want[wantIdx].(map[string]any)["name"] != name { wantIdx++ } if wantIdx == len(want) { t.Fatalf("tool %s is not in tools_minimal.json in this order", name) } if !reflect.DeepEqual(tool, want[wantIdx]) { t.Fatalf("tool %s differs from tools_minimal.json", name) } wantIdx++ } if wantIdx != len(want) { t.Fatalf("filtered list stopped at %d of %d embedded tools", wantIdx, len(want)) } } } func TestNotification(t *testing.T) { s := testServer(t, false) rec := authedCall(t, s, `{"jsonrpc":"2.0","method":"notifications/initialized"}`) if rec.Code != http.StatusNoContent { t.Fatalf("status = %d, want 204", rec.Code) } if rec.Body.Len() != 0 { t.Fatalf("notification response body = %q, want empty", rec.Body.String()) } } func TestUnknownMethod(t *testing.T) { env := decodeEnvelope(t, authedCall(t, testServer(t, false), `{"jsonrpc":"2.0","id":1,"method":"does/not/exist"}`)) if env.Error == nil || env.Error.Code != CodeMethodNotFound { t.Fatalf("error = %+v, want code %d", env.Error, CodeMethodNotFound) } } func TestTransportErrors(t *testing.T) { s := testServer(t, false) t.Run("get", func(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/mcp", nil) req.Header.Set("Authorization", "Bearer "+testToken) rec := httptest.NewRecorder() s.Handle(rec, req) if rec.Code != http.StatusMethodNotAllowed { t.Fatalf("status = %d, want 405", rec.Code) } if got := rec.Header().Get("Allow"); got != http.MethodPost { t.Fatalf("Allow = %q, want POST", got) } }) t.Run("delete", func(t *testing.T) { req := httptest.NewRequest(http.MethodDelete, "/mcp", nil) req.Header.Set("Authorization", "Bearer "+testToken) rec := httptest.NewRecorder() s.Handle(rec, req) if rec.Code != http.StatusMethodNotAllowed { t.Fatalf("status = %d, want 405", rec.Code) } }) t.Run("batch", func(t *testing.T) { env := decodeEnvelope(t, authedCall(t, s, `[{"jsonrpc":"2.0","id":1,"method":"ping"},{"jsonrpc":"2.0","id":2,"method":"ping"}]`)) if env.Error == nil || env.Error.Code != CodeInvalidRequest { t.Fatalf("error = %+v, want code %d", env.Error, CodeInvalidRequest) } if string(env.ID) != "null" { t.Fatalf("id = %s, want null", env.ID) } }) t.Run("oversize", func(t *testing.T) { body := `{"jsonrpc":"2.0","id":1,"method":"ping","params":"` + strings.Repeat("x", maxBodyBytes) + `"}` rec := authedCall(t, s, body) if rec.Code != http.StatusRequestEntityTooLarge { t.Fatalf("status = %d, want 413", rec.Code) } }) t.Run("parse error", func(t *testing.T) { env := decodeEnvelope(t, authedCall(t, s, `{"jsonrpc":`)) if env.Error == nil || env.Error.Code != CodeParseError { t.Fatalf("error = %+v, want code %d", env.Error, CodeParseError) } }) t.Run("missing method", func(t *testing.T) { env := decodeEnvelope(t, authedCall(t, s, `{"jsonrpc":"2.0","id":1}`)) if env.Error == nil || env.Error.Code != CodeInvalidRequest { t.Fatalf("error = %+v, want code %d", env.Error, CodeInvalidRequest) } }) } func TestToolsCallGates(t *testing.T) { s := testServer(t, false) readonly := testServer(t, true) cases := []struct { name string srv *Server body string code int }{ { name: "unknown tool", srv: s, body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"nope"}}`, code: CodeMethodNotFound, }, { name: "missing name", srv: s, body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{}}`, code: CodeInvalidParams, }, { name: "missing params", srv: s, body: `{"jsonrpc":"2.0","id":1,"method":"tools/call"}`, code: CodeInvalidParams, }, { name: "known but not implemented in M1", srv: s, body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_hosts"}}`, code: CodeInternal, }, { name: "readonly refuses write tool", srv: readonly, body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"terminal_exec"}}`, code: CodeDenied, }, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { env := decodeEnvelope(t, authedCall(t, tc.srv, tc.body)) if env.Error == nil || env.Error.Code != tc.code { t.Fatalf("error = %+v, want code %d", env.Error, tc.code) } }) } }