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

Daniel02a97f0dc837
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.go
index 6942abe676..6b551cd681 100644
--- a/kernel/agent/agent.go
+++ b/kernel/agent/agent.go
@@ -111,15 +111,16 @@ const (
// 这些参数会并入死循环签名,避免 agent 对不同 url/query/sql 的合法连续调用被误判;
// 同时对同一参数反复调用(真死循环)仍能正确触发终止。
var toolSignatureKeys = map[string][]string{
- "web_fetch": {"url", "format"},
- "web_search": {"query"},
- "sql": {"sql", "stmt"},
- "search": {"query", "keyword"},
- "outline": {"id", "doc_id"},
- "system": {"action"},
- "workspace": {"action"},
- "sync": {"action"},
- "todo_write": {"todos"},
+ "web_fetch": {"url", "format"},
+ "web_search": {"query"},
+ "http_request": {"action", "url"},
+ "sql": {"sql", "stmt"},
+ "search": {"query", "keyword"},
+ "outline": {"id", "doc_id"},
+ "system": {"action"},
+ "workspace": {"action"},
+ "sync": {"action"},
+ "todo_write": {"todos"},
}
// buildDoomSignature 用 toolName + action + 关键参数构造死循环签名。
@@ -294,22 +295,22 @@ type SessionEntryStep struct {
}
type agentCheckpoint struct {
- ID string `json:"id"`
- Title string `json:"title"`
- Titled bool `json:"titled"`
- Entries []SessionEntry `json:"entries"`
- PromptTokens int `json:"promptTokens"`
- CompletionTokens int `json:"completionTokens"`
- TotalDuration int64 `json:"totalDuration"`
- CreatedAt int64 `json:"createdAt"`
- UpdatedAt int64 `json:"updatedAt"`
- MessageHistory []string `json:"messageHistory,omitempty"`
- Snapshots []string `json:"snapshots,omitempty"`
- AlwaysAllow bool `json:"alwaysAllow,omitempty"`
- ContextTokens int `json:"contextTokens,omitempty"`
+ ID string `json:"id"`
+ Title string `json:"title"`
+ Titled bool `json:"titled"`
+ Entries []SessionEntry `json:"entries"`
+ PromptTokens int `json:"promptTokens"`
+ CompletionTokens int `json:"completionTokens"`
+ TotalDuration int64 `json:"totalDuration"`
+ CreatedAt int64 `json:"createdAt"`
+ UpdatedAt int64 `json:"updatedAt"`
+ MessageHistory []string `json:"messageHistory,omitempty"`
+ Snapshots []string `json:"snapshots,omitempty"`
+ AlwaysAllow bool `json:"alwaysAllow,omitempty"`
+ ContextTokens int `json:"contextTokens,omitempty"`
ContextTokenBreakdown map[string]int `json:"contextTokenBreakdown,omitempty"`
- ContextCachedTokens int `json:"contextCachedTokens,omitempty"`
- ContextLimit int `json:"contextLimit,omitempty"`
+ ContextCachedTokens int `json:"contextCachedTokens,omitempty"`
+ ContextLimit int `json:"contextLimit,omitempty"`
}
func AgentChat(ctx context.Context, client *openai.Client, model string, sessionID string, userMessage string, language string, references []Reference, editorCtx EditorContext, pluginActions []PluginAction, regenerate bool, confirmTimeout time.Duration, maxRetries int) <-chan AgentEvent {
diff --git a/kernel/mcp/tools/http_request.go b/kernel/mcp/tools/http_request.go
new file mode 100644
index 0000000000..5e737e7fc9
--- /dev/null
+++ b/kernel/mcp/tools/http_request.go
@@ -0,0 +1,81 @@
+// 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 (
+ "fmt"
+
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+// HTTPRequestTool 通用 HTTP 调用工具,供智能体访问需要鉴权的 REST API(如微信读书网关)。
+// 与 web_fetch 的区别:支持自定义 method/headers/body,且文本类响应(含 JSON)原样返回而非转 Markdown。
+// 用 action 承载 method(get/post/put/delete/patch),从而零改动复用 agent 的确认机制——
+// GET 命中 safeActions["get"] 免确认,POST 等写操作触发 UI 确认 + 写前快照。
+var HTTPRequestTool = &Tool{
+ Name: "http_request",
+ Description: "Send an HTTP request to a REST API and return the raw text response (JSON is kept as-is). action (HTTP method): get (default)/post/put/delete/patch. url (http/https), headers (object), body (string). Use this instead of web_fetch when you need POST, custom headers (e.g. Authorization), or raw JSON responses.",
+ InputSchema: ToolSchema{
+ Type: "object",
+ Properties: map[string]Property{
+ "action": {
+ Type: "string",
+ Description: "HTTP method. Defaults to get.",
+ Enum: []string{"get", "post", "put", "delete", "patch"},
+ },
+ "url": {Type: "string", Description: "The request URL (must start with http:// or https://)"},
+ "headers": {
+ Type: "object",
+ Description: "Optional request headers, e.g. {\"Authorization\":\"Bearer ...\", \"Content-Type\":\"application/json\"}.",
+ Properties: map[string]Property{},
+ },
+ "body": {Type: "string", Description: "Optional request body for post/put/patch."},
+ },
+ Required: []string{"url"},
+ },
+ Handler: httpRequestHandler,
+}
+
+func init() {
+ register(HTTPRequestTool)
+}
+
+func httpRequestHandler(args map[string]interface{}) (CallToolResult, error) {
+ action, _ := args["action"].(string)
+ rawURL, _ := args["url"].(string)
+
+ headers := map[string]string{}
+ if hs, ok := args["headers"].(map[string]interface{}); ok {
+ for k, v := range hs {
+ headers[k] = fmt.Sprintf("%v", v)
+ }
+ }
+ body, _ := args["body"].(string)
+
+ statusCode, contentType, text, err := util.HTTPRequest(action, rawURL, headers, body)
+ if err != nil {
+ return CallToolResult{
+ Content: []ContentItem{{Type: "text", Text: "http_request error: " + err.Error()}},
+ IsError: true,
+ }, nil
+ }
+
+ result := fmt.Sprintf("HTTP %d %s\n\n%s", statusCode, contentType, text)
+ return CallToolResult{
+ Content: []ContentItem{{Type: "text", Text: result}},
+ }, nil
+}
diff --git a/kernel/util/httprequest.go b/kernel/util/httprequest.go
new file mode 100644
index 0000000000..cf9da819ac
--- /dev/null
+++ b/kernel/util/httprequest.go
@@ -0,0 +1,163 @@
+// 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 (
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/imroc/req/v3"
+ "github.com/siyuan-note/httpclient"
+)
+
+const (
+ maxHTTPRequestBytes = 5 * 1024 * 1024 // text/html、text/plain、application/json 等文本类响应上限
+ maxHTTPRequestFileBytes = 10 * 1024 * 1024 // 二进制响应落盘上限
+ maxHTTPRequestChars = 50000
+)
+
+// CheckHostSSRF 校验主机名解析出的 IP 不落在内网/回环等不可达地址段,
+// 防止智能体被诱导发起 SSRF 攻击。web_fetch 与 http_request 共用此校验。
+func CheckHostSSRF(host string) error {
+ ips, err := net.LookupIP(host)
+ if err != nil {
+ return errors.New("failed to resolve host: " + err.Error())
+ }
+ for _, ip := range ips {
+ if ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsPrivate() || ip.IsUnspecified() {
+ return errors.New("access to private/internal IP is prohibited")
+ }
+ }
+ return nil
+}
+
+// HTTPRequest 发起一次通用 HTTP 调用,供智能体 http_request 工具使用。
+// 与 WebFetch 不同:本函数不做 HTML→Markdown 转换,文本类响应(含 JSON/XML)原样返回,
+// 便于智能体直接消费 REST API 的 JSON 输出。method 取值:GET/POST/PUT/DELETE/PATCH。
+// 返回的 text 为响应正文(文本类)或落盘后的文件路径(二进制类)。
+func HTTPRequest(method, rawURL string, headers map[string]string, body string) (statusCode int, contentType string, text string, err error) {
+ u, err := url.Parse(rawURL)
+ if err != nil || (u.Scheme != "http" && u.Scheme != "https") {
+ return 0, "", "", errors.New("URL must start with http:// or https://")
+ }
+ if u.Host == "" {
+ return 0, "", "", errors.New("URL has no host")
+ }
+
+ if serr := CheckHostSSRF(u.Hostname()); serr != nil {
+ return 0, "", "", serr
+ }
+
+ method = strings.ToUpper(strings.TrimSpace(method))
+ if method == "" {
+ method = "GET"
+ }
+
+ request := httpclient.NewBrowserRequest()
+ for k, v := range headers {
+ request.SetHeader(k, v)
+ }
+ if body != "" && method != "GET" && method != "HEAD" {
+ request.SetBody(body)
+ }
+
+ resp, err := sendByMethod(request, method, rawURL)
+ if err != nil {
+ return 0, "", "", errors.New("request failed: " + err.Error())
+ }
+ if resp == nil {
+ return 0, "", "", errors.New("nil response")
+ }
+ defer resp.Body.Close()
+
+ statusCode = resp.StatusCode
+ contentType = resp.Header.Get("Content-Type")
+
+ maxReadBytes := int64(maxHTTPRequestBytes)
+ if !isTextContentType(contentType) {
+ maxReadBytes = maxHTTPRequestFileBytes
+ }
+ // ContentLength 为 -1(chunked)时跳过大小预检,交由 LimitReader 兜底截断。
+ if resp.ContentLength > maxReadBytes {
+ return statusCode, contentType, "", errors.New("response too large")
+ }
+
+ respBody, rerr := io.ReadAll(io.LimitReader(resp.Body, maxReadBytes))
+ if rerr != nil {
+ return statusCode, contentType, "", errors.New("read body failed: " + rerr.Error())
+ }
+
+ // 二进制响应落盘,返回文件路径,供智能体按需进一步处理。
+ if !isTextContentType(contentType) {
+ importDir := filepath.Join(TempDir, "import")
+ if merr := os.MkdirAll(importDir, 0755); merr != nil {
+ return statusCode, contentType, "", errors.New("create import dir failed: " + merr.Error())
+ }
+ filename := extractFilename(rawURL, contentType)
+ filePath := filepath.Join(importDir, filename)
+ if werr := os.WriteFile(filePath, respBody, 0644); werr != nil {
+ return statusCode, contentType, "", errors.New("write file failed: " + werr.Error())
+ }
+ return statusCode, contentType, fmt.Sprintf("Saved to: %s (%d bytes)", filePath, len(respBody)), nil
+ }
+
+ return statusCode, contentType, truncateRunes(string(respBody), maxHTTPRequestChars), nil
+}
+
+// sendByMethod 按 method 分发请求,统一走 NewBrowserRequest 返回的 *req.Request。
+func sendByMethod(request *req.Request, method, rawURL string) (*req.Response, error) {
+ switch method {
+ case "GET", "":
+ return request.Get(rawURL)
+ case "POST":
+ return request.Post(rawURL)
+ case "PUT":
+ return request.Put(rawURL)
+ case "DELETE":
+ return request.Delete(rawURL)
+ case "PATCH":
+ return request.Patch(rawURL)
+ default:
+ return nil, fmt.Errorf("unsupported method: %s", method)
+ }
+}
+
+// isTextContentType 判断 Content-Type 是否为可直接展示给智能体的文本类响应。
+// 覆盖 text/*、application/json、application/xml、application/*+json 等。
+func isTextContentType(contentType string) bool {
+ ct := strings.ToLower(strings.TrimSpace(strings.SplitN(contentType, ";", 2)[0]))
+ if ct == "" {
+ return false
+ }
+ if strings.HasPrefix(ct, "text/") {
+ return true
+ }
+ switch ct {
+ case "application/json", "application/xml":
+ return true
+ }
+ if strings.HasPrefix(ct, "application/") && (strings.HasSuffix(ct, "+json") || strings.HasSuffix(ct, "+xml")) {
+ return true
+ }
+ return false
+}
diff --git a/kernel/util/webfetch.go b/kernel/util/webfetch.go
index 1819523926..2f4f20c589 100644
--- a/kernel/util/webfetch.go
+++ b/kernel/util/webfetch.go
@@ -21,7 +21,6 @@ import (
"fmt"
"io"
"mime"
- "net"
"net/url"
"os"
"path"
@@ -48,15 +47,8 @@ func WebFetch(rawURL, format string) (string, error) {
return "", errors.New("URL has no host")
}
- host := u.Hostname()
- ips, err := net.LookupIP(host)
- if err != nil {
- return "", errors.New("failed to resolve host: " + err.Error())
- }
- for _, ip := range ips {
- if ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsPrivate() || ip.IsUnspecified() {
- return "", errors.New("access to private/internal IP is prohibited")
- }
+ if err := CheckHostSSRF(u.Hostname()); err != nil {
+ return "", err
}
resp, err := httpclient.NewBrowserRequest().Get(rawURL)