Skip to content

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

:sparkles: Support Model Context Protocol (MCP) https://github.com/siyuan-note/siyuan/issues/13795

Danielb56232dc8c35
diff --git a/kernel/mcp/tools/web_search.go b/kernel/mcp/tools/web_search.go
new file mode 100644
index 0000000000..b3d3545013
--- /dev/null
+++ b/kernel/mcp/tools/web_search.go
@@ -0,0 +1,54 @@
+// 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 tools
+
+import (
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+var WebSearchTool = &Tool{
+ Name: "web_search",
+ Description: "Search the web using Exa search engine. Returns search results as text.\n- query: Search keywords (required).",
+ InputSchema: ToolSchema{
+ Type: "object",
+ Properties: map[string]Property{
+ "query": {Type: "string", Description: "Search query keywords"},
+ },
+ Required: []string{"query"},
+ },
+ Handler: webSearchHandler,
+}
+
+func init() {
+ register(WebSearchTool)
+}
+
+func webSearchHandler(args map[string]interface{}) (CallToolResult, error) {
+ query, _ := args["query"].(string)
+
+ result, err := util.WebSearch(query, "")
+ if err != nil {
+ return CallToolResult{
+ Content: []ContentItem{{Type: "text", Text: "web_search error: " + err.Error()}},
+ IsError: true,
+ }, nil
+ }
+
+ return CallToolResult{
+ Content: []ContentItem{{Type: "text", Text: result}},
+ }, nil
+}
diff --git a/kernel/util/websearch.go b/kernel/util/websearch.go
new file mode 100644
index 0000000000..8f62b0d9ca
--- /dev/null
+++ b/kernel/util/websearch.go
@@ -0,0 +1,130 @@
+// 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 util
+
+import (
+ "encoding/json"
+ "errors"
+ "strings"
+
+ "github.com/siyuan-note/httpclient"
+)
+
+const (
+ defaultExaURL = "https://mcp.exa.ai/mcp"
+ maxWebSearchChars = 50000
+)
+
+type mcpRequest struct {
+ JSONRPC string `json:"jsonrpc"`
+ ID int `json:"id"`
+ Method string `json:"method"`
+ Params mcpParams `json:"params"`
+}
+
+type mcpParams struct {
+ Name string `json:"name"`
+ Arguments map[string]interface{} `json:"arguments"`
+}
+
+type mcpResponse struct {
+ Result *mcpResult `json:"result,omitempty"`
+}
+
+type mcpResult struct {
+ Content []mcpContent `json:"content"`
+}
+
+type mcpContent struct {
+ Type string `json:"type"`
+ Text string `json:"text"`
+}
+
+func WebSearch(query, exaApiKey string) (string, error) {
+ url := defaultExaURL
+ if exaApiKey != "" {
+ url += "?exaApiKey=" + exaApiKey
+ }
+
+ reqBody := mcpRequest{
+ JSONRPC: "2.0",
+ ID: 1,
+ Method: "tools/call",
+ Params: mcpParams{
+ Name: "web_search_exa",
+ Arguments: map[string]interface{}{
+ "query": query,
+ "type": "auto",
+ "numResults": 8,
+ "livecrawl": "fallback",
+ },
+ },
+ }
+
+ resp, err := httpclient.NewBrowserRequest().SetBody(reqBody).Post(url)
+ if err != nil {
+ return "", errors.New("web search failed: " + err.Error())
+ }
+ defer resp.Body.Close()
+
+ body := resp.String()
+ text := parseMcpResponse(body)
+ if text == "" {
+ return "No search results found. Please try a different query.", nil
+ }
+
+ return truncateRunes(text, maxWebSearchChars), nil
+}
+
+func parseMcpResponse(body string) string {
+ if text := parseMcpJSON(body); text != "" {
+ return text
+ }
+
+ for _, line := range strings.Split(body, "\n") {
+ line = strings.TrimSpace(line)
+ if strings.HasPrefix(line, "data:") {
+ payload := strings.TrimSpace(line[5:])
+ if text := parseMcpJSON(payload); text != "" {
+ return text
+ }
+ }
+ }
+
+ return ""
+}
+
+func parseMcpJSON(payload string) string {
+ payload = strings.TrimSpace(payload)
+ if !strings.HasPrefix(payload, "{") {
+ return ""
+ }
+
+ var resp mcpResponse
+ if err := json.Unmarshal([]byte(payload), &resp); err != nil {
+ return ""
+ }
+ if resp.Result == nil {
+ return ""
+ }
+ for _, item := range resp.Result.Content {
+ if item.Text != "" {
+ return item.Text
+ }
+ }
+ return ""
+}