An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Route MCP tool calls by server ID https://github.com/siyuan-note/siyuan/issues/20186
Daniel1a733a6c359f
diff --git a/kernel/mcp/client/mcp.go b/kernel/mcp/client/mcp.goindex f8f3e65a96..44b54d74d7 100644--- a/kernel/mcp/client/mcp.go+++ b/kernel/mcp/client/mcp.go@@ -315,7 +315,7 @@ func connectOneServer(ctx context.Context, server conf.MCPServer, interactive bo}readOnlyHint := trustedReadOnlyHint(server, tool)- handler := mcpToolContextHandler(server.Name, tool.Name, serverTimeout(server), tool.OutputSchema != nil)+ handler := mcpToolContextHandler(server.ID, tool.Name, serverTimeout(server), tool.OutputSchema != nil)var outputSchema *tools.ToolSchemaif tool.OutputSchema != nil {converted := convertMCPSchema(tool.OutputSchema)@@ -692,14 +692,14 @@ func hasAuthorizationHeader(headers map[string]string) bool {return false}-func mcpToolContextHandler(serverName, toolName string, timeout time.Duration,+func mcpToolContextHandler(serverID, toolName string, timeout time.Duration,structuredContentExpected bool) func(context.Context, map[string]any) (tools.CallToolResult, error) {return func(ctx context.Context, args map[string]any) (tools.CallToolResult, error) {result := callMCPToolOnce(func() (*mcp.CallToolResult, error) {- connection := getMCPConnection(serverName)+ connection := getMCPConnection(serverID)result, rejected, err := callMCPTool(ctx, connection, toolName, timeout, args)if rejected && errors.Is(err, mcp.ErrSessionMissing) && ctx.Err() == nil {- logging.LogWarnf("mcp: server [%s] tool [%s] session expired, reconnecting", serverName, toolName)+ logging.LogWarnf("mcp: server [%s] tool [%s] session expired, reconnecting", serverID, toolName)recoveryCtx, cancel := context.WithTimeout(ctx, timeout)reconnected := reconnectMCPAndWait(recoveryCtx, connection)cancel()@@ -707,27 +707,27 @@ func mcpToolContextHandler(serverName, toolName string, timeout time.Duration,result, rejected, err = callMCPTool(ctx, reconnected, toolName, timeout, args)if rejected && errors.Is(err, mcp.ErrSessionMissing) {err = errors.New("mcp session expired again after reconnect")- go reconnectMCP(serverName)+ go reconnectMCP(serverID)}} else {err = errors.New("mcp session expired and reconnect failed")}}- updateMCPRuntimeAfterToolCall(serverName, err)+ updateMCPRuntimeAfterToolCall(serverID, err)return result, err}, func(err error) {- logging.LogWarnf("mcp: server [%s] tool [%s] disconnected (%s), reconnecting", serverName, toolName, err)- go reconnectMCP(serverName)+ logging.LogWarnf("mcp: server [%s] tool [%s] disconnected (%s), reconnecting", serverID, toolName, err)+ go reconnectMCP(serverID)}, structuredContentExpected)return result, nil}}-func updateMCPRuntimeAfterToolCall(serverName string, callErr error) {+func updateMCPRuntimeAfterToolCall(serverID string, callErr error) {mcpMu.Lock()connectionIndex := -1for i := range mcpConns {- if mcpConns[i].ServerName == serverName {+ if mcpConns[i].ServerID == serverID {connectionIndex = ibreak}@@ -861,11 +861,11 @@ func callMCPTool(parentCtx context.Context, connection *Connection, toolName strreturn result, rejected.Load(), err}-func getMCPConnection(serverName string) *Connection {+func getMCPConnection(serverID string) *Connection {mcpMu.Lock()defer mcpMu.Unlock()for _, conn := range mcpConns {- if conn.ServerName == serverName {+ if conn.ServerID == serverID {return &conn}}@@ -938,22 +938,22 @@ func waitMCPReconnect(ctx context.Context, done <-chan struct{}) bool {}// reconnectMCP 关闭现有连接并重新注册工具。-func reconnectMCP(serverName string) bool {+func reconnectMCP(serverID string) bool {mcpMu.Lock()if mcpConnecting {mcpMu.Unlock()return false}servers := append([]conf.MCPServer(nil), mcpServers...)- serverID := ""+ found := falsefor _, server := range servers {- if server.Name == serverName {- serverID = server.ID+ if server.ID == serverID {+ found = truebreak}}mcpMu.Unlock()- if serverID == "" {+ if !found {return false}ReconnectMCPAsync(servers, []string{serverID}, nil)diff --git a/kernel/mcp/client/mcp_test.go b/kernel/mcp/client/mcp_test.goindex 288ce14438..707a3971ea 100644--- a/kernel/mcp/client/mcp_test.go+++ b/kernel/mcp/client/mcp_test.go@@ -303,7 +303,7 @@ func TestMCPToolRetriesAfterSessionRejection(t *testing.T) {ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()- result, err := mcpToolContextHandler(configured.Name, "execute", 5*time.Second, false)(ctx, nil)+ result, err := mcpToolContextHandler(configured.ID, "execute", 5*time.Second, false)(ctx, nil)if err != nil || result.IsError || result.ExecutionUnknown || len(result.Content) == 0 || result.Content[0].Text != "done" {t.Fatalf("unexpected tool result: result=%#v err=%v", result, err)}@@ -315,7 +315,7 @@ func TestMCPToolRetriesAfterSessionRejection(t *testing.T) {denyInitialize.Store(true)failedCtx, failedCancel := context.WithTimeout(context.Background(), 10*time.Second)defer failedCancel()- result, err = mcpToolContextHandler(configured.Name, "execute", 5*time.Second, false)(failedCtx, nil)+ result, err = mcpToolContextHandler(configured.ID, "execute", 5*time.Second, false)(failedCtx, nil)if err != nil || !result.IsError || result.ExecutionUnknown {t.Fatalf("reconnect failure was not reported as a known rejection: result=%#v err=%v", result, err)}@@ -476,8 +476,14 @@ func TestOAuthToolFailureRemovesUnauthorizedConnection(t *testing.T) {mcpMu.Lock()oldConns := mcpConnsoldRuntime := mcpRuntime- mcpConns = []Connection{{ServerID: serverID, ServerName: "oauth-tool", Tools: 1}}- mcpRuntime = map[string]mcpRuntimeState{serverID: {Status: "oauth_retrying", Tools: 1}}+ mcpConns = []Connection{+ {ServerID: "other-server", ServerName: "oauth-tool", Tools: 1},+ {ServerID: serverID, ServerName: "oauth-tool", Tools: 1},+ }+ mcpRuntime = map[string]mcpRuntimeState{+ "other-server": {Status: "connected", Tools: 1},+ serverID: {Status: "oauth_retrying", Tools: 1},+ }mcpMu.Unlock()t.Cleanup(func() {mcpMu.Lock()@@ -486,12 +492,17 @@ func TestOAuthToolFailureRemovesUnauthorizedConnection(t *testing.T) {mcpMu.Unlock()})- updateMCPRuntimeAfterToolCall("oauth-tool", errors.New("401 Unauthorized"))+ updateMCPRuntimeAfterToolCall(serverID, errors.New("401 Unauthorized"))mcpMu.Lock()connections := len(mcpConns)state := mcpRuntime[serverID]+ otherState := mcpRuntime["other-server"]+ remainingID := ""+ if len(mcpConns) > 0 {+ remainingID = mcpConns[0].ServerID+ }mcpMu.Unlock()- if connections != 0 || state.Status != "authorization_required" {+ if connections != 1 || remainingID != "other-server" || otherState.Status != "connected" || state.Status != "authorization_required" {t.Fatalf("unexpected unauthorized connection state: connections=%d state=%#v", connections, state)}}@@ -513,7 +524,7 @@ func TestReconnectMCPDoesNotInterruptPendingConnection(t *testing.T) {mcpMu.Unlock()})- if reconnectMCP("server") {+ if reconnectMCP("server-id") {t.Fatal("pending connection was interrupted")}mcpMu.Lock()@@ -526,7 +537,7 @@ func TestReconnectMCPDoesNotInterruptPendingConnection(t *testing.T) {func TestReconnectMCPAsyncKeepsOtherConnections(t *testing.T) {serverA := conf.MCPServer{ID: "server-a", Name: "server-a", Enabled: true, Type: "stdio"}- serverB := conf.MCPServer{ID: "server-b", Name: "server-b", Enabled: true, Type: "stdio"}+ serverB := conf.MCPServer{ID: "server-b", Name: serverA.Name, Enabled: true, Type: "stdio"}mcpMu.Lock()oldConns := mcpConnsoldServers := mcpServers@@ -559,7 +570,9 @@ func TestReconnectMCPAsyncKeepsOtherConnections(t *testing.T) {mcpMu.Unlock()})- ReconnectMCPAsync([]conf.MCPServer{serverA, serverB}, []string{serverA.ID}, nil)+ if !reconnectMCP(serverA.ID) {+ t.Fatal("same-name server was not selected by ID for reconnect")+ }deadline := time.Now().Add(5 * time.Second)for time.Now().Before(deadline) {mcpMu.Lock()diff --git a/kernel/mcp/client/routing_test.go b/kernel/mcp/client/routing_test.gonew file mode 100644index 0000000000..386e42715e--- /dev/null+++ b/kernel/mcp/client/routing_test.go@@ -0,0 +1,54 @@+package client++import (+ "context"+ "testing"+ "time"++ "github.com/modelcontextprotocol/go-sdk/mcp"+)++func TestMCPToolHandlerRoutesSameNameServersByID(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ var connections []Connection+ for _, id := range []string{"first-server", "second-server"} {+ server := mcp.NewServer(&mcp.Implementation{Name: "same-name", Version: "1"}, nil)+ mcp.AddTool(server, &mcp.Tool{Name: "identify"},+ func(context.Context, *mcp.CallToolRequest, struct{}) (*mcp.CallToolResult, struct{}, error) {+ return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: id}}}, struct{}{}, nil+ })+ serverTransport, clientTransport := mcp.NewInMemoryTransports()+ serverSession, err := server.Connect(ctx, serverTransport, nil)+ if err != nil {+ t.Fatal(err)+ }+ defer serverSession.Close()+ client := mcp.NewClient(&mcp.Implementation{Name: "test", Version: "1"}, nil)+ session, err := client.Connect(ctx, clientTransport, nil)+ if err != nil {+ t.Fatal(err)+ }+ defer session.Close()+ connections = append(connections, Connection{ServerID: id, ServerName: "same-name", Session: session})+ }+ mcpMu.Lock()+ oldConns, oldRuntime := mcpConns, mcpRuntime+ mcpConns = connections+ mcpRuntime = map[string]mcpRuntimeState{}+ mcpMu.Unlock()+ t.Cleanup(func() {+ mcpMu.Lock()+ mcpConns, mcpRuntime = oldConns, oldRuntime+ mcpMu.Unlock()+ })+ for _, connection := range connections {+ result, err := mcpToolContextHandler(connection.ServerID, "identify", time.Second, false)(ctx, nil)+ if err != nil || result.IsError || len(result.Content) != 1 || result.Content[0].Text != connection.ServerID {+ t.Fatalf("same-name tool was routed to another server: id=%s result=%#v err=%v", connection.ServerID, result, err)+ }+ }+ if getMCPConnection("same-name") != nil {+ t.Fatal("display name was accepted as a connection ID")+ }+}