Skip to content
Merged
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
6 changes: 3 additions & 3 deletions cmd/wire_gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion i18n/id_ID.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ backend:
rank_invite_someone_to_answer_label:
other: Undang seseorang untuk menjawab
rank_tag_add_label:
other:
other: Buat tag baru
rank_tag_edit_label:
other: Edit tag description (need to review)
rank_question_edit_label:
Expand Down
2 changes: 1 addition & 1 deletion i18n/ru_RU.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -701,7 +701,7 @@ backend:
other: Активный участник на год, опубликовал по крайней мере один раз.
appreciated:
name:
other:
other: Appreciated
desc:
other: Received 1 up vote on 20 posts.
respected:
Expand Down
51 changes: 51 additions & 0 deletions internal/base/middleware/api_key_auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package middleware

import (
"github.com/apache/answer/internal/base/handler"
"github.com/apache/answer/internal/base/reason"
"github.com/gin-gonic/gin"
"github.com/segmentfault/pacman/errors"
)

// AuthAPIKey middleware to authenticate API key
func (am *AuthUserMiddleware) AuthAPIKey() gin.HandlerFunc {
return func(ctx *gin.Context) {
token := ExtractToken(ctx)
if len(token) == 0 {
handler.HandleResponse(ctx, errors.Unauthorized(reason.UnauthorizedError), nil)
ctx.Abort()
return
}
pass, err := am.authService.AuthAPIKey(ctx, ctx.Request.Method == "GET", token)
if err != nil {
handler.HandleResponse(ctx, errors.Unauthorized(reason.UnauthorizedError), nil)
ctx.Abort()
return
}
if !pass {
handler.HandleResponse(ctx, errors.Unauthorized(reason.UnauthorizedError), nil)
ctx.Abort()
return
}
ctx.Next()
}
}
5 changes: 5 additions & 0 deletions internal/base/server/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,5 +113,10 @@ func NewHTTPServer(debug bool,
agent.RegisterAuthAdminRouter(adminauthV1)
return nil
})

