Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

fix(agent): wire MCP tools and preserve execution errors (#19628)

Sbaaoui Idriss7b12ad2c97a5
diff --git a/internal/agent/component/agent.go b/internal/agent/component/agent.go
index e0853f0123..f7e2f6c039 100644
--- a/internal/agent/component/agent.go
+++ b/internal/agent/component/agent.go
@@ -88,6 +88,8 @@ type AgentParam struct {
Tools []string // Agent-visible tool names resolved into Eino BaseTool instances
ToolParams map[string]map[string]any // node-level tool constructor params keyed by tool name
SubAgents []SubAgentTool
+ MCP any // Saved MCP selections, decoded and validated when tools are built.
+ ToolTimeout time.Duration
MaxRounds int
MessageHistoryWindowSize int // number of prior conversation turns to include; zero disables history
OptimizeMultiTurn bool
@@ -664,6 +666,11 @@ func buildAgentTools(ctx context.Context, p AgentParam) ([]einotool.BaseTool, er
if err != nil {
return nil, err
}
+ mcpTools, err := buildAgentMCPTools(ctx, dao.DB, p.MCP, p.ToolTimeout)
+ if err != nil {
+ return nil, err
+ }
+ tools = append(tools, mcpTools...)
toolNames := make(map[string]struct{}, len(tools)+len(p.SubAgents))
for _, tool := range tools {
info, err := tool.Info(ctx)
@@ -1484,6 +1491,9 @@ func mergeAgentParam(base AgentParam, inputs map[string]any) AgentParam {
f := v
p.MaxTokens = &f
}
+ if enabled, ok := boolFrom(inputs, "maxTokensEnabled"); ok && !enabled {
+ p.MaxTokens = nil
+ }
if v, ok := floatFrom(inputs, "temperature"); ok {
f := v
p.Temperature = &f
@@ -1506,6 +1516,12 @@ func mergeAgentParam(base AgentParam, inputs map[string]any) AgentParam {
if v, ok := stringFrom(inputs, "base_url"); ok {
p.BaseURL = v
}
+ if v, ok := inputs["mcp"]; ok {
+ p.MCP = v
+ }
+ if v, ok := intFrom(inputs, "tool_timeout"); ok {
+ p.ToolTimeout = time.Duration(v) * time.Second
+ }
if tools, params, subAgents, ok := agentToolsFrom(inputs, "tools"); ok {
p.Tools = tools
p.SubAgents = subAgents
diff --git a/internal/agent/component/agent_mcp.go b/internal/agent/component/agent_mcp.go
new file mode 100644
index 0000000000..34d20985cc
--- /dev/null
+++ b/internal/agent/component/agent_mcp.go
@@ -0,0 +1,78 @@
+package component
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "maps"
+ "slices"
+ "time"
+
+ einotool "github.com/cloudwego/eino/components/tool"
+ "gorm.io/gorm"
+ "ragflow/internal/agent/runtime"
+ agenttool "ragflow/internal/agent/tool"
+ "ragflow/internal/dao"
+ "ragflow/internal/utility"
+)
+
+// buildAgentMCPTools binds the saved tool selection to tenant-owned servers.
+// Discovery happens when configuring the server; execution uses those schemas.
+func buildAgentMCPTools(ctx context.Context, db *gorm.DB, raw any, timeout time.Duration) ([]einotool.BaseTool, error) {
+ if raw == nil {
+ return nil, nil
+ }
+ var selections []struct {
+ ID string `json:"mcp_id"`
+ Tools map[string]utility.Tool `json:"tools"`
+ }
+ data, err := json.Marshal(raw)
+ if err != nil {
+ return nil, fmt.Errorf("encode Agent MCP configuration: %w", err)
+ }
+ if err := json.Unmarshal(data, &selections); err != nil {
+ return nil, fmt.Errorf("decode Agent MCP configuration: %w", err)
+ }
+ var tools []einotool.BaseTool
+ toolIndex := 0
+ for _, selection := range selections {
+ if len(selection.Tools) == 0 {
+ continue
+ }
+ state, _, err := runtime.GetStateFromContext[*runtime.CanvasState](ctx)
+ if err != nil || state == nil || db == nil {
+ return nil, fmt.Errorf("MCP server %q: missing runtime tenant or database", selection.ID)
+ }
+ tenantID, _ := state.Sys["tenant_id"].(string)
+ if tenantID == "" {
+ return nil, fmt.Errorf("MCP server %q: missing runtime tenant", selection.ID)
+ }
+ server, err := dao.NewMCPServerDAO().GetByIDAndTenant(ctx, db, selection.ID, tenantID)
+ if err != nil {
+ return nil, fmt.Errorf("load MCP server %q: %w", selection.ID, err)
+ }
+ headers := make(map[string]string, len(server.Headers))
+ for key, value := range server.Headers {
+ s, ok := value.(string)
+ if !ok {
+ return nil, fmt.Errorf("MCP server %q: header %q must be a string", selection.ID, key)
+ }
+ headers[key] = s
+ }
+ variables := make(map[string]string, len(server.Variables))
+ for key, value := range server.Variables {
+ variables[key] = fmt.Sprint(value)
+ }
+ for _, name := range slices.Sorted(maps.Keys(selection.Tools)) {
+ descriptor := selection.Tools[name]
+ descriptor.Name = name
+ adapter := agenttool.NewMCPToolAdapterWithOptions(descriptor, utility.CallOptions{
+ URL: server.URL, ServerType: server.ServerType, Headers: headers, Variables: variables, Timeout: timeout,
+ })
+ adapter.SetVisibleName(fmt.Sprintf("%s_%d", name, toolIndex))
+ toolIndex++
+ tools = append(tools, adapter)
+ }
+ }
+ return tools, nil
+}
diff --git a/internal/agent/component/agent_mcp_test.go b/internal/agent/component/agent_mcp_test.go
new file mode 100644
index 0000000000..4cd7ff741c
--- /dev/null
+++ b/internal/agent/component/agent_mcp_test.go
@@ -0,0 +1,185 @@
+package component
+
+import (
+ "encoding/json"
+ "fmt"
+ "github.com/cloudwego/eino/compose"
+ "github.com/cloudwego/eino/flow/agent/react"
+ "github.com/cloudwego/eino/schema"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "ragflow/internal/agent/runtime"
+ "ragflow/internal/entity"
+ "ragflow/internal/entity/models"
+ "ragflow/internal/utility"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+func TestAgentMCPRequiresRuntimeServer(t *testing.T) {
+ p := mergeAgentParam(AgentParam{}, map[string]any{"mcp": []any{map[string]any{"mcp_id": "missing", "tools": map[string]any{"route": map[string]any{"name": "route"}}}}})
+ if _, err := buildAgentTools(t.Context(), p); err == nil {
+ t.Fatal("configured MCP tools silently discarded")
+ }
+}
+
+func TestAgentMCPModelDispatch(t *testing.T) {
+ // Keep this test non-parallel: it swaps the global MCP network hooks.
+ db := setupComponentTestDB(t)
+ if err := db.AutoMigrate(&entity.MCPServer{}); err != nil {
+ t.Fatal(err)
+ }
+ pushComponentDB(t, db)
+ lookup := utility.LookupHost
+ utility.LookupHost = func(string) ([]string, error) { return []string{"8.8.8.8"}, nil }
+ t.Cleanup(func() { utility.LookupHost = lookup })
+ var dispatched atomic.Bool
+ mcp := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == "DELETE" {
+ w.WriteHeader(204)
+ return
+ }
+ var req struct {
+ ID int `json:"id"`
+ Method string `json:"method"`
+ Params struct {
+ Name string `json:"name"`
+ Arguments map[string]string `json:"arguments"`
+ } `json:"params"`
+ }
+ json.NewDecoder(r.Body).Decode(&req)
+ w.Header().Set("Content-Type", "application/json")
+ switch req.Method {
+ case "initialize":
+ fmt.Fprintf(w, `{"jsonrpc":"2.0","id":%d,"result":{"protocolVersion":"2025-03-26","capabilities":{}}}`, req.ID)
+ case "notifications/initialized":
+ w.WriteHeader(202)
+ case "tools/call":
+ dispatched.Store(true)
+ if req.Params.Name != "route" || req.Params.Arguments["origin"] != "大连路站" {
+ t.Errorf("unexpected dispatch: %+v", req)
+ }
+ fmt.Fprintf(w, `{"jsonrpc":"2.0","id":%d,"result":{"content":[{"type":"text","text":"metro route"}]}}`, req.ID)
+ }
+ }))
+ defer mcp.Close()
+ pinned := utility.PinnedHTTPClient
+ utility.PinnedHTTPClient = func(string, string, time.Duration) *http.Client { return mcp.Client() }
+ t.Cleanup(func() { utility.PinnedHTTPClient = pinned })
+ if err := db.Create(&entity.MCPServer{ID: "mcp", TenantID: "tenant", Name: "route server", URL: mcp.URL, ServerType: utility.TransportStreamableHTTP}).Error; err != nil {
+ t.Fatal(err)
+ }
+ state := runtime.NewCanvasState("run", "task")
+ state.Sys["tenant_id"] = "tenant"
+ ctx := withStateForTest(t.Context(), state)
+ p := mergeAgentParam(AgentParam{}, map[string]any{"mcp": []any{map[string]any{"mcp_id": "mcp", "tools": map[string]any{"route": map[string]any{"name": "route", "inputSchema": map[string]any{"type": "object", "properties": map[string]any{"origin": map[string]any{"type": "string"}}, "required": []string{"origin"}}}}}}})
+ tools, err := buildAgentTools(ctx, p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var requests atomic.Int32
+ llm := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ Tools []struct {
+ Function struct {
+ Name string `json:"name"`
+ Parameters map[string]any `json:"parameters"`
+ } `json:"function"`
+ } `json:"tools"`
+ ToolChoice string `json:"tool_choice"`
+ Messages []models.Message `json:"messages"`
+ }
+ json.NewDecoder(r.Body).Decode(&req)
+ if len(req.Tools) != 1 || req.Tools[0].Function.Name != "route_0" || req.ToolChoice != "auto" {
+ t.Errorf("tools missing from model request: %+v", req)
+ }
+ if len(req.Tools) == 1 {
+ properties, _ := req.Tools[0].Function.Parameters["properties"].(map[string]any)
+ if _, ok := properties["origin"]; !ok {
+ t.Error("MCP argument schema missing from model request")
+ }
+ }
+ if requests.Add(1) == 1 {
+ w.Header().Set("Content-Type", "application/json")
+ io.WriteString(w, `{"choices":[{"index":0,"finish_reason":"tool_calls","message":{"role":"assistant","tool_calls":[{"id":"call1","type":"function","function":{"name":"route_0","arguments":"{\"origin\":\"大连路站\"}"}}]}}]}`)
+ } else {
+ raw, _ := json.Marshal(req.Messages)
+ if !strings.Contains(string(raw), "metro route") {
+ t.Error("MCP result missing from follow-up model request")
+ }
+ w.Header().Set("Content-Type", "text/event-stream")
+ io.WriteString(w, "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"metro answer\"},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n")
+ }
+ }))
+ defer llm.Close()
+ driver := models.NewOpenAIModel(map[string]string{"default": llm.URL}, models.URLSuffix{Chat: "chat/completions"})
+ modelName, key := "test", "test"
+ chat := models.NewEinoChatModel(models.NewChatModel(driver, &modelName, &models.APIConfig{ApiKey: &key}), nil)
+ a, err := react.NewAgent(ctx, &react.AgentConfig{ToolCallingModel: chat, ToolsConfig: compose.ToolsNodeConfig{Tools: tools}, StreamToolCallChecker: scanAllStreamForToolCall, MaxStep: 3})
+ if err != nil {
+ t.Fatal(err)
+ }
+ stream, err := a.Stream(ctx, []*schema.Message{schema.UserMessage("how to go from 大连路站 to 水清三村公寓 by metro")})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer stream.Close()
+ var content string
+ for {
+ msg, err := stream.Recv()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ content += msg.Content
+ }
+ if !dispatched.Load() || content != "metro answer" {
+ t.Fatalf("dispatch=%v content=%q", dispatched.Load(), content)
+ }
+ state.Sys["tenant_id"] = "other-tenant"
+ if _, err := buildAgentTools(ctx, p); err == nil {
+ t.Fatal("cross-tenant MCP access allowed")
+ }
+}
+
+func TestAgentMCPToolNamesDoNotCollide(t *testing.T) {
+ db := setupComponentTestDB(t)
+ if err := db.AutoMigrate(&entity.MCPServer{}); err != nil {
+ t.Fatal(err)
+ }
+ pushComponentDB(t, db)
+ for _, id := range []string{"first", "second"} {
+ if err := db.Create(&entity.MCPServer{ID: id, TenantID: "tenant", Name: id, URL: "https://example.com/mcp", ServerType: utility.TransportStreamableHTTP}).Error; err != nil {
+ t.Fatal(err)
+ }
+ }
+ state := runtime.NewCanvasState("run", "task")
+ state.Sys["tenant_id"] = "tenant"
+ ctx := withStateForTest(t.Context(), state)
+ p := AgentParam{Tools: nil, MCP: []any{
+ map[string]any{"mcp_id": "first", "tools": map[string]any{"search": map[string]any{"name": "web_search"}}},
+ map[string]any{"mcp_id": "second", "tools": map[string]any{"search": map[string]any{"name": "web_search"}}},
+ }}
+ tools, err := buildAgentTools(ctx, p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := []string{"search_0", "search_1"}
+ if len(tools) != len(want) {
+ t.Fatalf("got %d tools, want %d", len(tools), len(want))
+ }
+ for i, tool := range tools {
+ info, err := tool.Info(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if info.Name != want[i] {
+ t.Errorf("tool %d name = %q, want %q", i, info.Name, want[i])
+ }
+ }
+}
diff --git a/internal/agent/component/agent_test.go b/internal/agent/component/agent_test.go
index 3db5ae3a05..d4633db4ff 100644
--- a/internal/agent/component/agent_test.go
+++ b/internal/agent/component/agent_test.go
@@ -1317,3 +1317,16 @@ func TestAgent_ReActExhaustsSteps(t *testing.T) {
t.Errorf("sqlmock expectations: %v", err)
}
}
+
+func TestAgentDisabledMaxTokens(t *testing.T) {
+ p := mergeAgentParam(AgentParam{}, map[string]any{"max_tokens": 256, "maxTokensEnabled": false})
+ if p.MaxTokens != nil {
+ t.Fatalf("disabled max_tokens still applied: %d", *p.MaxTokens)
+ }
+ for _, inputs := range []map[string]any{{"max_tokens": 256}, {"max_tokens": 256, "maxTokensEnabled": true}} {
+ p = mergeAgentParam(AgentParam{}, inputs)
+ if p.MaxTokens == nil || *p.MaxTokens != 256 {
+ t.Fatal("enabled or unflagged max_tokens lost")
+ }
+ }
+}
diff --git a/internal/agent/component/message.go b/internal/agent/component/message.go
index 14b9f1e831..9ae96d8eb1 100644
--- a/internal/agent/component/message.go
+++ b/internal/agent/component/message.go
@@ -442,6 +442,9 @@ func (m *MessageComponent) resolveDeferredTemplate(ctx context.Context, text str
if err != nil {
return "", true, fmt.Errorf("Message: consume deferred Agent stream: %w", err)
}
+ if resultErr, _ := result["_ERROR"].(string); strings.TrimSpace(resultErr) != "" {
+ return "", true, fmt.Errorf("Message: consume deferred Agent stream: %s", resultErr)
+ }
finalText := visible.String()
if result != nil {
if completedContent, ok := result["content"].(string); ok {
diff --git a/internal/agent/component/message_test.go b/internal/agent/component/message_test.go
index ca86c7227c..a4e71fca5d 100644
--- a/internal/agent/component/message_test.go
+++ b/internal/agent/component/message_test.go
@@ -382,6 +382,27 @@ func TestMessage_DeferredStreamUsesCompletedContent(t *testing.T) {
}
}
+func TestMessage_DeferredStreamSurfacesResultError(t *testing.T) {
+ c, _ := NewMessageComponent(nil)
+ state := canvas.NewCanvasState("run-deferred-error", "task-deferred-error")
+ state.SetVar("agent_0", "content", &runtime.DeferredStream{
+ Open: func(_ context.Context, _ runtime.AgentDeltaSink) (map[string]any, error) {
+ return map[string]any{"_ERROR": "**ERROR**: upstream 402"}, nil
+ },
+ })
+ ctx := runtime.WithDeferredNodeRegistry(withStateForTest(t.Context(), state))
+ completed := false
+ runtime.RegisterDeferredNode(ctx, "agent_0", func() { completed = true })
+
+ _, err := c.Invoke(ctx, nil, map[string]any{"text": "{{agent_0@content}}"})
+ if err == nil || !strings.Contains(err.Error(), "upstream 402") {
+ t.Fatalf("Invoke error = %v, want upstream 402", err)
+ }
+ if completed {
+ t.Fatal("deferred node completed after result _ERROR")
+ }
+}
+
func TestMessage_FormalizedContentFallback(t *testing.T) {
c, _ := NewMessageComponent(nil)
state := canvas.NewCanvasState("run-5", "task-5")
diff --git a/internal/agent/tool/mcp.go b/internal/agent/tool/mcp.go
index 424b53e044..ebb62052a3 100644
--- a/internal/agent/tool/mcp.go
+++ b/internal/agent/tool/mcp.go
@@ -18,9 +18,7 @@
//
// Wraps a single MCP-server-discovered tool (utility/mcpclient.Tool) as
// an eino BaseTool so it can be invoked from inside the Agent's
-// ReAct loop. The MCP tool list is fetched via utility/mcpclient
-// (which currently only implements tools/list discovery; tools/call
-// invocation is the next step on the MCP client).
+// ReAct loop. Discovery and invocation use the utility MCP client.
package tool
import (
@@ -50,11 +48,14 @@ import (
// a URL (legacy callers) fall back to the "not yet wired"
// sentinel so existing call sites don't break.
type MCPToolAdapter struct {
- mcpTool mcpclient.Tool
- serverURL string
- headers map[string]string
- timeout time.Duration
- httpClient *http.Client
+ mcpTool mcpclient.Tool
+ visibleName string
+ serverType string
+ variables map[string]string
+ serverURL string
+ headers map[string]string
+ timeout time.Duration
+ httpClient *http.Client
}
// NewMCPToolAdapter constructs a wrapper for a single MCP tool.
@@ -91,8 +92,18 @@ func NewMCPToolAdapterFull(t mcpclient.Tool, serverURL string, headers map[strin
}
}
+// NewMCPToolAdapterWithOptions preserves the server transport and header variables.
+func NewMCPToolAdapterWithOptions(t mcpclient.Tool, opts mcpclient.CallOptions) *MCPToolAdapter {
+ return &MCPToolAdapter{mcpTool: t, serverURL: opts.URL, serverType: opts.ServerType, headers: opts.Headers, variables: opts.Variables, timeout: opts.Timeout, httpClient: opts.HTTPClient}
+}
+
// Name returns the underlying MCP tool name.
-func (m *MCPToolAdapter) Name() string { return m.mcpTool.Name }
+func (m *MCPToolAdapter) Name() string {
+ if m.visibleName != "" {
+ return m.visibleName
+ }
+ return m.mcpTool.Name
+}
// Info returns eino-compatible tool metadata. The MCP client stores the
// full inputSchema object ({"type":"object","properties":{...},"required":
@@ -105,7 +116,7 @@ func (m *MCPToolAdapter) Name() string { return m.mcpTool.Name }
// nil so callers emit an empty object schema instead of an invalid schema.
func (m *MCPToolAdapter) Info(_ context.Context) (*schema.ToolInfo, error) {
info := &schema.ToolInfo{
- Name: m.mcpTool.Name,
+ Name: m.Name(),
Desc: m.mcpTool.Description,
}
if len(m.mcpTool.InputSchema) == 0 {
@@ -138,7 +149,8 @@ func (m *MCPToolAdapter) InvokableRun(ctx context.Context, argumentsInJSON strin
}
res, err := mcpclient.CallTool(ctx, mcpclient.CallOptions{
URL: m.serverURL,
- ServerType: mcpclient.TransportStreamableHTTP,
+ ServerType: m.serverType,
+ Variables: m.variables,
Headers: m.headers,
ToolName: m.mcpTool.Name,
Arguments: argsJSON,
@@ -198,3 +210,6 @@ func marshalArguments(argumentsInJSON string) (json.RawMessage, error) {
}
return json.RawMessage(argumentsInJSON), nil
}
+
+// SetVisibleName disambiguates the model-facing name while retaining wire name.
+func (m *MCPToolAdapter) SetVisibleName(name string) { m.visibleName = name }
diff --git a/internal/utility/mcp_call.go b/internal/utility/mcp_call.go
index 29479fcf9e..68e0ad9b0f 100644
--- a/internal/utility/mcp_call.go
+++ b/internal/utility/mcp_call.go
@@ -14,17 +14,6 @@
// limitations under the License.
//
-// Phase 3.7: MCP tools/call implementation. The mcp_client.go
-// file handles tools/list discovery; this file adds the
-// tools/call invocation path so the MCPToolAdapter can return
-// real results instead of "not yet implemented" errors.
-//
-// The implementation focuses on the streamable-HTTP transport
-// (spec 2025-03-26) because that is the dominant transport for
-// modern MCP servers. The legacy SSE transport's session
-// lifecycle is more complex; deferring it matches the rest of
-// the package's "loud-fail with a clear error" pattern.
-
package utility
import (
@@ -104,7 +93,13 @@ func CallTool(ctx context.Context, opts CallOptions) (*CallResult, error) {
// declaring the legacy SSE transport get the legacy path.
return callToolStreamableHTTP(connectCtx, opts.URL, headers, opts.HTTPClient, opts.ToolName, opts.Arguments, opts.Timeout)
case TransportSSE:
- return nil, errors.New("MCP tools/call on legacy SSE transport is not yet implemented in Go (Phase 3.7 deferred; use streamable-http)")
+ result, err := requestSSE(connectCtx, opts.URL, headers, opts.HTTPClient, "tools/call", map[string]any{
+ "name": opts.ToolName, "arguments": opts.Arguments,
+ })
+ if err != nil {
+ return nil, err
+ }
+ return parseCallResult(result)
default:
return nil, fmt.Errorf("Unsupported MCP server type.")
}
diff --git a/internal/utility/mcp_call_test.go b/internal/utility/mcp_call_test.go
index 968ced6e0e..42094d0ce8 100644
--- a/internal/utility/mcp_call_test.go
+++ b/internal/utility/mcp_call_test.go
@@ -561,3 +561,59 @@ func TestCallTool_InvalidArgumentsJSON(t *testing.T) {
t.Errorf("error should mention JSON, got %v", err)
}
}
+
+func TestCallToolSSE(t *testing.T) {
+ defer allowLoopbackForTests(t)()
+ pushes := make(chan string, 4)
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /sse", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/event-stream")
+ io.WriteString(w, "event: endpoint\ndata: /messages\n\n")
+ w.(http.Flusher).Flush()
+ for {
+ select {
+ case msg := <-pushes:
+ io.WriteString(w, "event: message\ndata: "+msg+"\n\n")
+ w.(http.Flusher).Flush()
+ case <-r.Context().Done():
+ return
+ }
+ }
+ })
+ var called atomic.Bool
+ mux.HandleFunc("POST /messages", func(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ ID int `json:"id"`
+ Method string `json:"method"`
+ Params struct {
+ Name string `json:"name"`
+ Arguments map[string]string `json:"arguments"`
+ } `json:"params"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ t.Error(err)
+ return
+ }
+ switch req.Method {
+ case "initialize":
+ pushes <- `{"jsonrpc":"2.0","id":0,"result":{"capabilities":{}}}`
+ case "tools/call":
+ called.Store(true)
+ if req.Params.Name != "route" || req.Params.Arguments["origin"] != "大连路站" || req.Params.Arguments["destination"] != "水清三村公寓" {
+ t.Errorf("unexpected call: %+v", req)
+ }
+ raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": req.ID, "result": map[string]any{"content": []map[string]string{{"type": "text", "text": "metro route"}}}})
+ pushes <- string(raw)
+ }
+ w.WriteHeader(http.StatusAccepted)
+ })
+ srv := httptest.NewServer(mux)
+ defer srv.Close()
+ result, err := CallTool(t.Context(), CallOptions{URL: srv.URL + "/sse", ServerType: TransportSSE, HTTPClient: srv.Client(), Timeout: time.Second, ToolName: "route", Arguments: json.RawMessage(`{"origin":"大连路站","destination":"水清三村公寓"}`)})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !called.Load() || result.Text != "metro route" {
+ t.Fatalf("called=%v result=%+v", called.Load(), result)
+ }
+}
diff --git a/internal/utility/mcp_client.go b/internal/utility/mcp_client.go
index 11ba976ada..9b26677b4c 100644
--- a/internal/utility/mcp_client.go
+++ b/internal/utility/mcp_client.go
@@ -367,6 +367,15 @@ func streamableSend(ctx context.Context, client *http.Client, endpoint, sessionI
// ---------- SSE transport ----------
func fetchToolsSSE(ctx context.Context, endpoint string, headers map[string]string, client *http.Client) ([]Tool, error) {
+ result, err := requestSSE(ctx, endpoint, headers, client, "tools/list", nil)
+ if err != nil {
+ return nil, err
+ }
+ return parseToolsResult(result)
+}
+
+// requestSSE initializes a session and performs one JSON-RPC request.
+func requestSSE(ctx context.Context, endpoint string, headers map[string]string, client *http.Client, method string, params any) (json.RawMessage, error) {
streamReq, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, fmt.Errorf("build SSE request: %w", err)
@@ -420,7 +429,10 @@ func fetchToolsSSE(ctx context.Context, endpoint string, headers map[string]stri
}()
postOnce := func(payload jsonRPCRequest) error {
- body, _ := json.Marshal(payload)
+ body, err := json.Marshal(payload)
+ if err != nil {
+ return fmt.Errorf("encode MCP SSE request: %w", err)
+ }
req, err := http.NewRequestWithContext(ctx, http.MethodPost, postURL, bytes.NewReader(body))
if err != nil {
return fmt.Errorf("build SSE POST: %w", err)
@@ -465,7 +477,7 @@ func fetchToolsSSE(ctx context.Context, endpoint string, headers map[string]stri
return nil, err
}
listWaiter := pending.register(1)
- if err = postOnce(jsonRPCRequest{JSONRPC: jsonRPCVersion, ID: 1, Method: "tools/list"}); err != nil {
+ if err = postOnce(jsonRPCRequest{JSONRPC: jsonRPCVersion, ID: 1, Method: method, Params: params}); err != nil {
pending.cancel(1)
return nil, err
}
@@ -474,9 +486,9 @@ func fetchToolsSSE(ctx context.Context, endpoint string, headers map[string]stri
return nil, err
}
if listRes.Error != nil {
- return nil, formatMCPError("tools/list", listRes.Error)
+ return nil, formatMCPError(method, listRes.Error)
}
- return parseToolsResult(listRes.Result)
+ return listRes.Result, nil
}
// waitForEndpoint reads SSE events until an "endpoint" event arrives and