Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(mcp): report advertised directory failures in connection tests (#3905)
helloxjade4243018ff1f5
diff --git a/internal/application/service/mcp_service.go b/internal/application/service/mcp_service.goindex 80c94da9f..a595c0d28 100644--- a/internal/application/service/mcp_service.go+++ b/internal/application/service/mcp_service.go@@ -423,16 +423,20 @@ func (s *mcpServiceService) TestMCPService(return mcpTestFailure(err, "Initialization failed"), nil}- // List toolstools, err := client.ListTools(testCtx)if err != nil {+ if initResult.Capabilities.Tools != nil {+ return mcpTestFailure(err, "Failed to list tools"), nil+ }logger.GetLogger(ctx).Warnf("Failed to list tools: %v", err)tools = []*types.MCPTool{}}- // List resourcesresources, err := client.ListResources(testCtx)if err != nil {+ if initResult.Capabilities.Resources != nil {+ return mcpTestFailure(err, "Failed to list resources"), nil+ }logger.GetLogger(ctx).Warnf("Failed to list resources: %v", err)resources = []*types.MCPResource{}}diff --git a/internal/application/service/mcp_service_test.go b/internal/application/service/mcp_service_test.goindex 31be6fbb6..5ad6b6cda 100644--- a/internal/application/service/mcp_service_test.go+++ b/internal/application/service/mcp_service_test.go@@ -1,12 +1,20 @@package serviceimport (+ "bytes""context"+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest""strings"+ "sync""testing""github.com/Tencent/WeKnora/internal/mcp""github.com/Tencent/WeKnora/internal/types"+ "github.com/Tencent/WeKnora/internal/utils"+ sdkserver "github.com/mark3labs/mcp-go/server""github.com/stretchr/testify/assert""github.com/stretchr/testify/require")@@ -117,6 +125,105 @@ func newTestService() (*mcpServiceService, *fakeMCPRepo) {return svc, repo}+func TestTestMCPService_ListingCapabilityCompatibility(t *testing.T) {+ tests := []struct {+ name string+ tools bool+ resources bool+ failMethod string+ listMethod string+ wantSuccess bool+ }{+ {name: "tool list fails", tools: true, failMethod: "tools/list"},+ {name: "resource list fails", resources: true, failMethod: "resources/list"},+ {name: "resource-only server", resources: true, failMethod: "tools/list", wantSuccess: true},+ {name: "tool-only server", tools: true, failMethod: "resources/list", wantSuccess: true},+ {name: "tools without advertised capability", listMethod: "tools/list", wantSuccess: true},+ {name: "resources without advertised capability", listMethod: "resources/list", wantSuccess: true},+ {name: "advertised empty lists", tools: true, resources: true, wantSuccess: true},+ {name: "no advertised capabilities", failMethod: "tools/list", wantSuccess: true},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ utils.SetSSRFWhitelistFromRaw("127.0.0.1")+ t.Cleanup(utils.ResetSSRFWhitelistForTest)++ var options []sdkserver.ServerOption+ if tt.tools {+ options = append(options, sdkserver.WithToolCapabilities(false))+ }+ if tt.resources {+ options = append(options, sdkserver.WithResourceCapabilities(false, false))+ }+ mcpServer := sdkserver.NewMCPServer("test", "1", options...)+ upstream := sdkserver.NewStreamableHTTPServer(mcpServer, sdkserver.WithStateLess(true))+ requests := map[string]bool{}+ var requestsMu sync.Mutex+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ body, err := io.ReadAll(r.Body)+ require.NoError(t, err)+ var request struct {+ ID json.RawMessage `json:"id"`+ Method string `json:"method"`+ }+ require.NoError(t, json.Unmarshal(body, &request))+ requestsMu.Lock()+ requests[request.Method] = true+ requestsMu.Unlock()+ if request.Method == tt.failMethod {+ w.Header().Set("Content-Type", "application/json")+ errBody := `{"jsonrpc":"2.0","id":` + string(request.ID) ++ `,"error":{"code":-32603,"message":"directory unavailable"}}`+ _, _ = w.Write([]byte(errBody))+ return+ }+ if request.Method == tt.listMethod {+ w.Header().Set("Content-Type", "application/json")+ result := `{"tools":[{"name":"test_tool","inputSchema":{"type":"object"}}]}`+ if request.Method == "resources/list" {+ result = `{"resources":[{"uri":"test://resource","name":"test_resource"}]}`+ }+ _, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":` + string(request.ID) + `,"result":` + result + `}`))+ return+ }+ r.Body = io.NopCloser(bytes.NewReader(body))+ upstream.ServeHTTP(w, r)+ }))+ t.Cleanup(server.Close)++ svc, repo := newTestService()+ url := server.URL+ repo.store["svc"] = &types.MCPService{+ ID: "svc", TenantID: 1, Name: "test", URL: &url,+ TransportType: types.MCPTransportHTTPStreamable,+ }+ result, err := svc.TestMCPService(context.Background(), 1, "svc")+ require.NoError(t, err)+ require.NotNil(t, result)+ assert.Equal(t, tt.wantSuccess, result.Success)+ if !tt.wantSuccess {+ assert.Contains(t, result.Message, "directory unavailable")+ }+ if tt.listMethod == "tools/list" {+ require.Len(t, result.Tools, 1)+ assert.Equal(t, "test_tool", result.Tools[0].Name)+ } else {+ assert.Empty(t, result.Tools)+ }+ if tt.listMethod == "resources/list" {+ require.Len(t, result.Resources, 1)+ assert.Equal(t, "test://resource", result.Resources[0].URI)+ } else {+ assert.Empty(t, result.Resources)+ }+ requestsMu.Lock()+ defer requestsMu.Unlock()+ assert.True(t, requests["tools/list"])+ assert.Equal(t, !tt.tools || tt.failMethod != "tools/list", requests["resources/list"])+ })+ }+}+func TestUpdateMCPService_RespectsScalarFieldPresence(t *testing.T) {tests := []struct {name stringdiff --git a/internal/mcp/client.go b/internal/mcp/client.goindex 6a688f5b8..c490af998 100644--- a/internal/mcp/client.go+++ b/internal/mcp/client.go@@ -438,8 +438,20 @@ func (c *mcpGoClient) Initialize(ctx context.Context) (*InitializeResult, error))}+ capabilities := ServerCapabilities{}+ if result.Capabilities.Tools != nil {+ capabilities.Tools = &ToolsCapability{ListChanged: result.Capabilities.Tools.ListChanged}+ }+ if result.Capabilities.Resources != nil {+ capabilities.Resources = &ResourcesCapability{+ Subscribe: result.Capabilities.Resources.Subscribe,+ ListChanged: result.Capabilities.Resources.ListChanged,+ }+ }+return &InitializeResult{ProtocolVersion: result.ProtocolVersion,+ Capabilities: capabilities,Instructions: result.Instructions,ServerInfo: ServerInfo{Name: result.ServerInfo.Name,diff --git a/website-docs/03-features/08-mcp.md b/website-docs/03-features/08-mcp.mdindex eedeca26a..7d35b6718 100644--- a/website-docs/03-features/08-mcp.md+++ b/website-docs/03-features/08-mcp.md@@ -201,7 +201,7 @@ ClientInfo: mcp.Implementation{ Name: "WeKnora", Version: "1.0.0" }| GET | `/mcp-services/{id}` | Viewer+ | 服务详情(经 DTO 脱敏) || PUT | `/mcp-services/{id}` | Admin+ | 更新服务;主 PUT **忽略** `auth_config.api_key` / `auth_config.token`(打 deprecated 警告) || DELETE | `/mcp-services/{id}` | Admin+ | 删除服务(软删除,先 `CloseClient`) |-| POST | `/mcp-services/{id}/test` | Admin+ | 连接测试:临时客户端 Connect + Initialize + ListTools + ListResources;返回 `MCPTestResult`(含 `oauth_required` 标记) |+| POST | `/mcp-services/{id}/test` | Admin+ | 连接测试:临时客户端 Connect + Initialize,并尝试读取工具与资源列表;读取失败且服务端声明支持该能力时返回失败结果,否则记录警告并按空列表继续。返回 `MCPTestResult`(含 `oauth_required` 标记) || GET | `/mcp-services/{id}/tools` | Viewer+ | 拉取 MCP 服务的工具列表 || GET | `/mcp-services/{id}/resources` | Viewer+ | 拉取 MCP 服务的资源列表 || PUT | `/mcp-services/{id}/credentials` | Admin+ | 写入 `api_key` / `token` 凭据(见下) |