Repository navigation
Port agent PRs to GO - #16529
Port agent PRs to GO#16529
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
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)
📝 WalkthroughWalkthroughThis PR adds MCP server support, safe JSON marshaling, LLM message fitting with ChangesRuntime and protocol changes
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
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 inconclusive)
✅ Passed checks (4 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: 13
🧹 Nitpick comments (2)
internal/handler/agent.go (1)
1126-1131: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winReuse
WriteChatbotRunEventfor the synthetic terminator.This branch bypasses the shared
[DONE]helper path and drops the error from the synthetic frame write. Keeping both writes onservice.WriteChatbotRunEventwill 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
NewBGPTToolWithdoes not currently affect HTTP behavior.The constructor stores
helper, butInvokableRunalways allocates its ownhttp.Client. That makes the injected dependency ineffective for tests and any shared transport/timeout policy. Route requests throughb.helperor 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
📒 Files selected for processing (19)
cmd/server_main.gointernal/agent/canvas/runner.gointernal/agent/component/llm.gointernal/agent/runtime/json_safe.gointernal/agent/runtime/state.gointernal/agent/tool/bgpt.gointernal/agent/tool/registry.gointernal/common/time.gointernal/dao/user_canvas.gointernal/handler/agent.gointernal/handler/mcp_server.gointernal/mcp/connector.gointernal/mcp/server.gointernal/mcp/types.gointernal/router/router.gointernal/service/agent.gointernal/service/agent_sessions.gointernal/service/bot_completion.gointernal/service/chat_pipeline.go
There was a problem hiding this comment.
Actionable comments posted: 7
🧹 Nitpick comments (5)
internal/mcp/connector.go (2)
68-68: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueLocal
descshadows thedesc boolparameter.Minor readability nit: the local
descstring variable shadows thedesc boolsort-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 winDuplicate item-building logic between
ListDatasetsandListChats.Both methods repeat the same pattern: iterate map records, extract
id/name/descriptionvia 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 valueDead branch:
reflect.Interfaceis unreachable here.
cleanForJSONis always invoked with values obtained via.Interface()(see line 74, 96, 102, 109, 137), soreflect.ValueOf(v)always yields the concrete dynamic type'sKind(), neverreflect.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 tradeoffNo cycle detection for self-referencing structures.
cleanForJSONrecurses 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 beforejson.Marshalis 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 valueInconsistent optionality pattern for
ForceRefresh.Every other boolean/scalar field added for optional semantics in this struct (
UseKG,Keyword) uses a pointer withomitemptyso callers can distinguish "unset" from "explicitly false".ForceRefreshis a plainboolwithoutomitempty, meaning it can never be omitted and there's no way to distinguish an unset flag from an explicitfalse. Per theMCPRetrievalsnippet ininternal/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
📒 Files selected for processing (22)
cmd/server_main.gointernal/agent/canvas/runner.gointernal/agent/component/llm.gointernal/agent/runtime/json_safe.gointernal/agent/runtime/state.gointernal/agent/tool/bgpt.gointernal/agent/tool/registry.gointernal/common/time.gointernal/dao/user_canvas.gointernal/handler/agent.gointernal/handler/mcp_server.gointernal/mcp/connector.gointernal/mcp/server.gointernal/mcp/types.gointernal/router/router.gointernal/service/agent.gointernal/service/agent_sessions.gointernal/service/bot_completion.gointernal/service/chat_pipeline.gointernal/service/dataset.gointernal/service/kg/scoring.gointernal/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
| if v, ok := args["dataset_ids"]; ok { | ||
| req.DatasetIDs = toStringSlice(v) | ||
| } | ||
| if v, ok := args["document_ids"]; ok { | ||
| req.DocumentIDs = toStringSlice(v) | ||
| } |
There was a problem hiding this comment.
🗄️ 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.
There was a problem hiding this comment.
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
📒 Files selected for processing (22)
cmd/server_main.gointernal/agent/canvas/runner.gointernal/agent/component/llm.gointernal/agent/runtime/json_safe.gointernal/agent/runtime/state.gointernal/agent/tool/bgpt.gointernal/agent/tool/registry.gointernal/common/time.gointernal/dao/user_canvas.gointernal/handler/agent.gointernal/handler/mcp_server.gointernal/mcp/connector.gointernal/mcp/server.gointernal/mcp/types.gointernal/router/router.gointernal/service/agent.gointernal/service/agent_sessions.gointernal/service/bot_completion.gointernal/service/chat_pipeline.gointernal/service/dataset.gointernal/service/kg/scoring.gointernal/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
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
Summary
Port the following PRs to GO in this PR
#14210
#14641
#15220
#15228
#15384
#15754
#16413
#16483
#16419
#16361
#16050