diff --git a/internal/controller/mcp_controller.go b/internal/controller/mcp_controller.go index 7fd7c9662..6ecdab177 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), diff --git a/internal/schema/mcp_schema.go b/internal/schema/mcp_schema.go index a8902bc4e..4f7e23b3e 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 { @@ -240,14 +267,6 @@ func getRequestValue(request mcp.CallToolRequest, key string) (string, bool) { return value, true } -func getRequestNumber(request mcp.CallToolRequest, key string) (int, bool) { - value, ok := request.GetArguments()[key].(float64) - if !ok { - return 0, false - } - return int(value), true -} - func (cond *MCPSearchCond) ToQueryString() string { var queryBuilder strings.Builder if len(cond.Keyword) > 0 { 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) + } + }) + } +}