Skip to content

Port agent PRs to GO - #16529

Merged
yuzhichang merged 5 commits into
infiniflow:mainfrom
qinling0210:port_to_go
Jul 2, 2026
Merged

yuzhichang merged 5 commits into
infiniflow:mainfrom
qinling0210:port_to_go

Conversation

@qinling0210

Copy link
Copy Markdown
Contributor

Summary

Port the following PRs to GO in this PR

#14210
#14641
#15220
#15228
#15384
#15754
#16413
#16483
#16419
#16361
#16050

@qinling0210 qinling0210 self-assigned this Jul 1, 2026
@coderabbitai

coderabbitai Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

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: eb6bcf84-2008-40d7-86ac-30611be0c314

📥 Commits

Reviewing files that changed from the base of the PR and between 387f26b and 17a4e5d.

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

📝 Walkthrough

Walkthrough

This PR adds MCP server support, safe JSON marshaling, LLM message fitting with sys.files, a BGPT tool, ISO8601 parsing helpers, canvas type filtering, and SSE robustness updates.

Changes

Runtime and protocol changes

Layer / File(s) Summary
MCP protocol types
internal/mcp/types.go
Adds JSON-RPC and MCP protocol constants, payload structs, tool schema types, and constructors for success/error responses and tool results.
MCP dispatch and connector
internal/mcp/server.go, internal/mcp/connector.go
Implements JSON-RPC request handling, tool listing/call routing, argument extraction, and an in-process service connector for dataset/chat listing and retrieval.
MCP handler and route wiring
internal/handler/mcp_server.go, internal/router/router.go, cmd/server_main.go
Adds the HTTP MCP handler, service wrappers, and registers /api/v1/mcp through server startup and router wiring.
Safe JSON marshaling
internal/agent/runtime/json_safe.go, internal/agent/runtime/state.go
Adds SafeJSONMarshal, recursive value cleaning, and uses it for canvas state snapshot encoding.
Canvas and chatbot SSE serialization
internal/agent/canvas/runner.go, internal/service/bot_completion.go
Switches waiting/error run events and chatbot SSE frames to safe marshaling with fallback handling.
LLM sys.files and token fitting
internal/agent/component/llm.go, internal/service/chat_pipeline.go, internal/service/kg/scoring.go, internal/tokenizer/tokenizer.go
Adds sys.files collection/injection, visual-file deduplication, ollama chat suffix handling, stricter thinking parsing, and token-budget trimming helpers. Also updates chat message fitting support.
Chat completion robustness
internal/service/chat_pipeline.go, internal/handler/agent.go
Preserves the default max_tokens value when unset or non-positive, and ensures [DONE] is written when no run events are emitted.
BGPT tool implementation
internal/agent/tool/bgpt.go, internal/agent/tool/registry.go
Adds the BGPT search tool, its request/response types, execution logic, and registry entry.
ISO8601 parsing and agent filters
internal/common/time.go, internal/service/agent_sessions.go, internal/dao/user_canvas.go, internal/service/agent.go, internal/handler/agent.go
Adds flexible ISO8601 parsing helpers, updates agent session date parsing, and threads canvas_type through DAO, service, and handler list paths.

Estimated code review effort: 4 (Complex) | ~75 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client as JSON-RPC client
  participant MCPServer as mcp.Server
  participant Connector as ServiceConnector
  participant DatasetService as DatasetService
  Client->>MCPServer: tools/list or tools/call
  MCPServer->>Connector: dispatch list/chat/retrieval
  Connector->>DatasetService: list datasets / search datasets
  DatasetService-->>Connector: results
  Connector-->>MCPServer: newline-delimited JSON
  MCPServer-->>Client: JSON-RPC response
Loading

Possibly related PRs

  • infiniflow/ragflow#15220: Both PRs modify the LLM prompt/context building to inject sys.files into prompts and multimodal inputs.
  • infiniflow/ragflow#16405: Both PRs modify the SSE completion path in internal/handler/agent.go, including [DONE] handling.
  • infiniflow/ragflow#16455: Both PRs modify the LLM thinking parameter parsing path in internal/agent/component/llm.go.

