Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: AI Agent https://github.com/siyuan-note/siyuan/issues/17797

Daniel8335aa714576
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.go
index a1d9165f06..f0f49901b4 100644
--- a/kernel/agent/agent.go
+++ b/kernel/agent/agent.go
@@ -29,6 +29,8 @@ import (
"github.com/sashabaranov/go-openai"
"github.com/siyuan-note/filelock"
+ mcpclient "github.com/siyuan-note/siyuan/kernel/mcp/client"
+ kernelModel "github.com/siyuan-note/siyuan/kernel/model"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -75,6 +77,12 @@ type confirmResult struct {
always bool
}
+type doomLoopTracker struct {
+ prevSig string
+ prevName string
+ count int
+}
+
var confirmChannelsMu sync.Mutex
var confirmChannels = make(map[string]chan confirmResult)
@@ -146,11 +154,18 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
}
}()
+ var mcpConns []mcpclient.Connection
+ if kernelModel.Conf.AI.MCP != nil {
+ mcpConns = mcpclient.ConnectServers(kernelModel.Conf.AI.MCP.Servers)
+ }
+ defer mcpclient.CloseConnections(mcpConns)
+
tools := convertMCPToolsToOpenAI()
messages := buildMessages(history, language, references)
var totalPrompt, totalCompletion int
startTime := time.Now().UnixMilli()
alwaysAllow := map[string]bool{}
+ var doomLoop doomLoopTracker
checkpointMsgs := make([]AgentMessage, 0, len(history))
for _, h := range history {
@@ -321,21 +336,39 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
}
setCurrentTodoSession(sessionID)
- result := executeTool(tc)
+ result := executeTool(tc)
ch <- AgentEvent{
- Type: "tool_result",
- Name: tc.Function.Name,
- Result: result,
- }
+ Type: "tool_result",
+ Name: tc.Function.Name,
+ Result: result,
+ }
- messages = append(messages, openai.ChatCompletionMessage{
+ messages = append(messages, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleTool,
Content: result,
ToolCallID: tc.ID,
})
checkpointMsgs[assistantIdx].ToolCalls[i].Result = result
+
+ sig := tc.Function.Name + "::" + tc.Function.Arguments
+ if sig == doomLoop.prevSig && doomLoop.prevSig != "" {
+ doomLoop.count++
+ } else {
+ doomLoop.prevSig = sig
+ doomLoop.prevName = tc.Function.Name
+ doomLoop.count = 1
+ }
+ }
+
+ if doomLoop.count >= 3 {
+ messages = append(messages, openai.ChatCompletionMessage{
+ Role: openai.ChatMessageRoleSystem,
+ Content: "You have called '" + doomLoop.prevName + "' " + fmt.Sprintf("%d", doomLoop.count) + " times with the same arguments. Please try a different approach.",
+ })
+ doomLoop = doomLoopTracker{}
}
+
saveCheckpoint(sessionID, checkpointMsgs, totalPrompt, totalCompletion, startTime)
continue
}
diff --git a/kernel/conf/ai.go b/kernel/conf/ai.go
index 199a6e91c5..38aeeefb02 100644
--- a/kernel/conf/ai.go
+++ b/kernel/conf/ai.go
@@ -26,7 +26,23 @@ import (
)
type AI struct {
- OpenAI *OpenAI `json:"openAI"`
+ OpenAI *OpenAI `json:"openAI"`
+ MCP *MCPConfig `json:"mcp"`
+}
+
+type MCPConfig struct {
+ Servers []MCPServer `json:"servers"`
+}
+
+type MCPServer struct {
+ Name string `json:"name"`
+ Enabled bool `json:"enabled"`
+ Type string `json:"type"` // "stdio" | "http"
+ Command string `json:"command"`
+ Args []string `json:"args"`
+ URL string `json:"url"`
+ Headers map[string]string `json:"headers"`
+ Timeout int `json:"timeout"`
}
type OpenAI struct {
diff --git a/kernel/go.mod b/kernel/go.mod
index 2e9986bb45..b994b07bd3 100644
--- a/kernel/go.mod
+++ b/kernel/go.mod
@@ -38,7 +38,7 @@ require (
github.com/gin-gonic/gin v1.11.0
github.com/go-ole/go-ole v1.3.0
github.com/gofrs/flock v0.13.0
- github.com/golang-jwt/jwt/v5 v5.3.0
+ github.com/golang-jwt/jwt/v5 v5.3.1
github.com/gonutz/w32/v2 v2.12.1
github.com/google/uuid v1.6.0
github.com/gorilla/css v1.0.1
@@ -53,6 +53,7 @@ require (
github.com/mattn/go-sqlite3 v2.0.3+incompatible
github.com/microcosm-cc/bluemonday v1.0.27
github.com/mitchellh/go-ps v1.0.0
+ github.com/modelcontextprotocol/go-sdk v1.6.1
github.com/mssola/useragent v1.0.0
github.com/olahol/melody v1.4.0
github.com/open-spaced-repetition/go-fsrs/v3 v3.3.1
@@ -90,7 +91,7 @@ require (
golang.org/x/sync v0.20.0
golang.org/x/sys v0.45.0
golang.org/x/text v0.37.0
- golang.org/x/time v0.14.0
+ golang.org/x/time v0.15.0
gopkg.in/yaml.v3 v3.0.1
)
@@ -150,6 +151,7 @@ require (
github.com/goccy/go-yaml v1.18.0 // indirect
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
github.com/google/go-querystring v1.2.0 // indirect
+ github.com/google/jsonschema-go v0.4.3 // indirect
github.com/google/pprof v0.0.0-20250607225305-033d6d78b36a // indirect
github.com/gopherjs/gopherjs v1.20.2 // indirect
github.com/gorilla/context v1.1.2 // indirect
@@ -187,6 +189,8 @@ require (
github.com/restic/chunker v0.4.0 // indirect
github.com/richardlehane/mscfb v1.0.6 // indirect
github.com/richardlehane/msoleps v1.0.6 // indirect
+ github.com/segmentio/asm v1.1.3 // indirect
+ github.com/segmentio/encoding v0.5.4 // indirect
github.com/shopspring/decimal v1.4.0 // indirect
github.com/spf13/pflag v1.0.9 // indirect
github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect
@@ -201,10 +205,12 @@ require (
github.com/wmentor/html v1.0.3 // indirect
github.com/xuri/efp v0.0.1 // indirect
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 // indirect
+ github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
golang.org/x/arch v0.23.0 // indirect
golang.org/x/crypto v0.52.0 // indirect
golang.org/x/image v0.38.0 // indirect
+ golang.org/x/oauth2 v0.35.0 // indirect
golang.org/x/tools v0.44.0 // indirect
google.golang.org/protobuf v1.36.10 // indirect
gopkg.in/cenkalti/backoff.v1 v1.1.0 // indirect
diff --git a/kernel/go.sum b/kernel/go.sum
index 21e49b50c3..54efef0158 100644
--- a/kernel/go.sum
+++ b/kernel/go.sum
@@ -205,8 +205,8 @@ github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw=
github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/gofrs/flock v0.13.0 h1:95JolYOvGMqeH31+FC7D2+uULf6mG61mEZ/A8dRYMzw=
github.com/gofrs/flock v0.13.0/go.mod h1:jxeyy9R1auM5S6JYDBhDt+E2TCo7DkratH4Pgi8P+Z0=
-github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
-github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
+github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
+github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g=
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k=
github.com/gonutz/w32/v2 v2.12.1 h1:ZTWg6ZlETDfWK1Qxx+rdWQdQWZwfhiXoyvxzFYdgsUY=
@@ -219,6 +219,8 @@ github.com/google/go-querystring v1.2.0/go.mod h1:8IFJqpSRITyJ8QhQ13bmbeMBDfmeEJ
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
+github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
+github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/google/pprof v0.0.0-20250607225305-033d6d78b36a h1://KbezygeMJZCSHH+HgUZiTeSoiuFspbMg1ge+eFj18=
github.com/google/pprof v0.0.0-20250607225305-033d6d78b36a/go.mod h1:5hDyRhoBCxViHszMt12TnOpEI4VVi+U8Gm9iphldiMA=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@@ -308,6 +310,8 @@ github.com/mitchellh/go-ps v1.0.0 h1:i6ampVEEF4wQFF+bkYfwYgY+F/uYJDktmvLPf7qIgjc
github.com/mitchellh/go-ps v1.0.0/go.mod h1:J4lOc8z8yJs6vUwklHw2XEIiT4z4C40KtWVN3nvg8Pg=
github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=
github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
+github.com/modelcontextprotocol/go-sdk v1.6.1 h1:0zOSupjKUxPKSocPT1Wtago+mUHU2/uZ4xSOY0FGReU=
+github.com/modelcontextprotocol/go-sdk v1.6.1/go.mod h1:kzm3kzFL1/+AziGOE0nUs3gvPoNxMCvkxokMkuFapXQ=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
@@ -374,6 +378,10 @@ github.com/samber/lo v1.53.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRo
github.com/sashabaranov/go-openai v1.41.2 h1:vfPRBZNMpnqu8ELsclWcAvF19lDNgh1t6TVfFFOPiSM=
github.com/sashabaranov/go-openai v1.41.2/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=
github.com/scylladb/termtables v0.0.0-20191203121021-c4c0b6d42ff4/go.mod h1:C1a7PQSMz9NShzorzCiG2fk9+xuCgLkPeCvMHYR2OWg=
+github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
+github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
+github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
+github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
github.com/shirou/gopsutil/v4 v4.26.4 h1:B4SXVbcwTyrocPHEmWBC4uCYr4Xcu3MK1TXqbprAOWY=
github.com/shirou/gopsutil/v4 v4.26.4/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=
github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=
@@ -459,6 +467,8 @@ github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 h1:+C0TIdyyYmzadGaL/HBL
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ=
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
+github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
+github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
@@ -513,6 +523,8 @@ golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
+golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
+golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -566,8 +578,8 @@ golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
-golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
-golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
+golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
+golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
diff --git a/kernel/mcp/client/convert.go b/kernel/mcp/client/convert.go
new file mode 100644
index 0000000000..5e516a2dcb
--- /dev/null
+++ b/kernel/mcp/client/convert.go
@@ -0,0 +1,105 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package client
+
+import (
+ "github.com/siyuan-note/siyuan/kernel/mcp/tools"
+)
+
+func convertMCPSchema(inputSchema any) tools.ToolSchema {
+ schema := tools.ToolSchema{Type: "object"}
+
+ if inputSchema == nil {
+ return schema
+ }
+
+ m, ok := inputSchema.(map[string]any)
+ if !ok {
+ return schema
+ }
+
+ if t, ok := m["type"].(string); ok && t != "" {
+ schema.Type = t
+ }
+
+ if props, ok := m["properties"].(map[string]any); ok {
+ schema.Properties = make(map[string]tools.Property)
+ for name, prop := range props {
+ schema.Properties[name] = convertMCPProperty(prop)
+ }
+ }
+
+ if req, ok := m["required"].([]any); ok {
+ schema.Required = make([]string, 0, len(req))
+ for _, r := range req {
+ if s, ok := r.(string); ok {
+ schema.Required = append(schema.Required, s)
+ }
+ }
+ }
+
+ return schema
+}
+
+func convertMCPProperty(val any) tools.Property {
+ prop := tools.Property{}
+
+ m, ok := val.(map[string]any)
+ if !ok {
+ return prop
+ }
+
+ if t, ok := m["type"].(string); ok && t != "" {
+ prop.Type = t
+ }
+
+ if desc, ok := m["description"].(string); ok {
+ prop.Description = desc
+ }
+
+ if enums, ok := m["enum"].([]any); ok {
+ prop.Enum = make([]string, 0, len(enums))
+ for _, e := range enums {
+ if s, ok := e.(string); ok {
+ prop.Enum = append(prop.Enum, s)
+ }
+ }
+ }
+
+ if items, ok := m["items"].(map[string]any); ok {
+ itemProp := convertMCPProperty(items)
+ prop.Items = &itemProp
+ }
+
+ if nested, ok := m["properties"].(map[string]any); ok {
+ prop.Properties = make(map[string]tools.Property)
+ for name, p := range nested {
+ prop.Properties[name] = convertMCPProperty(p)
+ }
+ }
+
+ if req, ok := m["required"].([]any); ok {
+ prop.Required = make([]string, 0, len(req))
+ for _, r := range req {
+ if s, ok := r.(string); ok {
+ prop.Required = append(prop.Required, s)
+ }
+ }
+ }
+
+ return prop
+}
diff --git a/kernel/mcp/client/mcp.go b/kernel/mcp/client/mcp.go
new file mode 100644
index 0000000000..ab918b8262
--- /dev/null
+++ b/kernel/mcp/client/mcp.go
@@ -0,0 +1,221 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package client
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "os/exec"
+ "strings"
+ "time"
+
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/mcp/tools"
+)
+
+const (
+ mcpTimeout = 30 * time.Second
+)
+
+type Connection struct {
+ ServerName string
+ Session *mcp.ClientSession
+ Cmd *exec.Cmd // non-nil for stdio servers
+}
+
+func ConnectServers(servers []conf.MCPServer) []Connection {
+ var connections []Connection
+
+ for _, server := range servers {
+ if !server.Enabled {
+ continue
+ }
+
+ session, cmd, err := connectServer(server)
+ if err != nil {
+ logging.LogWarnf("mcp: server [%s] connect failed: %s", server.Name, err)
+ continue
+ }
+
+ listCtx, listCancel := context.WithTimeout(context.Background(), mcpTimeout)
+ toolList, err := session.ListTools(listCtx, nil)
+ listCancel()
+ if err != nil {
+ logging.LogWarnf("mcp: server [%s] list tools failed: %s", server.Name, err)
+ session.Close()
+ if cmd != nil && cmd.Process != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ }
+ continue
+ }
+
+ registered := 0
+ for _, t := range toolList.Tools {
+ tool := t
+ name := "mcp_" + sanitize(server.Name) + "_" + sanitize(tool.Name)
+ desc := tool.Description
+ if !strings.HasPrefix(desc, "[MCP]") {
+ desc = "[MCP:" + server.Name + "] " + desc
+ }
+
+ tools.Registry[name] = &tools.Tool{
+ Name: name,
+ Description: desc,
+ InputSchema: convertMCPSchema(tool.InputSchema),
+ Handler: mcpToolHandler(session, tool.Name),
+ }
+ registered++
+ }
+
+ connections = append(connections, Connection{
+ ServerName: server.Name,
+ Session: session,
+ Cmd: cmd,
+ })
+ logging.LogInfof("mcp: server [%s] connected, %d tools registered", server.Name, registered)
+ }
+
+ return connections
+}
+
+func CloseConnections(connections []Connection) {
+ for _, conn := range connections {
+ if conn.Session != nil {
+ conn.Session.Close()
+ }
+ if conn.Cmd != nil && conn.Cmd.Process != nil {
+ conn.Cmd.Process.Kill()
+ conn.Cmd.Wait()
+ }
+ }
+}
+
+func connectServer(server conf.MCPServer) (*mcp.ClientSession, *exec.Cmd, error) {
+ c := mcp.NewClient(&mcp.Implementation{Name: "siyuan", Version: "3.0"}, nil)
+
+ switch server.Type {
+ case "stdio":
+ return connectStdio(c, server)
+ case "http":
+ return connectHTTP(c, server)
+ default:
+ return nil, nil, fmt.Errorf("unsupported server type: %s", server.Type)
+ }
+}
+
+func connectStdio(client *mcp.Client, server conf.MCPServer) (*mcp.ClientSession, *exec.Cmd, error) {
+ if server.Command == "" {
+ return nil, nil, fmt.Errorf("command is required for stdio server")
+ }
+
+ cmd := exec.Command(server.Command, server.Args...)
+ stdin, err := cmd.StdinPipe()
+ if err != nil {
+ return nil, nil, fmt.Errorf("stdin pipe: %w", err)
+ }
+ stdout, err := cmd.StdoutPipe()
+ if err != nil {
+ return nil, nil, fmt.Errorf("stdout pipe: %w", err)
+ }
+ cmd.Stderr = io.Discard
+
+ if err := cmd.Start(); err != nil {
+ return nil, nil, fmt.Errorf("start command: %w", err)
+ }
+
+ connectCtx, connectCancel := context.WithTimeout(context.Background(), mcpTimeout)
+ defer connectCancel()
+ transport := &mcp.IOTransport{Reader: stdout, Writer: stdin}
+ session, err := client.Connect(connectCtx, transport, nil)
+ if err != nil {
+ cmd.Process.Kill()
+ cmd.Wait()
+ return nil, cmd, fmt.Errorf("connect: %w", err)
+ }
+
+ return session, cmd, nil
+}
+
+func connectHTTP(client *mcp.Client, server conf.MCPServer) (*mcp.ClientSession, *exec.Cmd, error) {
+ if server.URL == "" {
+ return nil, nil, fmt.Errorf("url is required for http server")
+ }
+
+ transport := &mcp.StreamableClientTransport{
+ Endpoint: server.URL,
+ }
+
+ connectCtx, connectCancel := context.WithTimeout(context.Background(), mcpTimeout)
+ defer connectCancel()
+ session, err := client.Connect(connectCtx, transport, nil)
+ if err != nil {
+ return nil, nil, fmt.Errorf("connect: %w", err)
+ }
+
+ return session, nil, nil
+}
+
+func mcpToolHandler(session *mcp.ClientSession, toolName string) func(args map[string]interface{}) (tools.CallToolResult, error) {
+ return func(args map[string]interface{}) (tools.CallToolResult, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), mcpTimeout)
+ defer cancel()
+
+ result, err := session.CallTool(ctx, &mcp.CallToolParams{
+ Name: toolName,
+ Arguments: args,
+ })
+ if err != nil {
+ return tools.CallToolResult{
+ Content: []tools.ContentItem{{Type: "text", Text: fmt.Sprintf("mcp tool error: %s", err.Error())}},
+ IsError: true,
+ }, nil
+ }
+
+ var textParts []string
+ for _, content := range result.Content {
+ if textContent, ok := content.(*mcp.TextContent); ok {
+ textParts = append(textParts, textContent.Text)
+ }
+ }
+ text := strings.Join(textParts, "\n")
+ if text == "" {
+ text = "(empty result)"
+ }
+
+ syr := tools.CallToolResult{
+ IsError: result.IsError,
+ Content: []tools.ContentItem{{Type: "text", Text: text}},
+ }
+ return syr, nil
+ }
+}
+
+func sanitize(s string) string {
+ var sb strings.Builder
+ for _, r := range s {
+ if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '_' || r == '-' {
+ sb.WriteRune(r)
+ } else {
+ sb.WriteByte('_')
+ }
+ }
+ return sb.String()
+}