Skip to content

fix: unable to fetch tools for MCP - #16583

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
Haruko386:mian
Jul 3, 2026
Merged

JinHai-CN merged 3 commits into
infiniflow:mainfrom
Haruko386:mian

Conversation

@Haruko386

@Haruko386 Haruko386 commented Jul 3, 2026 •

Copy link
Copy Markdown
Member

Summary

bug:
img_v3_02138_72100ff8-2d92-46d2-8ef0-05b1c44f2dcg


fixed:

image

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jul 3, 2026
@coderabbitai

coderabbitai Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: fce73a98-c964-43bc-8d7e-07fafe584f09

📥 Commits

Reviewing files that changed from the base of the PR and between e1f1f03 and c99d3b9.

📒 Files selected for processing (1)
  • internal/service/mcp.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/service/mcp.go

📝 Walkthrough

Walkthrough

Adds 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.

Changes

Chatbot Info Route Test

Layer / File(s) Summary
Route registration test
internal/router/router_test.go
Adds a test that sets up the router, sends a GET request to the chatbot info endpoint, and asserts the response is not 404 and returns a CodeUnauthorized error.

MCP Tool Fetching

Layer / File(s) Summary
Timeout parsing and tool-fetch helpers
internal/service/mcp.go
Adds strconv import and introduces optionalFloat64, fetchMCPTools, and jsonMapStringValues helpers for timeout parsing and remote MCP tool requests.
CreateMCPServer fetches and persists tools
internal/service/mcp.go
Adds a Timeout field to CreateMCPServerRequest, validates timeout bounds, and stores fetched remote tools in variables["tools"].
UpdateMCPServer refreshes tools when inputs change
internal/service/mcp.go
Detects update changes, parses an optional timeout, refreshes tools when needed, and reuses existing tools otherwise.

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
Loading

Poem

A hop, a fetch, a timeout so neat,
Fresh tools arrive on rabbit feet.
The chatbot gate still says “nope” at the door,
While the MCP stash holds tools galore.
🐇✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: fixing MCP tool fetching.
Description check ✅ Passed The PR description matches the required Summary section and explains the fix with before/after context.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Haruko386 Haruko386 added the ci Continue Integration label Jul 3, 2026
@Haruko386
Haruko386 marked this pull request as draft July 3, 2026 03:12
@Haruko386
Haruko386 marked this pull request as ready for review July 3, 2026 03:12

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
internal/service/mcp.go (1)

144-149: 🩺 Stability & Availability | 🔵 Trivial | ⚖️ Poor tradeoff

CreateMCPServer 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 via context.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 (see internal/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

📥 Commits

Reviewing files that changed from the base of the PR and between 1aa8abe and e1f1f03.

📒 Files selected for processing (2)
  • internal/router/router_test.go
  • internal/service/mcp.go

Comment thread internal/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"`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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.

Comment thread internal/service/mcp.go
Comment on lines +178 to +228
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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

sed -n '1,280p' internal/service/mcp.go

Repository: infiniflow/ragflow

Length of output: 8848


🏁 Script executed:

rg -n "type JSONMap|safeJSONMap|FetchTools|maxMCPFetchTimeoutSec|defaultMCPFetchTimeoutSec" internal

Repository: 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.go

Repository: 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.go

Repository: 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 common

Repository: 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)
PY

Repository: infiniflow/ragflow

Length of output: 322


Preserve template values and bound the timeout before converting it to time.Duration.

  • jsonMapStringValues drops 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.
  • fetchMCPTools also accepts arbitrarily large timeoutSeconds; the float→time.Duration conversion 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.

Comment thread internal/service/mcp.go Resolved
@JinHai-CN
JinHai-CN merged commit ee94271 into infiniflow:main Jul 3, 2026
3 checks passed
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 3, 2026
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 6, 2026
@Haruko386
Haruko386 deleted the mian branch July 14, 2026 02:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants