Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 64 additions & 67 deletions internal/controller/mcp_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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),
Expand All @@ -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)
Expand Down Expand Up @@ -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{
Expand All @@ -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,
Expand All @@ -467,49 +453,60 @@ 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,
})
}
}
}
resp = append(resp, item)
}

resp = append(resp, item)
}

data, _ := json.Marshal(resp)
Expand Down
42 changes: 42 additions & 0 deletions internal/controller/mcp_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
})
}
}
39 changes: 33 additions & 6 deletions internal/schema/mcp_schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
Loading