Suggested labels: 💞 feature, size:XXL

Suggested reviewers: buua436, yuzhichang, Haruko386

Poem

🐰 I hop through MCP doors tonight,
Safe JSON keeps the bytes just right.
I trim the words, I guide the flow,
And make the [DONE] flag show.
Hop! The tools now answer bright.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive The summary section is present, but it is mostly a list of links and lacks the brief purpose/context requested by the template. Add a short summary of what these PRs change and why they are being ported to Go, with a bit of background context.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and matches the main change: porting multiple agent-related PRs to Go.
Docstring Coverage ✅ Passed Docstring coverage is 80.70% which is sufficient. The required threshold is 80.00%.
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.

@qinling0210
qinling0210 marked this pull request as ready for review July 1, 2026 08:08
@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Jul 1, 2026

@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: 13

🧹 Nitpick comments (2)
internal/handler/agent.go (1)

1126-1131: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Reuse WriteChatbotRunEvent for the synthetic terminator.

This branch bypasses the shared [DONE] helper path and drops the error from the synthetic frame write. Keeping both writes on service.WriteChatbotRunEvent will preserve the same flush/error behavior as the normal stream path.

Proposed fix
-		_ = service.WriteChatbotRunEvent(c.Writer, event)
-		if _, err := c.Writer.Write([]byte("data: [DONE]\n\n")); err != nil {
+		if err := service.WriteChatbotRunEvent(c.Writer, event); err != nil {
+			common.Debug("agent chat completions: client disconnected",
+				zap.String("agent_id", req.AgentID),
+				zap.Error(err),
+			)
+			return
+		}
+		if err := service.WriteChatbotRunEvent(c.Writer, canvas.RunEvent{Type: "done"}); err != nil {
 			common.Debug("agent chat completions: failed to write [DONE]",
 				zap.Error(err),
 			)
 		}
🤖 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/handler/agent.go` around lines 1126 - 1131, The streaming terminator
path in agent chat completions is bypassing the shared helper and handling the
synthetic “[DONE]” frame manually, which skips the same flush/error behavior
used elsewhere. Update the branch in agent.go to route the terminator through
service.WriteChatbotRunEvent just like the normal event path, instead of calling
c.Writer.Write directly. Keep the existing debug logging behavior by relying on
the helper’s write handling so the synthetic frame uses the same shared path as
the rest of the stream.
internal/agent/tool/bgpt.go (1)

82-97: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

NewBGPTToolWith does not currently affect HTTP behavior.

The constructor stores helper, but InvokableRun always allocates its own http.Client. That makes the injected dependency ineffective for tests and any shared transport/timeout policy. Route requests through b.helper or remove the helper-based constructor.

Also applies to: 167-168

🤖 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/agent/tool/bgpt.go` around lines 82 - 97, NewBGPTToolWith currently
injects a helper, but BGPTTool.InvokableRun ignores it and creates its own
http.Client, so the constructor has no effect. Update InvokableRun to use
b.helper for request creation/execution (or otherwise thread the helper’s
client/transport through the request path) so injected timeout/transport
behavior is honored; if that’s not intended, remove the helper field and
NewBGPTToolWith/NewBGPTTool in favor of a single constructor.
🤖 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/agent/component/llm.go`:
- Around line 982-1015: fitMessages is dropping non-string message parts because
it only copies Role and Content, which breaks multi-content inputs like
UserInputMultiContent. Update fitMessages to preserve the full schema.Message
payload when building the fitting input and when reconstructing the result, so
message parts such as images/text blocks survive the call to messageFitInRaw.
Use fitMessages, schema.Message, and messageFitInRaw as the key places to adjust
the copy/round-trip logic without mutating the caller’s slice.
- Around line 390-399: The message fitting step is missing on the final
assembled messages, so sys.files and history can still be passed to the model
untrimmed. Update the LLM flow in llm.go around the message assembly and invoker
path so fitting runs after all augmentation in buildMessagesWithImages and the
sys.files injection logic, and before the final Messages: msgs call. Use the
existing fitting helpers on the final msgs slice so the model only receives the
trimmed messages.
- Around line 1029-1054: The message ordering logic in the conversation trimming
code is putting retained turns ahead of the system prompt. Update the slice
handling in the function that builds result from messages so the system message
is preserved as the first element, then build the remaining kept turns
separately and append them after it instead of prepending into the same slice.
- Around line 390-398: The sys.files injection in llm.go only appends to
msgs[len(msgs)-1].Content, which misses visual prompts created by
buildMessagesWithImages when the last user message uses multi-content. Update
the message merge logic in the buildMessagesWithImages flow so sys.files text is
appended into the existing user message payload regardless of whether it is
stored in Content or UserInputMultiContent. Keep the fix localized around the
msgs slice handling and schema.Message user-role branch.

In `@internal/agent/runtime/json_safe.go`:
- Around line 99-102: The reflect.Struct branch in cleanForJSON currently
returns the struct unchanged, so wrapper types like canvasStateJSON and the
WaitingForUserEvent payload still reach marshaling with unsafe nested values.
Update cleanForJSON to recursively walk exported struct fields and also unwrap
ptr/interface values before descending, so nested func/chan values are sanitized
instead of leaking through unchanged. Keep the fix centered in cleanForJSON and
verify the callers in state marshaling and runner fallback now get cleaned
output rather than the raw struct value.
- Around line 85-90: The generic map fallback in cleanForJSON is rebuilding the
map with the original value type, which can panic when nested values change
shape during cleaning. Update the reflect.Map case in json_safe.go to either
construct a map with any/interface values or explicitly coerce each cleaned
entry back to rv.Type().Elem() before SetMapIndex. Make sure the fix keeps
cleanForJSON safe for the reference/state payloads flowing through
bot_completion handling and state serialization.

In `@internal/agent/tool/bgpt.go`:
- Around line 140-146: Cap the upstream request size in bgpt tool handling:
MaxResults is only defaulted in the request builder and can still be arbitrarily
large, which can amplify the full-body read in bgpt.go. Update the request
construction in the code path that builds reqBody in the bgpt tool to clamp
p.MaxResults to a safe upper bound before sending the request, and keep the same
bound enforced anywhere the response is read and processed so the full-response
handling cannot be triggered by an oversized num_results value.
- Around line 186-215: BGPT success handling is ignoring the upstream error
envelope, so a 200 response with an error field is treated as an empty success.
In bgpt.go within the response parsing path after json.Unmarshal into
bgptResponse, check raw.Error before building results and return the JSON error
envelope via bgptErrJSON and the matching Go error when it is present. Keep the
normal results mapping and json.Marshal of bgptEnv unchanged for true success
cases.

In `@internal/handler/mcp_server.go`:
- Around line 148-227: MCPRetrieval currently ignores the advertised
force_refresh flag, so the tool contract is incomplete. Update MCPRetrieval to
read req.ForceRefresh and propagate it into the search path, most likely by
adding a corresponding field to service.SearchDatasetsRequest and using it in
ds.SearchDatasets. Verify the request wiring around SearchDatasetsRequest and
SearchDatasets so the flag changes behavior instead of being silently dropped.
- Around line 79-85: Bound the incoming request body in the MCP server handler
before reading it into memory. In the request handling path that calls
io.ReadAll on c.Request.Body, wrap the body with a size limit (for example via
http.MaxBytesReader or an equivalent limit) and handle the oversized-body error
by returning a bad request response. Keep the change localized to the MCP server
request parsing logic in the handler that reads the body so large HTTP payloads
cannot exhaust memory.

In `@internal/mcp/connector.go`:
- Around line 69-72: The MCP dataset payload built in the connector currently
drops the dataset name, so clients never receive a field that
`ragflow_list_datasets` promises. Update the item construction in `connector.go`
to preserve and emit the dataset name alongside `id` and `description`, using
the existing dataset mapping logic so the payload matches the contract
documented by `ragflow_list_datasets` in `server.go`.

In `@internal/mcp/types.go`:
- Around line 46-50: `JSONRPCResponse` is omitting `id` when it should serialize
as null for parse errors. Update the `JSONRPCResponse` struct so `id` is not
dropped by `omitempty` when `NewParseError()` sets `ID: nil`, and make sure
`internal/mcp/server.go` still uses that helper for parse failures so strict
JSON-RPC clients receive `"id": null` instead of a missing field.

In `@internal/service/chat_pipeline.go`:
- Around line 214-221: The max_tokens override in the chat pipeline is reading
the wrong type, so the configured value is never applied. Update the max_tokens
handling in the chat path that uses llmModelConfig to assert the stored value as
int instead of float64, since buildLLMModelConfig populates it as an int. Keep
the existing 8192 default for missing or non-positive values, but ensure the
branch in the chat pipeline actually picks up the configured max_tokens.

---

Nitpick comments:
In `@internal/agent/tool/bgpt.go`:
- Around line 82-97: NewBGPTToolWith currently injects a helper, but
BGPTTool.InvokableRun ignores it and creates its own http.Client, so the
constructor has no effect. Update InvokableRun to use b.helper for request
creation/execution (or otherwise thread the helper’s client/transport through
the request path) so injected timeout/transport behavior is honored; if that’s
not intended, remove the helper field and NewBGPTToolWith/NewBGPTTool in favor
of a single constructor.

In `@internal/handler/agent.go`:
- Around line 1126-1131: The streaming terminator path in agent chat completions
is bypassing the shared helper and handling the synthetic “[DONE]” frame
manually, which skips the same flush/error behavior used elsewhere. Update the
branch in agent.go to route the terminator through service.WriteChatbotRunEvent
just like the normal event path, instead of calling c.Writer.Write directly.
Keep the existing debug logging behavior by relying on the helper’s write
handling so the synthetic frame uses the same shared path as the rest of the
stream.
🪄 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: 4b0ef9fe-bd89-47d5-a065-27994fdcf6f7

📥 Commits

Reviewing files that changed from the base of the PR and between d770217 and 20ad4d7.

📒 Files selected for processing (19)
  • cmd/server_main.go
  • internal/agent/canvas/runner.go
  • internal/agent/component/llm.go
  • internal/agent/runtime/json_safe.go
  • internal/agent/runtime/state.go
  • internal/agent/tool/bgpt.go
  • internal/agent/tool/registry.go
  • internal/common/time.go
  • internal/dao/user_canvas.go
  • internal/handler/agent.go
  • internal/handler/mcp_server.go
  • internal/mcp/connector.go
  • internal/mcp/server.go
  • internal/mcp/types.go
  • internal/router/router.go
  • internal/service/agent.go
  • internal/service/agent_sessions.go
  • internal/service/bot_completion.go
  • internal/service/chat_pipeline.go

Comment thread internal/agent/component/llm.go Resolved
Comment thread internal/agent/component/llm.go Resolved
Comment thread internal/agent/component/llm.go Resolved
Comment thread internal/agent/component/llm.go Resolved
Comment thread internal/agent/runtime/json_safe.go Resolved
Comment thread internal/handler/mcp_server.go Resolved
Comment thread internal/handler/mcp_server.go Resolved
Comment thread internal/mcp/connector.go Resolved
Comment thread internal/mcp/types.go Resolved
Comment thread internal/service/chat_pipeline.go Resolved
@qinling0210 qinling0210 added the ci Continue Integration label Jul 1, 2026

@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: 7

🧹 Nitpick comments (5)
internal/mcp/connector.go (2)

68-68: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Local desc shadows the desc bool parameter.

Minor readability nit: the local desc string variable shadows the desc bool sort-order parameter in the same function scope.

🤖 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/mcp/connector.go` at line 68, The local desc string in the function
that already takes a desc bool parameter is shadowing the sort-order flag, which
hurts readability. Rename the local variable in the connector logic around the
desc assignment to something distinct, and update its uses in the same function
so the desc bool parameter remains clearly visible and unambiguous.

59-124: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicate item-building logic between ListDatasets and ListChats.

Both methods repeat the same pattern: iterate map records, extract id/name/description via type assertions, marshal to JSON, join with newlines. Consider extracting a shared helper to reduce duplication and centralize the newline-delimited JSON formatting.

♻️ Suggested helper extraction
func toNDJSON(data []map[string]interface{}) string {
	var lines []string
	for _, d := range data {
		item := map[string]interface{}{
			"id":          strField(d, "id"),
			"name":        strField(d, "name"),
			"description": strField(d, "description"),
		}
		b, err := json.Marshal(item)
		if err != nil {
			continue
		}
		lines = append(lines, string(b))
	}
	return strings.Join(lines, "\n")
}

func strField(d map[string]interface{}, key string) string {
	if v, ok := d[key]; ok {
		if s, ok := v.(string); ok {
			return s
		}
	}
	return ""
}
🤖 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/mcp/connector.go` around lines 59 - 124, Both ListDatasets and
ListChats in ServiceConnector duplicate the same record-to-NDJSON formatting
logic, including repeated id/name/description extraction and json.Marshal
handling. Extract that shared loop into a helper (for example, a toNDJSON-style
function plus a small string-field helper) and have both methods call it,
keeping the existing output format and error-skipping behavior unchanged.
internal/agent/runtime/json_safe.go (2)

110-114: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Dead branch: reflect.Interface is unreachable here.

cleanForJSON is always invoked with values obtained via .Interface() (see line 74, 96, 102, 109, 137), so reflect.ValueOf(v) always yields the concrete dynamic type's Kind(), never reflect.Interface. This branch will never execute.

🤖 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/agent/runtime/json_safe.go` around lines 110 - 114, Remove the
unreachable reflect.Interface branch from cleanForJSON in json_safe.go; the
function only sees concrete values from Interface() calls, so this case will
never match. Keep the surrounding reflection handling intact, and let the
existing fallback path cover any non-nil interface values via their underlying
concrete kind.

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

No cycle detection for self-referencing structures.

cleanForJSON recurses unconditionally through pointers, maps, slices, and structs with no visited-set tracking. A cyclic reference reachable from canvas state (e.g. a struct/map containing a back-pointer to an ancestor) would stack-overflow before json.Marshal is even reached. Since this utility exists specifically to make marshaling "safe" against unusual runtime values leaking into state, guarding against cycles (e.g. tracking visited pointers) would strengthen that guarantee.

🤖 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/agent/runtime/json_safe.go` around lines 78 - 144, cleanForJSON
currently recurses through pointers, maps, slices, and structs without tracking
already-seen references, so cyclic values can still stack overflow. Update
cleanForJSON in json_safe.go to maintain a visited set for reference-bearing
values, especially reflect.Ptr and any nested structures reachable through
maps/slices/structs, and short-circuit repeated nodes to a safe nil/placeholder
result. Keep the existing recursive cleanup behavior for non-cyclic values while
adding the cycle guard around the reflect-based traversal logic.
internal/service/dataset.go (1)

1711-1711: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Inconsistent optionality pattern for ForceRefresh.

Every other boolean/scalar field added for optional semantics in this struct (UseKG, Keyword) uses a pointer with omitempty so callers can distinguish "unset" from "explicitly false". ForceRefresh is a plain bool without omitempty, meaning it can never be omitted and there's no way to distinguish an unset flag from an explicit false. Per the MCPRetrieval snippet in internal/handler/mcp_server.go, it's passed through directly (ForceRefresh: req.ForceRefresh), so this may be intentional if there's no meaningful "unset" state for a refresh flag — but worth confirming this matches the intended API semantics.

🤖 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/dataset.go` at line 1711, `ForceRefresh` in the dataset
request struct uses a plain bool while related optional fields like `UseKG` and
`Keyword` use pointer/omitempty semantics, so update the `ForceRefresh` field in
the struct and any related request handling to match the intended API behavior.
If the flag should be optional, switch it to a pointer with `omitempty` and
adjust the `MCPRetrieval` passthrough in `internal/handler/mcp_server.go` to
preserve nil vs false; if it is truly always present, keep it as-is and ensure
the API contract reflects that choice consistently.
🤖 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/agent/component/llm.go`:
- Around line 383-385: Invoke currently leaves the literal {sys.files} marker in
the prompt when collectSysFiles returns empty because a placeholder was present,
so update llm.go in Invoke to explicitly replace that marker with the collected
system file text or an empty string before building the final prompt. Use the
existing collectSysFiles flow and the prompt fields on the request object to
ensure both SystemPrompt and UserPrompt no longer contain the placeholder after
processing, including the related path around the same logic elsewhere in the
file.
- Around line 1128-1149: The token counting and trimming logic in
UserInputMultiContent is only reading and updating the "content" field, so
multimodal entries stored in user_input_multi_content are not counted or trimmed
correctly. Update the helper path that uses stringContent,
TrimContentToTokenLimit, and countAllTokens to operate on the actual
multi-content representation as well as the standard content field, and make
sure the trimmed value is written back to the same field that is later consumed.
- Around line 1118-1120: The fitMessages logic in llm.go drops the only user
message when there is no system prompt, leaving result empty and causing an
error instead of trimming it. Update the message selection around the
messages[len(messages)-1] handling so a single over-budget user message is still
kept in result for trimming, while preserving the existing behavior for
multi-message prompts.

In `@internal/mcp/server.go`:
- Around line 294-336: The pagination and top_k inputs are passed through from
callRagflowRetrieval, callListDatasets, and callListChats without enforcing the
schema bounds. Add server-side validation/clamping for page, page_size, and
top_k before calling s.connector.Retrieval, s.connector.ListDatasets, and
s.connector.ListChats, using the existing getIntArg-based flow or helper(s) so
oversized values are rejected or normalized consistently.
- Around line 307-312: The dataset_ids and document_ids parsing currently
coerces arbitrary JSON values into strings via toStringSlice, which can produce
invalid IDs like map[...] or <nil>. Update the argument handling in the MCP
request parsing logic that assigns req.DatasetIDs and req.DocumentIDs to
validate each array entry is a non-empty string and reject or error on any
non-string item instead of coercing it. Apply the same validation wherever these
IDs are parsed in the other related block mentioned by the review, keeping the
behavior consistent across both request paths.
- Around line 294-314: The retrieval handler in callRagflowRetrieval should not
proceed with an empty question, since question is required by the tool schema
but currently defaults to "". Add an explicit validation for the Question field
after building the RetrievalRequest and return an error response when it is
missing or blank, before calling s.connector.Retrieval. Keep the check close to
the call site so the existing argument parsing for dataset_ids and document_ids
stays unchanged.

In `@internal/tokenizer/tokenizer.go`:
- Around line 545-548: The trim path in NumTokensFromString should fail closed
when getCL100KEncoder cannot load the encoder instead of returning the original
string from the tokenizer flow. Update the logic around getCL100KEncoder so the
same budget-enforcement behavior is preserved as in NumTokensFromString, and use
the existing NumTokensFromString/getCL100KEncoder symbols to locate the fallback
path that should either trim deterministically or propagate the failure rather
than sending the untrimmed string.

---

Nitpick comments:
In `@internal/agent/runtime/json_safe.go`:
- Around line 110-114: Remove the unreachable reflect.Interface branch from
cleanForJSON in json_safe.go; the function only sees concrete values from
Interface() calls, so this case will never match. Keep the surrounding
reflection handling intact, and let the existing fallback path cover any non-nil
interface values via their underlying concrete kind.
- Around line 78-144: cleanForJSON currently recurses through pointers, maps,
slices, and structs without tracking already-seen references, so cyclic values
can still stack overflow. Update cleanForJSON in json_safe.go to maintain a
visited set for reference-bearing values, especially reflect.Ptr and any nested
structures reachable through maps/slices/structs, and short-circuit repeated
nodes to a safe nil/placeholder result. Keep the existing recursive cleanup
behavior for non-cyclic values while adding the cycle guard around the
reflect-based traversal logic.

In `@internal/mcp/connector.go`:
- Line 68: The local desc string in the function that already takes a desc bool
parameter is shadowing the sort-order flag, which hurts readability. Rename the
local variable in the connector logic around the desc assignment to something
distinct, and update its uses in the same function so the desc bool parameter
remains clearly visible and unambiguous.
- Around line 59-124: Both ListDatasets and ListChats in ServiceConnector
duplicate the same record-to-NDJSON formatting logic, including repeated
id/name/description extraction and json.Marshal handling. Extract that shared
loop into a helper (for example, a toNDJSON-style function plus a small
string-field helper) and have both methods call it, keeping the existing output
format and error-skipping behavior unchanged.

In `@internal/service/dataset.go`:
- Line 1711: `ForceRefresh` in the dataset request struct uses a plain bool
while related optional fields like `UseKG` and `Keyword` use pointer/omitempty
semantics, so update the `ForceRefresh` field in the struct and any related
request handling to match the intended API behavior. If the flag should be
optional, switch it to a pointer with `omitempty` and adjust the `MCPRetrieval`
passthrough in `internal/handler/mcp_server.go` to preserve nil vs false; if it
is truly always present, keep it as-is and ensure the API contract reflects that
choice consistently.
🪄 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: 58ed5393-aa7f-4022-96ba-16fbaac8915c

📥 Commits

Reviewing files that changed from the base of the PR and between 20ad4d7 and 0407c05.

📒 Files selected for processing (22)
  • cmd/server_main.go
  • internal/agent/canvas/runner.go
  • internal/agent/component/llm.go
  • internal/agent/runtime/json_safe.go
  • internal/agent/runtime/state.go
  • internal/agent/tool/bgpt.go
  • internal/agent/tool/registry.go
  • internal/common/time.go
  • internal/dao/user_canvas.go
  • internal/handler/agent.go
  • internal/handler/mcp_server.go
  • internal/mcp/connector.go
  • internal/mcp/server.go
  • internal/mcp/types.go
  • internal/router/router.go
  • internal/service/agent.go
  • internal/service/agent_sessions.go
  • internal/service/bot_completion.go
  • internal/service/chat_pipeline.go
  • internal/service/dataset.go
  • internal/service/kg/scoring.go
  • internal/tokenizer/tokenizer.go
✅ Files skipped from review due to trivial changes (1)
  • internal/agent/runtime/state.go
🚧 Files skipped from review as they are similar to previous changes (12)
  • internal/service/bot_completion.go
  • internal/service/agent.go
  • internal/agent/tool/registry.go
  • internal/common/time.go
  • internal/service/agent_sessions.go
  • internal/agent/tool/bgpt.go
  • internal/router/router.go
  • internal/dao/user_canvas.go
  • internal/mcp/types.go
  • internal/agent/canvas/runner.go
  • internal/handler/agent.go
  • internal/handler/mcp_server.go

Comment thread internal/agent/component/llm.go Resolved
Comment thread internal/agent/component/llm.go Resolved
Comment thread internal/agent/component/llm.go Resolved
Comment thread internal/mcp/server.go Resolved
Comment thread internal/mcp/server.go Resolved
Comment thread internal/mcp/server.go
Comment on lines +307 to +312
if v, ok := args["dataset_ids"]; ok {
req.DatasetIDs = toStringSlice(v)
}
if v, ok := args["document_ids"]; ok {
req.DocumentIDs = toStringSlice(v)
}

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.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Reject non-string ID array entries instead of coercing them.

fmt.Sprintf turns invalid JSON values into IDs like map[...], <nil>, or 123, which can send malformed filters downstream. Validate that every dataset_ids and document_ids item is a non-empty string.

Suggested fix
-	if v, ok := args["dataset_ids"]; ok {
-		req.DatasetIDs = toStringSlice(v)
+	if v, ok := args["dataset_ids"]; ok {
+		var ok bool
+		req.DatasetIDs, ok = toStringSlice(v)
+		if !ok {
+			return NewSuccessResponse(id, NewErrorResult("dataset_ids must be an array of strings"))
+		}
 	}
-	if v, ok := args["document_ids"]; ok {
-		req.DocumentIDs = toStringSlice(v)
+	if v, ok := args["document_ids"]; ok {
+		var ok bool
+		req.DocumentIDs, ok = toStringSlice(v)
+		if !ok {
+			return NewSuccessResponse(id, NewErrorResult("document_ids must be an array of strings"))
+		}
 	}
@@
-func toStringSlice(v interface{}) []string {
+func toStringSlice(v interface{}) ([]string, bool) {
 	arr, ok := v.([]interface{})
 	if !ok {
-		return nil
+		return nil, false
 	}
 	result := make([]string, 0, len(arr))
 	for _, item := range arr {
-		result = append(result, fmt.Sprintf("%v", item))
+		s, ok := item.(string)
+		if !ok || strings.TrimSpace(s) == "" {
+			return nil, false
+		}
+		result = append(result, s)
 	}
-	return result
+	return result, true
 }

Also applies to: 407-418

🤖 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/mcp/server.go` around lines 307 - 312, The dataset_ids and
document_ids parsing currently coerces arbitrary JSON values into strings via
toStringSlice, which can produce invalid IDs like map[...] or <nil>. Update the
argument handling in the MCP request parsing logic that assigns req.DatasetIDs
and req.DocumentIDs to validate each array entry is a non-empty string and
reject or error on any non-string item instead of coercing it. Apply the same
validation wherever these IDs are parsed in the other related block mentioned by
the review, keeping the behavior consistent across both request paths.

Comment thread internal/tokenizer/tokenizer.go Resolved

@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: 1

🤖 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/mcp/server.go`:
- Around line 298-299: The retrieval weight arguments are currently read with
getFloat64Arg in server.go and can bypass the advertised 0..1 limits, so update
the argument parsing in the retrieval config path to clamp or validate
similarity_threshold and vector_similarity_weight before constructing the
request config. Apply the same bounds enforcement in both the code paths around
the retrieval setup and any similar parsing block referenced by the comment so
out-of-range values are rejected or normalized before reaching retrieval.
🪄 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: 644206fe-c322-449f-8424-ef4055368d88

📥 Commits

Reviewing files that changed from the base of the PR and between 43d5ac6 and 387f26b.

📒 Files selected for processing (22)
  • cmd/server_main.go
  • internal/agent/canvas/runner.go
  • internal/agent/component/llm.go
  • internal/agent/runtime/json_safe.go
  • internal/agent/runtime/state.go
  • internal/agent/tool/bgpt.go
  • internal/agent/tool/registry.go
  • internal/common/time.go
  • internal/dao/user_canvas.go
  • internal/handler/agent.go
  • internal/handler/mcp_server.go
  • internal/mcp/connector.go
  • internal/mcp/server.go
  • internal/mcp/types.go
  • internal/router/router.go
  • internal/service/agent.go
  • internal/service/agent_sessions.go
  • internal/service/bot_completion.go
  • internal/service/chat_pipeline.go
  • internal/service/dataset.go
  • internal/service/kg/scoring.go
  • internal/tokenizer/tokenizer.go
🚧 Files skipped from review as they are similar to previous changes (20)
  • internal/agent/tool/registry.go
  • internal/service/agent_sessions.go
  • internal/service/kg/scoring.go
  • internal/agent/runtime/state.go
  • internal/service/dataset.go
  • internal/agent/runtime/json_safe.go
  • internal/mcp/types.go
  • internal/agent/canvas/runner.go
  • internal/common/time.go
  • internal/service/agent.go
  • internal/agent/tool/bgpt.go
  • internal/handler/agent.go
  • internal/tokenizer/tokenizer.go
  • internal/dao/user_canvas.go
  • internal/mcp/connector.go
  • internal/service/chat_pipeline.go
  • internal/handler/mcp_server.go
  • internal/agent/component/llm.go
  • internal/service/bot_completion.go
  • internal/router/router.go

Comment thread internal/mcp/server.go Resolved
@codecov

codecov Bot commented Jul 1, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (81cfcdf) to head (17a4e5d).
⚠️ Report is 10 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16529   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@yuzhichang yuzhichang left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration lgtm This PR has been approved by a maintainer size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants