diff --git a/internal/controller/mcp_controller.go b/internal/controller/mcp_controller.go index 81e23e859..4516c5c10 100644 --- a/internal/controller/mcp_controller.go +++ b/internal/controller/mcp_controller.go @@ -171,33 +171,10 @@ func (c *MCPController) MCPAnswersHandler() func(ctx context.Context, request mc return nil, err } - if len(cond.QuestionID) > 0 { - question, err := c.questioncommon.Info(ctx, cond.QuestionID, "") - if err != nil || !mcpQuestionIsPublic(question) { - return mcp.NewToolResultText("[]"), nil - } - answerList, err := c.answerRepo.GetAnswerList(ctx, &entity.Answer{QuestionID: cond.QuestionID}) - if err != nil { - log.Errorf("get answers failed: %v", err) - return nil, err - } - resp := make([]*schema.MCPSearchAnswerInfoResp, 0) - for _, answer := range answerList { - if answer.Status != entity.AnswerStatusAvailable { - continue - } - t := &schema.MCPSearchAnswerInfoResp{ - QuestionID: answer.QuestionID, - AnswerID: answer.ID, - AnswerContent: answer.OriginalText, - Link: fmt.Sprintf("%s/questions/%s/answers/%s", siteGeneral.SiteUrl, answer.QuestionID, answer.ID), - } - resp = append(resp, t) - } - data, _ := json.Marshal(resp) - return mcp.NewToolResultText(string(data)), nil + question, err := c.questioncommon.Info(ctx, cond.QuestionID, "") + if err != nil || !mcpQuestionIsPublic(question) { + return mcp.NewToolResultText("[]"), nil } - answerList, err := c.answerRepo.GetAnswerList(ctx, &entity.Answer{QuestionID: cond.QuestionID}) if err != nil { log.Errorf("get answers failed: %v", err) @@ -210,6 +187,7 @@ func (c *MCPController) MCPAnswersHandler() func(ctx context.Context, request mc } t := &schema.MCPSearchAnswerInfoResp{ QuestionID: answer.QuestionID, + QuestionTitle: question.Title, AnswerID: answer.ID, AnswerContent: answer.OriginalText, Link: fmt.Sprintf("%s/questions/%s/answers/%s", siteGeneral.SiteUrl, answer.QuestionID, answer.ID), @@ -221,6 +199,20 @@ func (c *MCPController) MCPAnswersHandler() func(ctx context.Context, request mc } } +// mcpSemanticSearchAnswerVisible reports whether an answer may be exposed +// through MCP semantic search. Deleted and pending answers must never surface; +// the caller additionally verifies the parent question is public. +func mcpSemanticSearchAnswerVisible(answer *entity.Answer) bool { + return answer != nil && answer.Status == entity.AnswerStatusAvailable +} + +// mcpSemanticSearchCommentVisible reports whether a comment may be exposed +// through MCP semantic search, matching the visibility the comments tool gets +// from the repository layer. +func mcpSemanticSearchCommentVisible(comment *entity.Comment) bool { + return comment != nil && comment.Status == entity.CommentStatusAvailable +} + func mcpQuestionIsPublic(question *schema.QuestionInfoResp) bool { return question != nil && question.Show == entity.QuestionShow && (question.Status == entity.QuestionStatusAvailable || question.Status == entity.QuestionStatusClosed) @@ -419,33 +411,27 @@ func (c *MCPController) MCPSemanticSearchHandler() func(ctx context.Context, req var meta plugin.VectorSearchMetadata _ = json.Unmarshal([]byte(r.Metadata), &meta) - item := &schema.MCPSemanticSearchResp{ - ObjectID: r.ObjectID, - ObjectType: r.ObjectType, - Score: r.Score, - } - - // Compose link from metadata - if r.ObjectType == "answer" && meta.AnswerID != "" { - item.Link = fmt.Sprintf("%s/questions/%s/%s", siteGeneral.SiteUrl, meta.QuestionID, meta.AnswerID) - } else { - item.Link = fmt.Sprintf("%s/questions/%s", siteGeneral.SiteUrl, meta.QuestionID) - } - - // Query content from DB using IDs stored in metadata + // Every fetch below is gated by the visibility rules the other MCP tools + // apply, so a stale embedding cannot leak deleted or hidden content. if r.ObjectType == "question" { question, qErr := c.questioncommon.Info(ctx, meta.QuestionID, "") - if qErr != nil { - log.Warnf("get question %s for semantic search failed: %v", meta.QuestionID, qErr) - } else { - item.Title = question.Title - item.Content = question.Content + if qErr != nil || !mcpQuestionIsPublic(question) { + continue + } + + item := &schema.MCPSemanticSearchResp{ + ObjectID: r.ObjectID, + ObjectType: r.ObjectType, + Score: r.Score, + Title: question.Title, + Content: question.Content, + Link: fmt.Sprintf("%s/questions/%s", siteGeneral.SiteUrl, meta.QuestionID), } // Fetch answers by ID from metadata for _, a := range meta.Answers { - answerEntity, exist, aErr := c.answerRepo.GetAnswer(ctx, a.AnswerID) - if aErr != nil || !exist { + answerEntity, _, aErr := c.answerRepo.GetAnswer(ctx, a.AnswerID) + if aErr != nil || !mcpSemanticSearchAnswerVisible(answerEntity) { continue } answerItem := &schema.MCPSemanticSearchAnswer{ @@ -454,8 +440,8 @@ func (c *MCPController) MCPSemanticSearchHandler() func(ctx context.Context, req } // Fetch comments on this answer from DB for _, ac := range a.Comments { - cmt, cExist, cErr := c.commentRepo.GetComment(ctx, ac.CommentID) - if cErr == nil && cExist { + cmt, _, cErr := c.commentRepo.GetComment(ctx, ac.CommentID) + if cErr == nil && mcpSemanticSearchCommentVisible(cmt) { answerItem.Comments = append(answerItem.Comments, &schema.MCPSemanticSearchComment{ CommentID: ac.CommentID, Content: cmt.OriginalText, @@ -467,39 +453,51 @@ func (c *MCPController) MCPSemanticSearchHandler() func(ctx context.Context, req // Fetch question comments from DB for _, qc := range meta.Comments { - cmt, cExist, cErr := c.commentRepo.GetComment(ctx, qc.CommentID) - if cErr == nil && cExist { + cmt, _, cErr := c.commentRepo.GetComment(ctx, qc.CommentID) + if cErr == nil && mcpSemanticSearchCommentVisible(cmt) { item.Comments = append(item.Comments, &schema.MCPSemanticSearchComment{ CommentID: qc.CommentID, Content: cmt.OriginalText, }) } } + resp = append(resp, item) } else if r.ObjectType == "answer" { - // Fetch question title for context + // The parent question must be public before its title or content is shown question, qErr := c.questioncommon.Info(ctx, meta.QuestionID, "") - if qErr == nil { - item.Title = question.Title + if qErr != nil || !mcpQuestionIsPublic(question) { + continue } - // Fetch answer content from DB + // Fetch the answer content from DB; deleted and pending answers are skipped + var answerEntity *entity.Answer if meta.AnswerID != "" { - answerEntity, exist, aErr := c.answerRepo.GetAnswer(ctx, meta.AnswerID) - if aErr == nil && exist { - item.Content = answerEntity.OriginalText - } + answerEntity, _, _ = c.answerRepo.GetAnswer(ctx, meta.AnswerID) } else if len(meta.Answers) > 0 { - answerEntity, exist, aErr := c.answerRepo.GetAnswer(ctx, meta.Answers[0].AnswerID) - if aErr == nil && exist { - item.Content = answerEntity.OriginalText - } + answerEntity, _, _ = c.answerRepo.GetAnswer(ctx, meta.Answers[0].AnswerID) + } + if !mcpSemanticSearchAnswerVisible(answerEntity) { + continue + } + + item := &schema.MCPSemanticSearchResp{ + ObjectID: r.ObjectID, + ObjectType: r.ObjectType, + Score: r.Score, + Title: question.Title, + Content: answerEntity.OriginalText, + } + if meta.AnswerID != "" { + item.Link = fmt.Sprintf("%s/questions/%s/%s", siteGeneral.SiteUrl, meta.QuestionID, meta.AnswerID) + } else { + item.Link = fmt.Sprintf("%s/questions/%s", siteGeneral.SiteUrl, meta.QuestionID) } // Fetch answer comments from DB if len(meta.Answers) > 0 { for _, ac := range meta.Answers[0].Comments { - cmt, cExist, cErr := c.commentRepo.GetComment(ctx, ac.CommentID) - if cErr == nil && cExist { + cmt, _, cErr := c.commentRepo.GetComment(ctx, ac.CommentID) + if cErr == nil && mcpSemanticSearchCommentVisible(cmt) { item.Comments = append(item.Comments, &schema.MCPSemanticSearchComment{ CommentID: ac.CommentID, Content: cmt.OriginalText, @@ -507,9 +505,8 @@ func (c *MCPController) MCPSemanticSearchHandler() func(ctx context.Context, req } } } + resp = append(resp, item) } - - resp = append(resp, item) } data, _ := json.Marshal(resp) diff --git a/internal/controller/mcp_controller_test.go b/internal/controller/mcp_controller_test.go index 09f75a6a3..8488e4f8a 100644 --- a/internal/controller/mcp_controller_test.go +++ b/internal/controller/mcp_controller_test.go @@ -48,3 +48,45 @@ func TestMCPQuestionIsPublic(t *testing.T) { }) } } + +func TestMCPSemanticSearchAnswerVisible(t *testing.T) { + testCases := []struct { + name string + answer *entity.Answer + want bool + }{ + {"nil", nil, false}, + {"available", &entity.Answer{Status: entity.AnswerStatusAvailable}, true}, + {"deleted", &entity.Answer{Status: entity.AnswerStatusDeleted}, false}, + {"pending", &entity.Answer{Status: entity.AnswerStatusPending}, false}, + } + + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + if got := mcpSemanticSearchAnswerVisible(testCase.answer); got != testCase.want { + t.Fatalf("mcpSemanticSearchAnswerVisible() = %v, want %v", got, testCase.want) + } + }) + } +} + +func TestMCPSemanticSearchCommentVisible(t *testing.T) { + testCases := []struct { + name string + comment *entity.Comment + want bool + }{ + {"nil", nil, false}, + {"available", &entity.Comment{Status: entity.CommentStatusAvailable}, true}, + {"deleted", &entity.Comment{Status: entity.CommentStatusDeleted}, false}, + {"pending", &entity.Comment{Status: entity.CommentStatusPending}, false}, + } + + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + if got := mcpSemanticSearchCommentVisible(testCase.comment); got != testCase.want { + t.Fatalf("mcpSemanticSearchCommentVisible() = %v, want %v", got, testCase.want) + } + }) + } +} diff --git a/internal/schema/mcp_schema.go b/internal/schema/mcp_schema.go index a8902bc4e..26a994a8d 100644 --- a/internal/schema/mcp_schema.go +++ b/internal/schema/mcp_schema.go @@ -33,6 +33,11 @@ const ( MCPDefaultPageSize = 5 // MCPMaxPageSize is the upper bound for page_size so clients cannot request unbounded results. MCPMaxPageSize = 50 + // MCPDefaultTopK is the default number of semantic search results. + MCPDefaultTopK = 5 + // MCPMaxTopK is the upper bound for top_k so a client cannot request an + // unbounded dump of everything stored in the vectors. + MCPMaxTopK = 50 MCPSearchCondKeyword = "keyword" MCPSearchCondUsername = "username" @@ -143,11 +148,18 @@ type MCPSemanticSearchComment struct { } func NewMCPSemanticSearchCond(request mcp.CallToolRequest) *MCPSemanticSearchCond { - cond := &MCPSemanticSearchCond{TopK: 5} + cond := &MCPSemanticSearchCond{TopK: MCPDefaultTopK} if query, ok := getRequestValue(request, MCPSearchCondSemanticQuery); ok { cond.Query = query } - if topK, ok := getRequestNumber(request, MCPSearchCondTopK); ok && topK > 0 { + // GetInt accepts the number and string forms of the argument, matching the + // way the pagination arguments are read. + if topK := request.GetInt(MCPSearchCondTopK, MCPDefaultTopK); topK > 0 { + if topK > MCPMaxTopK { + // Cap the requested result count like page_size, so a client cannot + // ask for an unbounded dump of everything stored in the vectors. + topK = MCPMaxTopK + } cond.TopK = topK } return cond @@ -161,11 +173,12 @@ func NewMCPSearchCond(request mcp.CallToolRequest) *MCPSearchCond { if username, ok := getRequestValue(request, MCPSearchCondUsername); ok { cond.Username = username } - if score, ok := getRequestNumber(request, MCPSearchCondScore); ok { - cond.Score = score - } + // The get_questions tool declares score as a string argument, so read it the + // same way the pagination arguments are read: both the string and the number + // form are accepted instead of silently ignoring one of them. + cond.Score = request.GetInt(MCPSearchCondScore, 0) if tag, ok := getRequestValue(request, MCPSearchCondTag); ok { - cond.Tags = strings.Split(tag, ",") + cond.Tags = splitTagList(tag) } if questionID, ok := getRequestValue(request, MCPSearchCondQuestionID); ok { cond.QuestionID = questionID @@ -232,6 +245,20 @@ func NewMCPSearchUserCond(request mcp.CallToolRequest) *MCPSearchUserCond { return cond } +// splitTagList splits a tag filter on the separators the get_questions tool +// documents ("semicolon separated") and the comma form earlier clients used, +// trimming surrounding whitespace and dropping empty entries. +func splitTagList(tag string) []string { + fields := strings.FieldsFunc(tag, func(r rune) bool { return r == ',' || r == ';' }) + tags := make([]string, 0, len(fields)) + for _, field := range fields { + if trimmed := strings.TrimSpace(field); trimmed != "" { + tags = append(tags, trimmed) + } + } + return tags +} + func getRequestValue(request mcp.CallToolRequest, key string) (string, bool) { value, ok := request.GetArguments()[key].(string) if !ok { diff --git a/internal/schema/mcp_schema_test.go b/internal/schema/mcp_schema_test.go index 6874132bd..2484caa28 100644 --- a/internal/schema/mcp_schema_test.go +++ b/internal/schema/mcp_schema_test.go @@ -20,6 +20,7 @@ package schema import ( + "slices" "testing" "github.com/mark3labs/mcp-go/mcp" @@ -58,3 +59,80 @@ func TestNewMCPSearchCondPagination(t *testing.T) { }) } } + +func TestNewMCPSearchCondScore(t *testing.T) { + testCases := []struct { + name string + arguments map[string]any + wantScore int + }{ + {"number form", map[string]any{"score": float64(9)}, 9}, + {"string form as the tool declares", map[string]any{"score": "5"}, 5}, + {"missing", nil, 0}, + } + + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + request := mcp.CallToolRequest{} + request.Params.Arguments = testCase.arguments + + cond := NewMCPSearchCond(request) + if cond.Score != testCase.wantScore { + t.Fatalf("NewMCPSearchCond() score = %d, want %d", cond.Score, testCase.wantScore) + } + }) + } +} + +func TestNewMCPSearchCondTagSeparators(t *testing.T) { + testCases := []struct { + name string + arguments map[string]any + wantTags []string + }{ + {"semicolon separated as documented", map[string]any{"tag": "go;java;rust"}, []string{"go", "java", "rust"}}, + {"comma separated with spaces", map[string]any{"tag": "go, java , rust"}, []string{"go", "java", "rust"}}, + {"mixed separators", map[string]any{"tag": "go; java,rust"}, []string{"go", "java", "rust"}}, + {"empty entries are dropped", map[string]any{"tag": "go;; java,,,"}, []string{"go", "java"}}, + {"no separator stays one tag", map[string]any{"tag": "go"}, []string{"go"}}, + } + + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + request := mcp.CallToolRequest{} + request.Params.Arguments = testCase.arguments + + cond := NewMCPSearchCond(request) + if !slices.Equal(cond.Tags, testCase.wantTags) { + t.Fatalf("NewMCPSearchCond() tags = %v, want %v", cond.Tags, testCase.wantTags) + } + }) + } +} + +func TestNewMCPSemanticSearchCondTopKBounds(t *testing.T) { + testCases := []struct { + name string + arguments map[string]any + wantTopK int + }{ + {"defaults", nil, MCPDefaultTopK}, + {"explicit value", map[string]any{"top_k": float64(10)}, 10}, + {"string value", map[string]any{"top_k": "7"}, 7}, + {"clamped to the upper bound", map[string]any{"top_k": float64(1000000)}, MCPMaxTopK}, + {"non-positive falls back to default", map[string]any{"top_k": float64(0)}, MCPDefaultTopK}, + {"negative falls back to default", map[string]any{"top_k": float64(-3)}, MCPDefaultTopK}, + } + + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + request := mcp.CallToolRequest{} + request.Params.Arguments = testCase.arguments + + cond := NewMCPSemanticSearchCond(request) + if cond.TopK != testCase.wantTopK { + t.Fatalf("NewMCPSemanticSearchCond() top_k = %d, want %d", cond.TopK, testCase.wantTopK) + } + }) + } +}