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: Preserve MCP request scopes for legacy protocols https://github.com/siyuan-note/siyuan/issues/18530
Daniele0a6ea804d1c
diff --git a/kernel/mcp/request_scope.go b/kernel/mcp/request_scope.gonew file mode 100644index 0000000000..c00941ad55--- /dev/null+++ b/kernel/mcp/request_scope.go@@ -0,0 +1,74 @@+// 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 mcp++import (+ "context"+ "errors"+ "net/http"+ "sync"++ "github.com/google/uuid"+ mcpsdk "github.com/modelcontextprotocol/go-sdk/mcp"+ "github.com/siyuan-note/siyuan/kernel/model"+)++const requestOperationScopeHeader = "X-Siyuan-Mcp-Request-Scope"++var (+ errMCPRequestOperationScopeClosed = errors.New("MCP request operation scope is closed")+ requestOperationScopes sync.Map // 键为请求 ID,值为 context.Context。+)++// withEncryptedBoxOperationScope 为当前 HTTP 响应注册加密笔记本操作作用域。+func withEncryptedBoxOperationScope(handler http.Handler) http.Handler {+ return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {+ requestContext, release := model.WithEncryptedBoxOperationScope(request.Context())+ requestID := uuid.NewString()+ scopedRequest := request.WithContext(requestContext)+ scopedRequest.Header = request.Header.Clone()+ scopedRequest.Header.Set(requestOperationScopeHeader, requestID)+ requestOperationScopes.Store(requestID, requestContext)+ defer func() {+ requestOperationScopes.Delete(requestID)+ release()+ }()++ handler.ServeHTTP(writer, scopedRequest)+ })+}++// requestOperationContext 返回承载当前 HTTP 响应级租约的上下文。+func requestOperationContext(fallback context.Context, request mcpsdk.Request) (context.Context, error) {+ extra := request.GetExtra()+ if extra == nil || extra.Header == nil {+ return fallback, nil+ }+ requestID := extra.Header.Get(requestOperationScopeHeader)+ if requestID == "" {+ return fallback, nil+ }+ value, ok := requestOperationScopes.Load(requestID)+ if !ok {+ return nil, errMCPRequestOperationScopeClosed+ }+ requestContext, ok := value.(context.Context)+ if !ok {+ return nil, errMCPRequestOperationScopeClosed+ }+ return requestContext, nil+}diff --git a/kernel/mcp/request_scope_test.go b/kernel/mcp/request_scope_test.gonew file mode 100644index 0000000000..553d5a7f87--- /dev/null+++ b/kernel/mcp/request_scope_test.go@@ -0,0 +1,58 @@+// 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 mcp++import (+ "context"+ "errors"+ "net/http"+ "net/http/httptest"+ "testing"++ mcpsdk "github.com/modelcontextprotocol/go-sdk/mcp"+)++func TestRequestOperationScopeBridge(t *testing.T) {+ request := httptest.NewRequest(http.MethodPost, "/mcp", nil)+ request.Header.Set(requestOperationScopeHeader, "forged")+ var capturedHeader http.Header++ handler := withEncryptedBoxOperationScope(http.HandlerFunc(func(writer http.ResponseWriter, scopedRequest *http.Request) {+ capturedHeader = scopedRequest.Header.Clone()+ if requestID := scopedRequest.Header.Get(requestOperationScopeHeader); requestID == "" || requestID == "forged" {+ t.Fatalf("request operation scope ID was not replaced: %q", requestID)+ }+ toolRequest := &mcpsdk.CallToolRequest{Extra: &mcpsdk.RequestExtra{Header: scopedRequest.Header}}+ operationContext, err := requestOperationContext(context.Background(), toolRequest)+ if err != nil {+ t.Fatal(err)+ }+ if operationContext != scopedRequest.Context() {+ t.Fatal("tool request did not resolve the current HTTP operation context")+ }+ writer.WriteHeader(http.StatusNoContent)+ }))++ handler.ServeHTTP(httptest.NewRecorder(), request)+ if request.Header.Get(requestOperationScopeHeader) != "forged" {+ t.Fatal("request operation scope wrapper mutated the original header")+ }+ toolRequest := &mcpsdk.CallToolRequest{Extra: &mcpsdk.RequestExtra{Header: capturedHeader}}+ if _, err := requestOperationContext(context.Background(), toolRequest); !errors.Is(err, errMCPRequestOperationScopeClosed) {+ t.Fatalf("released request operation scope returned unexpected error: %v", err)+ }+}diff --git a/kernel/mcp/server.go b/kernel/mcp/server.goindex b69d43eef1..f3c600e253 100644--- a/kernel/mcp/server.go+++ b/kernel/mcp/server.go@@ -19,6 +19,7 @@ package mcpimport ("context""encoding/json"+ "errors""fmt""net/http""sync"@@ -123,11 +124,9 @@ func isModernRequest(request *http.Request) bool {}func serveHTTP(handler http.Handler) gin.HandlerFunc {+ scopedHandler := withEncryptedBoxOperationScope(handler)return func(ginContext *gin.Context) {- requestContext, release := model.WithEncryptedBoxOperationScope(ginContext.Request.Context())- defer release()- request := ginContext.Request.WithContext(requestContext)- handler.ServeHTTP(ginContext.Writer, request)+ scopedHandler.ServeHTTP(ginContext.Writer, ginContext.Request)}}@@ -177,9 +176,18 @@ func syncTool(server *mcpsdk.Server, name string, tool *tools.Tool) {}releaseBoxLeases := func() {}if tool.BoxLeaseResolver != nil {- releaseBoxLeases, err = model.AcquireEncryptedBoxOperations(ctx, tool.BoxLeaseResolver(arguments))+ leaseContext, contextErr := requestOperationContext(ctx, request)+ if contextErr != nil {+ logging.LogWarnf("mcp: acquire request operation scope for tool [%s] failed: %v", name, contextErr)+ return toolErrorResult(contextErr.Error()), nil+ }+ releaseBoxLeases, err = model.AcquireEncryptedBoxOperations(leaseContext, tool.BoxLeaseResolver(arguments))if err != nil {- return toolErrorResult("encrypted notebook is locked, please unlock it first"), nil+ if errors.Is(err, model.ErrEncryptedBoxNotUnlocked) {+ return toolErrorResult("encrypted notebook is locked, please unlock it first"), nil+ }+ logging.LogWarnf("mcp: acquire encrypted notebook operations for tool [%s] failed: %v", name, err)+ return toolErrorResult(err.Error()), nil}}defer releaseBoxLeases()diff --git a/kernel/mcp/server_test.go b/kernel/mcp/server_test.goindex b18f1e5368..584c6aec57 100644--- a/kernel/mcp/server_test.go+++ b/kernel/mcp/server_test.go@@ -33,8 +33,9 @@ func newTestHTTPServer(t *testing.T) (*mcpsdk.Server, *httptest.Server) {t.Helper()server := newServer()syncTool(server, "echo", &tools.Tool{- Name: "echo",- Description: "Echo text",+ Name: "echo",+ Description: "Echo text",+ BoxLeaseResolver: func(map[string]any) []string { return nil },InputSchema: tools.ToolSchema{Type: "object",Properties: map[string]tools.Property{@@ -46,7 +47,7 @@ func newTestHTTPServer(t *testing.T) (*mcpsdk.Server, *httptest.Server) {return tools.CallToolResult{Content: []tools.ContentItem{{Type: "text", Text: text}}}, nil},})- httpServer := httptest.NewServer(newHTTPHandler(server))+ httpServer := httptest.NewServer(withEncryptedBoxOperationScope(newHTTPHandler(server)))t.Cleanup(httpServer.Close)return server, httpServer}@@ -412,56 +413,82 @@ func TestModernProtocolHeadersAndResult(t *testing.T) {}func TestLegacyProtocolSession(t *testing.T) {- _, httpServer := newTestHTTPServer(t)- initialize := `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"legacy","version":"1.0.0"}}}`- response := postMCP(t, httpServer.URL, initialize, nil)- if response.StatusCode != http.StatusOK {- t.Fatalf("unexpected initialize status: %d", response.StatusCode)- }- sessionID := response.Header.Get("Mcp-Session-Id")- if sessionID == "" {- t.Fatal("legacy initialize did not create a session ID")- }- var initializeResponse struct {- Result struct {- ProtocolVersion string `json:"protocolVersion"`- } `json:"result"`- }- decodeResponse(t, response, &initializeResponse)- if initializeResponse.Result.ProtocolVersion != "2025-11-25" {- t.Fatalf("unexpected legacy protocol version: %q", initializeResponse.Result.ProtocolVersion)- }+ for _, protocolVersion := range []string{"2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"} {+ t.Run(protocolVersion, func(t *testing.T) {+ _, httpServer := newTestHTTPServer(t)+ initialize := `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"` + protocolVersion + `","capabilities":{},"clientInfo":{"name":"legacy","version":"1.0.0"}}}`+ response := postMCP(t, httpServer.URL, initialize, nil)+ if response.StatusCode != http.StatusOK {+ t.Fatalf("unexpected initialize status: %d", response.StatusCode)+ }+ sessionID := response.Header.Get("Mcp-Session-Id")+ if sessionID == "" {+ t.Fatal("legacy initialize did not create a session ID")+ }+ var initializeResponse struct {+ Result struct {+ ProtocolVersion string `json:"protocolVersion"`+ } `json:"result"`+ }+ decodeResponse(t, response, &initializeResponse)+ if initializeResponse.Result.ProtocolVersion != protocolVersion {+ t.Fatalf("unexpected legacy protocol version: %q", initializeResponse.Result.ProtocolVersion)+ }- response = postMCP(t, httpServer.URL,- `{"jsonrpc":"2.0","method":"notifications/initialized","params":{}}`,- map[string]string{- "MCP-Protocol-Version": "2025-11-25",- "Mcp-Session-Id": sessionID,- })- if response.StatusCode != http.StatusAccepted {- t.Fatalf("unexpected initialized status: %d", response.StatusCode)- }- response.Body.Close()+ response = postMCP(t, httpServer.URL,+ `{"jsonrpc":"2.0","method":"notifications/initialized","params":{}}`,+ map[string]string{+ "MCP-Protocol-Version": protocolVersion,+ "Mcp-Session-Id": sessionID,+ })+ if response.StatusCode != http.StatusAccepted {+ t.Fatalf("unexpected initialized status: %d", response.StatusCode)+ }+ response.Body.Close()++ response = postMCP(t, httpServer.URL,+ `{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}`,+ map[string]string{+ "MCP-Protocol-Version": protocolVersion,+ "Mcp-Session-Id": sessionID,+ })+ if response.StatusCode != http.StatusOK {+ t.Fatalf("unexpected tools/list status: %d", response.StatusCode)+ }+ var listResponse struct {+ Result struct {+ Tools []struct {+ Name string `json:"name"`+ } `json:"tools"`+ } `json:"result"`+ }+ decodeResponse(t, response, &listResponse)+ if len(listResponse.Result.Tools) != 1 || listResponse.Result.Tools[0].Name != "echo" {+ t.Fatalf("unexpected legacy tool list: %#v", listResponse.Result.Tools)+ }- response = postMCP(t, httpServer.URL,- `{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}`,- map[string]string{- "MCP-Protocol-Version": "2025-11-25",- "Mcp-Session-Id": sessionID,+ response = postMCP(t, httpServer.URL,+ `{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"echo","arguments":{"text":"hello"}}}`,+ map[string]string{+ "MCP-Protocol-Version": protocolVersion,+ "Mcp-Session-Id": sessionID,+ })+ if response.StatusCode != http.StatusOK {+ t.Fatalf("unexpected tools/call status: %d", response.StatusCode)+ }+ var callResponse struct {+ Result struct {+ Content []struct {+ Text string `json:"text"`+ } `json:"content"`+ IsError bool `json:"isError"`+ } `json:"result"`+ }+ decodeResponse(t, response, &callResponse)+ if callResponse.Result.IsError || len(callResponse.Result.Content) != 1 || callResponse.Result.Content[0].Text != "hello" {+ t.Fatalf("unexpected legacy tool result: %#v", callResponse.Result)+ }})- if response.StatusCode != http.StatusOK {- t.Fatalf("unexpected tools/list status: %d", response.StatusCode)- }- var listResponse struct {- Result struct {- Tools []struct {- Name string `json:"name"`- } `json:"tools"`- } `json:"result"`- }- decodeResponse(t, response, &listResponse)- if len(listResponse.Result.Tools) != 1 || listResponse.Result.Tools[0].Name != "echo" {- t.Fatalf("unexpected legacy tool list: %#v", listResponse.Result.Tools)}}diff --git a/kernel/model/crypto_lifecycle.go b/kernel/model/crypto_lifecycle.goindex c7cdcb88fc..302f061b3a 100644--- a/kernel/model/crypto_lifecycle.go+++ b/kernel/model/crypto_lifecycle.go@@ -149,7 +149,7 @@ func AcquireEncryptedBoxOperation(boxID string) error {lifecycle.condition.Broadcast()}if lifecycle.state != EncryptedBoxStateUnlocked {- return errors.New("encrypted notebook is not unlocked")+ return ErrEncryptedBoxNotUnlocked}lifecycle.activeOperations++return nil@@ -188,6 +188,13 @@ type encryptedBoxOperationScope struct {type encryptedBoxOperationScopeKey struct{}+var (+ // ErrEncryptedBoxNotUnlocked 表示加密笔记本当前未解锁。+ ErrEncryptedBoxNotUnlocked = errors.New("encrypted notebook is not unlocked")+ // ErrEncryptedBoxOperationScopeClosed 表示响应级操作作用域已经关闭。+ ErrEncryptedBoxOperationScopeClosed = errors.New("encrypted notebook operation scope is closed")+)+// WithEncryptedBoxOperationScope 创建覆盖整个外层响应过程的租约作用域。func WithEncryptedBoxOperationScope(ctx context.Context) (context.Context, func()) {scope := &encryptedBoxOperationScope{boxIDSet: map[string]struct{}{}}@@ -208,6 +215,9 @@ func AcquireEncryptedBoxOperations(ctx context.Context, boxIDs []string) (releassortedBoxIDs = append(sortedBoxIDs, boxID)}sort.Strings(sortedBoxIDs)+ if len(sortedBoxIDs) == 0 {+ return func() {}, nil+ }if scope, ok := ctx.Value(encryptedBoxOperationScopeKey{}).(*encryptedBoxOperationScope); ok {err = scope.acquire(sortedBoxIDs)@@ -235,7 +245,7 @@ func (scope *encryptedBoxOperationScope) acquire(boxIDs []string) error {scope.lock.Lock()defer scope.lock.Unlock()if scope.closed {- return errors.New("encrypted notebook operation scope is closed")+ return ErrEncryptedBoxOperationScopeClosed}for _, boxID := range boxIDs {if _, exists := scope.boxIDSet[boxID]; exists {diff --git a/kernel/model/crypto_lifecycle_test.go b/kernel/model/crypto_lifecycle_test.goindex c7b6bc4694..6a2aae80c6 100644--- a/kernel/model/crypto_lifecycle_test.go+++ b/kernel/model/crypto_lifecycle_test.go@@ -18,6 +18,8 @@ package modelimport ("bytes"+ "context"+ "errors""os""path/filepath""testing"@@ -28,6 +30,30 @@ import ("github.com/siyuan-note/siyuan/kernel/util")+func TestAcquireEncryptedBoxOperationsAllowsEmptyClosedScope(t *testing.T) {+ ctx, closeScope := WithEncryptedBoxOperationScope(context.Background())+ closeScope()+ release, err := AcquireEncryptedBoxOperations(ctx, nil)+ if err != nil {+ t.Fatalf("empty encrypted notebook operation set was rejected: %v", err)+ }+ release()+}++func TestAcquireEncryptedBoxOperationsReportsClosedScope(t *testing.T) {+ boxID := "20260803190000-abcdefg"+ cleanup := prepareEncryptedBoxLifecycleTest(t, boxID)+ defer cleanup()+ setEncryptedBoxState(boxID, EncryptedBoxStateUnlocked)++ ctx, closeScope := WithEncryptedBoxOperationScope(context.Background())+ closeScope()+ _, err := AcquireEncryptedBoxOperations(ctx, []string{boxID})+ if !errors.Is(err, ErrEncryptedBoxOperationScopeClosed) {+ t.Fatalf("closed encrypted notebook operation scope returned unexpected error: %v", err)+ }+}+func TestEncryptedBoxLifecycleWaitsForActiveOperations(t *testing.T) {boxID := "20260731160000-abcdefg"cleanup := prepareEncryptedBoxLifecycleTest(t, boxID)