// mcp
mcpAPIGroup := r.Group(uiConf.APIBaseURL + "/answer/api/v1")
mcpAPIGroup.Use(authUserMiddleware.AuthMcpEnable(), authUserMiddleware.AuthAPIKey())
answerRouter.RegisterMCPRouter(mcpAPIGroup)
return r
}
4 changes: 3 additions & 1 deletion internal/cli/reset_password.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import (
"github.com/apache/answer/internal/base/conf"
"github.com/apache/answer/internal/base/data"
"github.com/apache/answer/internal/base/path"
"github.com/apache/answer/internal/repo/api_key"
"github.com/apache/answer/internal/repo/auth"
"github.com/apache/answer/internal/repo/user"
authService "github.com/apache/answer/internal/service/auth"
Expand Down Expand Up @@ -95,7 +96,8 @@ func ResetPassword(ctx context.Context, dataDirPath string, opts *ResetPasswordO

userRepo := user.NewUserRepo(dataData)
authRepo := auth.NewAuthRepo(dataData)
authSvc := authService.NewAuthService(authRepo)
apiKeyRepo := api_key.NewAPIKeyRepo(dataData)
authSvc := authService.NewAuthService(authRepo, apiKeyRepo)

email := strings.TrimSpace(opts.Email)
if email == "" {
Expand Down
28 changes: 28 additions & 0 deletions internal/migrations/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ func (m *Mentor) InitDB() error {
m.do("init site info security", m.initSiteInfoSecurityConfig)
m.do("init default content", m.initDefaultContent)
m.do("init default badges", m.initDefaultBadges)
m.do("init default ai config", m.initSiteInfoAI)
m.do("init default MCP config", m.initSiteInfoMCP)
return m.err
}

Expand Down Expand Up @@ -606,3 +608,29 @@ func (m *Mentor) initDefaultBadges() {
}
}
}

func (m *Mentor) initSiteInfoAI() {
content := &schema.SiteAIReq{
PromptConfig: &schema.AIPromptConfig{
ZhCN: constant.DefaultAIPromptConfigZhCN,
EnUS: constant.DefaultAIPromptConfigEnUS,
},
}
writeDataBytes, _ := json.Marshal(content)
_, m.err = m.engine.Context(m.ctx).Insert(&entity.SiteInfo{
Type: constant.SiteTypeAI,
Content: string(writeDataBytes),
Status: 1,
})
}
func (m *Mentor) initSiteInfoMCP() {
content := &schema.SiteMCPReq{
Enabled: true,
}
writeDataBytes, _ := json.Marshal(content)
_, m.err = m.engine.Context(m.ctx).Insert(&entity.SiteInfo{
Type: constant.SiteTypeMCP,
Content: string(writeDataBytes),
Status: 1,
})
}
3 changes: 3 additions & 0 deletions internal/migrations/init_data.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ var (
&entity.BadgeAward{},
&entity.FileRecord{},
&entity.PluginKVStorage{},
&entity.APIKey{},
&entity.AIConversation{},
&entity.AIConversationRecord{},
}

roles = []*entity.Role{
Expand Down
3 changes: 3 additions & 0 deletions internal/router/answer_api_router.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ type AnswerAPIRouter struct {
aiController *controller.AIController
aiConversationController *controller.AIConversationController
aiConversationAdminController *controller_admin.AIConversationAdminController
mcpController *controller.MCPController
}

func NewAnswerAPIRouter(
Expand Down Expand Up @@ -98,6 +99,7 @@ func NewAnswerAPIRouter(
aiController *controller.AIController,
aiConversationController *controller.AIConversationController,
aiConversationAdminController *controller_admin.AIConversationAdminController,
mcpController *controller.MCPController,
) *AnswerAPIRouter {
return &AnswerAPIRouter{
langController: langController,
Expand Down Expand Up @@ -134,6 +136,7 @@ func NewAnswerAPIRouter(
aiController: aiController,
aiConversationController: aiConversationController,
aiConversationAdminController: aiConversationAdminController,
mcpController: mcpController,
}
}

Expand Down
44 changes: 44 additions & 0 deletions internal/router/mcp_router.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package router

import (
"github.com/apache/answer/internal/schema/mcp_tools"
"github.com/gin-gonic/gin"
"github.com/mark3labs/mcp-go/server"
)

func (a *AnswerAPIRouter) RegisterMCPRouter(r *gin.RouterGroup) {
s := server.NewMCPServer("Answer Enterprise MCP Server", "1.0.0")

s.AddTool(mcp_tools.NewQuestionsTool(), a.mcpController.MCPQuestionsHandler())
s.AddTool(mcp_tools.NewAnswersTool(), a.mcpController.MCPAnswersHandler())
s.AddTool(mcp_tools.NewCommentsTool(), a.mcpController.MCPCommentsHandler())
s.AddTool(mcp_tools.NewTagsTool(), a.mcpController.MCPTagsHandler())
s.AddTool(mcp_tools.NewTagDetailTool(), a.mcpController.MCPTagDetailsHandler())
s.AddTool(mcp_tools.NewUserTool(), a.mcpController.MCPUserDetailsHandler())

sseServer := server.NewSSEServer(s,
server.WithSSEEndpoint("/answer/api/v1/mcp/see"),
server.WithMessageEndpoint("/answer/api/v1/mcp/message"),
)
r.GET("/mcp/sse", gin.WrapH(sseServer.SSEHandler()))
r.POST("/mcp/message", gin.WrapH(sseServer.MessageHandler()))
}
26 changes: 23 additions & 3 deletions internal/service/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@ import (
"context"

"github.com/apache/answer/internal/entity"
"github.com/apache/answer/internal/service/apikey"
"github.com/apache/answer/pkg/token"
"github.com/apache/answer/plugin"
"github.com/segmentfault/pacman/log"
)

// AuthRepo auth repository
Expand All @@ -46,13 +48,15 @@ type AuthRepo interface {

// AuthService kit service
type AuthService struct {
authRepo AuthRepo
authRepo AuthRepo
apiKeyRepo apikey.APIKeyRepo
}

// NewAuthService email service
func NewAuthService(authRepo AuthRepo) *AuthService {
func NewAuthService(authRepo AuthRepo, apiKeyRepo apikey.APIKeyRepo) *AuthService {
return &AuthService{
authRepo: authRepo,
authRepo: authRepo,
apiKeyRepo: apiKeyRepo,
}
}

Expand Down Expand Up @@ -152,3 +156,19 @@ func (as *AuthService) SetAdminUserCacheInfo(ctx context.Context, accessToken st
func (as *AuthService) RemoveAdminUserCacheInfo(ctx context.Context, accessToken string) (err error) {
return as.authRepo.RemoveAdminUserCacheInfo(ctx, accessToken)
}
func (as *AuthService) AuthAPIKey(ctx context.Context, read bool, apiKey string) (pass bool, err error) {
apiKeyInfo, exist, err := as.apiKeyRepo.GetAPIKey(ctx, apiKey)
if err != nil {
return false, err
}
if !exist {
return false, nil
}
// If the request is not read-only, check if the API key has write permissions
if !read && apiKeyInfo.Scope == "read-only" {
log.Warnf("API key %s does not have write permissions", apiKeyInfo.AccessKey)
return false, nil
}
log.Infof("API key %s is valid, scope: %s", apiKeyInfo.AccessKey, apiKeyInfo.Scope)
return true, nil
}
4 changes: 2 additions & 2 deletions ui/src/pages/Install/components/FourthStep/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ const Index: FC<Props> = ({ visible, data, changeCallback, nextCallback }) => {

if (site_name.value && site_name.value.length > 30) {
bol = false;
data.site_url = {
data.site_name = {
value: site_name.value,
isInvalid: true,
errorMsg: t('site_name.msg_max_length'),
Expand All @@ -70,7 +70,7 @@ const Index: FC<Props> = ({ visible, data, changeCallback, nextCallback }) => {
data.site_url = {
value: '',
isInvalid: true,
errorMsg: t('site_name.msg.empty'),
errorMsg: t('site_url.msg.empty'),
};
}

Expand Down
Loading