Repository navigation
fix: unable to fetch tools for MCP - #16583
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds a router test for the chatbot info endpoint and updates MCP server create/update flows to validate optional timeouts, fetch remote tools, and persist the fetched tool list. ChangesChatbot Info Route Test
MCP Tool Fetching
Estimated code review effort: 3 (Moderate) | ~20 minutes Sequence Diagram(s)sequenceDiagram
participant Client
participant CreateMCPServer
participant fetchMCPTools
participant RemoteMCPServer
Client->>CreateMCPServer: request with Timeout
CreateMCPServer->>CreateMCPServer: validate timeout range
CreateMCPServer->>fetchMCPTools: fetchMCPTools(...)
fetchMCPTools->>RemoteMCPServer: utility.FetchTools(duration)
RemoteMCPServer-->>fetchMCPTools: tools list
fetchMCPTools-->>CreateMCPServer: tools map
CreateMCPServer->>CreateMCPServer: variables["tools"] = tools
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
internal/service/mcp.go (1)
144-149: 🩺 Stability & Availability | 🔵 Trivial | ⚖️ Poor tradeoffCreateMCPServer now blocks on an external network call using
context.Background().Previously
variables["tools"]was set synchronously with no I/O; now creation depends on a live round trip to the remote MCP endpoint viacontext.Background(), so the fetch can't be cancelled if the incoming HTTP request is aborted or times out upstream. Fixing this fully would require threading a real context through the handler → service call chain (seeinternal/handler/mcp.go:70-95), which is a broader change than this cohort — flagging for awareness rather than blocking here, given severity is mitigated by the recommended upper-bound timeout clamp.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/mcp.go` around lines 144 - 149, CreateMCPServer now performs a remote MCP fetch via fetchMCPTools using context.Background(), so the request cannot be cancelled or timed out when the caller aborts. Update the handler-to-service flow to pass the incoming request context through the MCP path, and have CreateMCPServer (or the service method it calls) use that context instead of Background when calling fetchMCPTools. Keep the variables["tools"] assignment as-is, but ensure the context is threaded from the HTTP handler through internal/service/mcp.go so the network call respects cancellation and upstream deadlines.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/service/mcp.go`:
- Line 67: The client-supplied Timeout field in MCP request handling is only
checked for being positive and can still be arbitrarily large, so add an
explicit upper bound before it reaches fetchMCPTools and utility.FetchTools.
Update the validation path around the request struct and the timeout
parsing/conversion logic so oversized values are rejected early, using the
existing MCP request handling flow and the Timeout field as the anchor for the
fix.
- Around line 346-355: In mcp.go, the update path currently always calls
fetchMCPTools after reading timeoutSeconds, which makes unrelated edits depend
on the remote server. Update the MCP update logic around the fetchMCPTools call
to only re-fetch when tool-relevant fields such as url, server_type, headers, or
variables are actually present/changed in the request; otherwise keep the
existing stored tools value. Use the existing update handling in this function
to detect which fields were supplied and preserve variables["tools"] when no
refresh is needed.
- Around line 178-228: The MCP tool-fetch path is losing template data and can
overflow on large timeouts. Update jsonMapStringValues to preserve all JSONMap
entries by stringifying non-string values instead of dropping them, so
headers/variables still substitute numeric and boolean templates. In
fetchMCPTools, validate or clamp timeoutSeconds before converting it to
time.Duration to prevent overflow on extreme values, while keeping the
defaultMCPFetchTimeoutSec fallback behavior intact.
---
Nitpick comments:
In `@internal/service/mcp.go`:
- Around line 144-149: CreateMCPServer now performs a remote MCP fetch via
fetchMCPTools using context.Background(), so the request cannot be cancelled or
timed out when the caller aborts. Update the handler-to-service flow to pass the
incoming request context through the MCP path, and have CreateMCPServer (or the
service method it calls) use that context instead of Background when calling
fetchMCPTools. Keep the variables["tools"] assignment as-is, but ensure the
context is threaded from the HTTP handler through internal/service/mcp.go so the
network call respects cancellation and upstream deadlines.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: edf51529-54b4-4663-a123-8e82e41908a6
📒 Files selected for processing (2)
internal/router/router_test.gointernal/service/mcp.go
| Description *string `json:"description,omitempty"` | ||
| Variables json.RawMessage `json:"variables,omitempty"` | ||
| Headers json.RawMessage `json:"headers,omitempty"` | ||
| Timeout float64 `json:"timeout,omitempty"` |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
No bounds validation on client-supplied Timeout.
Timeout is taken directly from the request body and flows unchecked into fetchMCPTools/utility.FetchTools, which only guards against <= 0 (see Lines 200-204) but not against very large values. A client can set an arbitrarily large timeout, tying up the request goroutine against a slow/unresponsive MCP endpoint. Combined with the float→duration conversion in fetchMCPTools, this is also vulnerable to implementation-dependent overflow (see comment on Lines 178-228).
Add an upper bound, e.g.:
🛡️ Proposed validation
+const maxMCPFetchTimeoutSec = 60
+
func (s *MCPService) CreateMCPServer(tenantID string, req CreateMCPServerRequest) (*CreateMCPServerResponse, common.ErrorCode, error) {
+ if req.Timeout < 0 || req.Timeout > maxMCPFetchTimeoutSec {
+ return nil, common.CodeDataError, errors.New("Invalid timeout.")
+ }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/service/mcp.go` at line 67, The client-supplied Timeout field in MCP
request handling is only checked for being positive and can still be arbitrarily
large, so add an explicit upper bound before it reaches fetchMCPTools and
utility.FetchTools. Update the validation path around the request struct and the
timeout parsing/conversion logic so oversized values are rejected early, using
the existing MCP request handling flow and the Timeout field as the anchor for
the fix.
| func optionalFloat64(req UpdateMCPServerRequest, key string, defaultValue float64) (float64, error) { | ||
| raw, ok := req[key] | ||
| if !ok || bytes.Equal(bytes.TrimSpace(raw), []byte("null")) { | ||
| return defaultValue, nil | ||
| } | ||
|
|
||
| var value float64 | ||
| if err := json.Unmarshal(raw, &value); err == nil { | ||
| return value, nil | ||
| } | ||
|
|
||
| var text string | ||
| if err := json.Unmarshal(raw, &text); err != nil { | ||
| return defaultValue, fmt.Errorf("%s must be a number", key) | ||
| } | ||
| value, err := strconv.ParseFloat(strings.TrimSpace(text), 64) | ||
| if err != nil { | ||
| return defaultValue, fmt.Errorf("%s must be a number", key) | ||
| } | ||
| return value, nil | ||
| } | ||
|
|
||
| func fetchMCPTools(ctx context.Context, url, serverType string, headers, variables entity.JSONMap, timeoutSeconds float64) (map[string]interface{}, error) { | ||
| if timeoutSeconds <= 0 { | ||
| timeoutSeconds = defaultMCPFetchTimeoutSec | ||
| } | ||
| timeout := time.Duration(timeoutSeconds * float64(time.Second)) | ||
|
|
||
| tools, err := utility.FetchTools(ctx, utility.FetchOptions{ | ||
| URL: url, | ||
| ServerType: serverType, | ||
| Headers: jsonMapStringValues(headers), | ||
| Variables: jsonMapStringValues(variables), | ||
| Timeout: timeout, | ||
| }) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| return toolsAsMap(tools), nil | ||
| } | ||
|
|
||
| func jsonMapStringValues(values entity.JSONMap) map[string]string { | ||
| out := map[string]string{} | ||
| for key, value := range values { | ||
| if text, ok := value.(string); ok { | ||
| out[key] = text | ||
| } | ||
| } | ||
| return out | ||
| } | ||
|
|
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
sed -n '1,280p' internal/service/mcp.goRepository: infiniflow/ragflow
Length of output: 8848
🏁 Script executed:
rg -n "type JSONMap|safeJSONMap|FetchTools|maxMCPFetchTimeoutSec|defaultMCPFetchTimeoutSec" internalRepository: infiniflow/ragflow
Length of output: 2800
🏁 Script executed:
sed -n '300,380p' internal/service/mcp.go && printf '\n---\n' && sed -n '1,220p' internal/utility/mcp_client.go && printf '\n---\n' && sed -n '1,220p' internal/entity/base.goRepository: infiniflow/ragflow
Length of output: 13961
🏁 Script executed:
sed -n '480,530p' internal/service/mcp.go && printf '\n---\n' && sed -n '1,220p' internal/utility/mcp_call.goRepository: infiniflow/ragflow
Length of output: 8559
🏁 Script executed:
rg -n "safe_substitute|Template|headers|variables|authorization_token|tools/list|jsonMapStringValues|renderHeaders" common internal | sed -n '1,240p'Repository: infiniflow/ragflow
Length of output: 23027
🏁 Script executed:
rg -n "timeout.*max|max.*timeout|defaultMCPFetchTimeoutSec|Timeout.*validate|timeoutSeconds" internal commonRepository: infiniflow/ragflow
Length of output: 2030
🏁 Script executed:
python3 - <<'PY'
from string import Template
import math
print("template_int:", Template("${x}").safe_substitute({"x": 5}))
print("template_bool:", Template("${x}").safe_substitute({"x": True}))
print("template_none:", Template("${x}").safe_substitute({"x": None}))
max_ns = 2**63 - 1
threshold = max_ns / 1e9
print("max_int64_ns:", max_ns)
print("overflow_threshold_seconds:", threshold)
print("10_years_seconds:", 10 * 365.25 * 24 * 3600)
PYRepository: infiniflow/ragflow
Length of output: 322
Preserve template values and bound the timeout before converting it to time.Duration.
jsonMapStringValuesdrops any non-string entry, but these maps are passed through header/variable substitution, where numeric/bool values should still be rendered as text instead of disappearing.fetchMCPToolsalso accepts arbitrarily largetimeoutSeconds; the float→time.Durationconversion can overflow on extreme inputs.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/service/mcp.go` around lines 178 - 228, The MCP tool-fetch path is
losing template data and can overflow on large timeouts. Update
jsonMapStringValues to preserve all JSONMap entries by stringifying non-string
values instead of dropping them, so headers/variables still substitute numeric
and boolean templates. In fetchMCPTools, validate or clamp timeoutSeconds before
converting it to time.Duration to prevent overflow on extreme values, while
keeping the defaultMCPFetchTimeoutSec fallback behavior intact.
Summary
bug:

fixed: