Skip to content

feat: add Go MCP server get mcpid API - #15254

Open
Helios531 wants to merge 406 commits into
infiniflow:mainfrom
Helios531:feat/go-mcp-server-get-mcpid
Open

Helios531 wants to merge 406 commits into
infiniflow:mainfrom
Helios531:feat/go-mcp-server-get-mcpid

Conversation

@Helios531

Copy link
Copy Markdown
Contributor

What

#15240
Implements MCP server read APIs in the Go API server.

Changes

  • Added MCP server DAO methods for tenant-scoped list/detail queries.
  • Added MCP service layer for list, detail, and export response shaping.
  • Added MCP handler for:
    • GET /api/v1/mcp/servers
    • GET /api/v1/mcp/servers/:mcp_id
  • Added support for GET /api/v1/mcp/servers/:mcp_id?mode=download.
  • Wired MCP routes into the authenticated /api/v1 router.
  • Initialized MCP service and handler during Go server startup.

API Behavior

Matches the Python MCP endpoints:

  • Requires authenticated user.
  • Scopes MCP servers to the current user ID.
  • List supports keywords, mcp_id, mcp_ids, page, page_size, orderby, and desc.
  • Detail returns a single MCP server by ID.
  • Download mode returns exported MCP server config under mcpServers.
  • Not found returns a data error response.

Verification

  • gofmt
  • git diff --check
  • go test ./internal/dao -run TestDoesNotExist -count=1
  • go test ./internal/handler -run TestDoesNotExist -count=1 -vet=off
  • go test ./internal/router -run TestDoesNotExist -count=1 -vet=off

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 26, 2026
@coderabbitai

coderabbitai Bot commented May 26, 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
📝 Walkthrough

Walkthrough

Adds tenant-scoped MCP server list/get/export: DAO lookup, service DTOs/builders, handler endpoints (including download/export), router route, plus small locale, script, docs, and test formatting fixes.

Changes

MCP Server Management

Layer / File(s) Summary
Data access: tenant-scoped get
internal/dao/mcp.go
Adds GetMCPServerByIDAndTenantID to fetch an MCPServer by id and tenant_id, returning nil when not found and propagating other DB errors.
Service: DTOs, list/get/export builders
internal/service/mcp.go
Adds DTOs (MCPServerListItem, ListMCPServersResponse, MCPServerDetail, ExportedMCPServers, ExportedMCPServer), ListMCPServers/GetMCPServer/ExportMCPServer methods, normalization helpers, and builders that format dates, ensure maps, and extract authorization_token and tools.
HTTP handlers: get & download
internal/handler/mcp.go
Adds MCPHandler.GetMCPServer, download/export flow (downloadMCPServer), and mcpNotFound helper; authenticates user, reads mcp_id, supports mode=download, and returns standardized JSON or errors.
Router wiring
internal/router/router.go
Registers authenticated route GET /api/v1/mcp/servers/:mcp_id to mcpHandler.GetMCPServer.
Misc: locales, scripts, docs, tests
web/src/locales/zh.ts, docker/launch_admin_service.sh, docs/guides/dataset/add_data_source/add_rss.md, internal/utility/oauth/client_test.go
Reformats two Chinese locale entries, removes trailing whitespace from .env sourcing line, adds a one-line RSS guide intro, and fixes an OIDC missing-issuer test assertion.

Sequence Diagram

sequenceDiagram
  participant Client
  participant MCPHandler
  participant MCPService
  participant MCPServerDAO
  Client->>MCPHandler: GET /api/v1/mcp/servers?page=1&keywords=test
  MCPHandler->>MCPHandler: authenticate, parse params
  MCPHandler->>MCPService: ListMCPServers(tenantID, ids, keywords, page, pageSize, orderby, desc)
  MCPService->>MCPServerDAO: ListMCPServers(...)
  MCPServerDAO-->>MCPService: entities, count
  MCPService->>MCPService: normalize, format dates, build DTOs
  MCPService-->>MCPHandler: ListMCPServersResponse
  MCPHandler-->>Client: {code: Success, data: response}
  Client->>MCPHandler: GET /api/v1/mcp/servers/:mcp_id?mode=download
  MCPHandler->>MCPService: ExportMCPServer(tenantID, mcpID)
  MCPService->>MCPServerDAO: GetMCPServerByIDAndTenantID(tenantID, mcpID)
  MCPServerDAO-->>MCPService: entity or nil
  MCPService->>MCPService: extract authorization_token, tools, build export
  MCPService-->>MCPHandler: ExportedMCPServers
  MCPHandler-->>Client: {code: Success, data: exported} or mcpNotFound/jsonError
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • infiniflow/ragflow#15260: Extends the same MCP modules; that PR adds create/exists while this one adds list/get/export.

Suggested reviewers

  • Hz-186

Poem

A rabbit hops in, ear to ear, 🐇
Tenants scoped, servers near,
Lists and exports, tokens bright,
Handlers, DTOs — all in sight,
Hooray for tidy API light! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: adding a Go MCP server get API endpoint by ID, which aligns with the implementation of GetMCPServer handler and route.
Description check ✅ Passed The PR description is comprehensive and follows the template structure with clear problem statement, changes breakdown, API behavior details, and verification steps performed.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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 and usage tips.

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

🤖 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/handler/mcp.go`:
- Around line 59-63: The handler is returning raw 500 JSON bodies instead of the
shared API envelope; replace the three direct c.JSON(...) error responses with
the common jsonError envelope used by other handlers. Locate the three
occurrences in internal/handler/mcp.go (the c.JSON calls that pass
common.CodeServerError and err.Error()) and change them to use the shared
helper/shape (e.g., call jsonError(c, common.CodeServerError, nil, err.Error())
or otherwise return {"code": common.CodeServerError, "data": nil, "message":
err.Error()}) so all three branches produce the uniform {code,data,message}
response.
- Around line 131-135: The mcpNotFound function builds an error envelope missing
the "data" field; update the JSON response in mcpNotFound (function name
mcpNotFound, parameters c *gin.Context, mcpID, tenantID string) to include a
"data": nil entry alongside "code" and "message" so the response shape matches
other error responses and avoids client-side parsing branches.
🪄 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: 74d30d2b-057d-4e74-b389-3b9f38aaea5b

📥 Commits

Reviewing files that changed from the base of the PR and between 5ae41dc and 3fb9df0.

📒 Files selected for processing (5)
  • cmd/server_main.go
  • internal/dao/mcp.go
  • internal/handler/mcp.go
  • internal/router/router.go
  • internal/service/mcp.go

Comment thread internal/handler/mcp.go Outdated
Comment on lines +59 to +63
c.JSON(http.StatusInternalServerError, gin.H{
"code": common.CodeServerError,
"message": err.Error(),
"data": nil,
})

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Use the standard API error envelope for server errors.

Line 59, Line 90, and Line 112 return raw HTTP 500 bodies instead of the shared jsonError shape used elsewhere in handlers. This can break clients expecting uniform {code,data,message} responses.

Proposed fix
-		c.JSON(http.StatusInternalServerError, gin.H{
-			"code":    common.CodeServerError,
-			"message": err.Error(),
-			"data":    nil,
-		})
+		jsonError(c, common.CodeServerError, err.Error())
 		return

(Apply in all three error branches.)

Also applies to: 90-94, 112-116

🤖 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/mcp.go` around lines 59 - 63, The handler is returning raw
500 JSON bodies instead of the shared API envelope; replace the three direct
c.JSON(...) error responses with the common jsonError envelope used by other
handlers. Locate the three occurrences in internal/handler/mcp.go (the c.JSON
calls that pass common.CodeServerError and err.Error()) and change them to use
the shared helper/shape (e.g., call jsonError(c, common.CodeServerError, nil,
err.Error()) or otherwise return {"code": common.CodeServerError, "data": nil,
"message": err.Error()}) so all three branches produce the uniform
{code,data,message} response.

Comment thread internal/handler/mcp.go Resolved
@yingfeng yingfeng added the ci Continue Integration label May 26, 2026
@yingfeng
yingfeng marked this pull request as draft May 26, 2026 13:05
@yingfeng
yingfeng marked this pull request as ready for review May 26, 2026 13:05
@codecov

codecov Bot commented May 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (0d836af) to head (5564169).
⚠️ Report is 2321 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #15254      +/-   ##
==========================================
- Coverage   94.56%   93.16%   -1.40%     
==========================================
  Files          10       10              
  Lines         717      717              
  Branches      118      118              
==========================================
- Hits          678      668      -10     
- Misses         25       29       +4     
- Partials       14       20       +6     

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

@Helios531

Copy link
Copy Markdown
Contributor Author

Hi, @JinHai-CN , can you review my PR, #15253, #15254, #15260, #15261, #15262, plz?

@Harry-Hz-Zhang Harry-Hz-Zhang 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.

The APIs look mostly aligned, but create_date and update_date should be formatted without timezone to match the Python response format.

Comment thread internal/service/mcp.go Outdated
Description *string `json:"description"`
Variables entity.JSONMap `json:"variables"`
CreateDate *time.Time `json:"create_date"`
UpdateDate *time.Time `json:"update_date"`

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.

Hi @Helios531, please do not return create_date / update_date as raw *time.Time here.

Go JSON encoding adds timezone information, e.g. 2026-05-28T10:30:20+08:00, while the Python MCP endpoint returns 2026-05-28T10:30:20.

Please format these fields before response serialization, or change them to string fields in the MCP response DTO, so the

Go API matches the Python endpoint.

Comment thread internal/service/mcp.go Outdated
CreateTime *int64 `json:"create_time"`
CreateDate *time.Time `json:"create_date"`
UpdateTime *int64 `json:"update_time"`
UpdateDate *time.Time `json:"update_date"`

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.

Hi, @Helios531, The detail response does not fully match the Python MCP endpoint.

Python returns create_date / update_date without timezone, e.g. 2026-05-28T10:30:20, but the Go endpoint currently returns RFC3339 timestamps with timezone, e.g. 2026-05-28T10:30:20+08:00.

This is caused by returning these fields as raw *time.Time in MCPServerDetail:

  CreateDate *time.Time `json:"create_date"`
  UpdateDate *time.Time `json:"update_date"`

Please format these fields before returning the response, or change the response DTO fields to strings, so the Go response

matches the Python API format.

JinHai-CN pushed a commit that referenced this pull request May 28, 2026
## Summary
- Add Go REST support for `GET /api/v1/system/healthz`.
- Return Python-compatible `ok`/`nok` dependency fields for DB, Redis,
document engine, and storage.
- Return HTTP 200 only when all checks pass; otherwise return HTTP 500
with `_meta` failure details.
- Add focused service coverage for the unhealthy dependency response
when Go dependencies are not initialized.

## Scope
This is a small, isolated slice of #15240. It avoids current open
connector PRs (#15274, #15300, #15265, #15264), tenant/member PRs
(#15295, #15301, #15276), MCP PRs (#15281, #15253, #15254, #15260,
#15261, #15262), and the memory-message PR (#15256).

Refs #15240
@Harry-Hz-Zhang Harry-Hz-Zhang removed the ci Continue Integration label May 28, 2026
@Helios531
Helios531 force-pushed the feat/go-mcp-server-get-mcpid branch from 3fb9df0 to bb43752 Compare May 28, 2026 16:33

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

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

98-117: 💤 Low value

Consider adding explicit "create_time" case for clarity.

The "create_time" value is the handler's default and should be explicitly listed rather than relying on the default branch. This separates "valid expected input" from "fallback for unrecognized input" and makes the supported values self-documenting.

♻️ Suggested refactor
 func mcpServerOrderColumn(orderby string) string {
 	switch orderby {
 	case "id":
 		return "id"
 	case "name":
 		return "name"
 	case "server_type":
 		return "server_type"
 	case "url":
 		return "url"
+	case "create_time":
+		return "create_time"
 	case "update_time":
 		return "update_time"
 	case "update_date":
 		return "update_date"
 	case "create_date":
 		return "create_date"
 	default:
 		return "create_time"
 	}
 }
🤖 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/dao/mcp.go` around lines 98 - 117, The switch in
mcpServerOrderColumn currently relies on the default branch to return
"create_time"; add an explicit case "create_time" to the switch (while leaving
the default branch as a fallback for unrecognized input) so the function's
supported/expected sort keys are self-documenting; update the switch in
mcpServerOrderColumn to include case "create_time": return "create_time".
🤖 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.

Nitpick comments:
In `@internal/dao/mcp.go`:
- Around line 98-117: The switch in mcpServerOrderColumn currently relies on the
default branch to return "create_time"; add an explicit case "create_time" to
the switch (while leaving the default branch as a fallback for unrecognized
input) so the function's supported/expected sort keys are self-documenting;
update the switch in mcpServerOrderColumn to include case "create_time": return
"create_time".

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3a197847-88b8-4aa3-a3bb-8ab5e6ac7a3d

📥 Commits

Reviewing files that changed from the base of the PR and between 3fb9df0 and bb43752.

📒 Files selected for processing (4)
  • internal/dao/mcp.go
  • internal/handler/mcp.go
  • internal/router/router.go
  • internal/service/mcp.go
💤 Files with no reviewable changes (3)
  • internal/router/router.go
  • internal/handler/mcp.go
  • internal/service/mcp.go

@Helios531

Copy link
Copy Markdown
Contributor Author

hi, @Hz-186 , can you review my pr, pls?

@Harry-Hz-Zhang Harry-Hz-Zhang 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.

@Helios531, LGTM

@Harry-Hz-Zhang Harry-Hz-Zhang added the ci Continue Integration label May 29, 2026
@Haruko386
Haruko386 marked this pull request as draft May 29, 2026 02:04
@Haruko386
Haruko386 marked this pull request as ready for review May 29, 2026 02:04
@dosubot dosubot Bot added the 💞 feature Feature request, pull request that fullfill a new feature. label May 29, 2026
Lobster-0429 added a commit to Lobster-0429/ragflow that referenced this pull request May 29, 2026
Address review feedback on infiniflow#15281: per-server CRUD lives in the dedicated
PRs (infiniflow#15253 list, infiniflow#15254 get, infiniflow#15260 create — merged, infiniflow#15261 update,
infiniflow#15262 delete), so drop those handlers/services here and ship only the
non-overlapping endpoints.

  POST /api/v1/mcp/servers/import   bulk import from a JSON config
  POST /api/v1/mcp/servers/:mcp_id/test   live tool-list probe

Behavior is aligned with api/apps/restful_apis/mcp_api.py:

- Import path corrected from /mcp/import to /mcp/servers/import. Gin
  v1.9.1's tree supports the static + param siblings under /servers/,
  so the prior workaround is no longer needed.
- Both endpoints validate server_type, SSRF-guard the URL via
  utility.AssertURLSafe (new port of common/ssrf_guard.assert_url_is_safe
  with IPv4-mapped-IPv6 normalisation, link-local / private / CGNAT /
  doc-range checks), and DNS-pin the resolved IP into the HTTP client
  to close the rebinding window.
- Tool discovery uses a new internal/mcpclient that implements the
  MCP handshake (initialize → notifications/initialized → tools/list)
  over both streamable-HTTP (single-endpoint JSON-RPC with optional
  inline SSE responses, Mcp-Session-Id propagation) and the legacy SSE
  transport (waits for the "endpoint" event, then POSTs JSON-RPC to
  the session URL while a goroutine dispatches SSE responses by id).
- Import persists the discovered tools under variables.tools keyed by
  name, matching the Python create/import shape.
- Test endpoint now uses mcp_id for log correlation, then opens a real
  session and returns the tools array; the previous "not implemented"
  response is gone.

Tests cover the SSRF guard (loopback / CGNAT / IPv4-mapped IPv6 /
doc-net / link-local / disallowed-scheme), MCP client (streamable-HTTP
JSON, streamable-HTTP error, SSE round-trip, unsupported type, empty
URL, ${var} substitution, JSON-RPC id normalisation), and the import /
test input-validation paths.
@JinHai-CN

Copy link
Copy Markdown
Member

@Helios531 would you please fix the conflicts?

@Helios531

Helios531 commented May 29, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @JinHai-CN, I've resolved the merge conflicts. Could you please review the PR and merge it?

1 similar comment
@Helios531

Copy link
Copy Markdown
Contributor Author

Hi @JinHai-CN, I've resolved the merge conflicts. Could you please review the PR and merge it?

@tmimmanuel tmimmanuel 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.

@JinHai-CN This is ready.

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

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

104-109: ⚡ Quick win

MCP not-found handling is already normalized in the service layer.

MCPService.GetMCPServer and MCPService.ExportMCPServer both translate errors.Is(err, gorm.ErrRecordNotFound) into (nil, false, nil), so returning the raw gorm not-found from GetMCPServerByIDAndTenantID doesn’t currently break the MCP endpoints. Optional improvement: normalize gorm.ErrRecordNotFound inside the DAO for consistent behavior across all potential callers.

🤖 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/dao/mcp.go` around lines 104 - 109, GetMCPServerByIDAndTenantID
currently returns raw gorm.ErrRecordNotFound which leaves normalization to
callers; update GetMCPServerByIDAndTenantID to treat errors.Is(err,
gorm.ErrRecordNotFound) as a non-error by returning (nil, nil) so callers
receive a nil result without an error, otherwise return the original error;
locate and modify the function GetMCPServerByIDAndTenantID in mcp.go to add the
errors.Is(...) check after the DB query and handle it accordingly.
🤖 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.

Nitpick comments:
In `@internal/dao/mcp.go`:
- Around line 104-109: GetMCPServerByIDAndTenantID currently returns raw
gorm.ErrRecordNotFound which leaves normalization to callers; update
GetMCPServerByIDAndTenantID to treat errors.Is(err, gorm.ErrRecordNotFound) as a
non-error by returning (nil, nil) so callers receive a nil result without an
error, otherwise return the original error; locate and modify the function
GetMCPServerByIDAndTenantID in mcp.go to add the errors.Is(...) check after the
DB query and handle it accordingly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9198fc31-f436-4380-8620-7001432e7b03

📥 Commits

Reviewing files that changed from the base of the PR and between bb43752 and 9de7006.

📒 Files selected for processing (5)
  • internal/dao/mcp.go
  • internal/handler/mcp.go
  • internal/router/router.go
  • internal/service/mcp.go
  • web/src/locales/zh.ts
✅ Files skipped from review due to trivial changes (1)
  • web/src/locales/zh.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • internal/router/router.go
  • internal/handler/mcp.go
  • internal/service/mcp.go

@Helios531
Helios531 requested a review from Harry-Hz-Zhang May 31, 2026 11:35
monsterdavidliu-ux and others added 7 commits June 11, 2026 15:46
…flow#15589)

## Summary

Fixes [infiniflow#15585](infiniflow#15585).

- Route markdown preview through the shared `request` client (same as
txt/image previewers) so `Authorization` headers and interceptors are
applied consistently.
- Add a unit test covering `AUTH_BETA` token loading for embedded search
auth.

## Root cause

Search result preview for `.md`/`.mdx` used raw `fetch`, which did not
apply the same auth path as other preview types. That led to `401` on
`GET /api/v1/documents/{id}/preview` even when the user was logged in or
using an embedded search `auth` query param.

## Test plan

- [ ] Log in, run a search, open a markdown citation link — preview
loads (no 401).
- [ ] Open an embedded shared search URL with `auth` query param,
preview a markdown file — preview loads.
- [ ] Confirm PDF/txt preview still works in the same search UI.

---------

Co-authored-by: MkDev11 <[email protected]>
Co-authored-by: Wang Qi <[email protected]>
…infiniflow#15699) (infiniflow#15879)

## Summary

Fixes infiniflow#15699.

User upgrades to v0.25.6 against an existing MySQL database, tries to
add an Ollama provider instance, and gets:

```
MySQL IntegrityError: Duplicate entry 'dbaafbfe608a11f1a5516d6066988224'
for key 'tenant_model_instance.tenantmodelinstance_api_key_provider_id'
```

The route at
[api/apps/restful_apis/provider_api.py:354](api/apps/restful_apis/provider_api.py#L354)
catches it and returns `get_error_data_result(message="Internal server
error")` — which by RAGFlow's convention is HTTP 200 with an error
`code` on the body — hence the reporter's "200 status code but the
database errored" complaint.

### Root cause

The provider-instance refactor in [PR
infiniflow#15460](infiniflow#15460) dropped the
unique-compound-index tuple from `TenantModelInstance`:

```python
# Removed in infiniflow#15460
class Meta:
    db_table = "tenant_model_instance"
    indexes = (
        (("api_key", "provider_id"), True),   # unique
    )
```

and added a one-shot drop in `migrate_db()` for existing databases. But
the drop targets the wrong index name:

```python
# Before this PR — wrong name
for table_name, index_name in [
    ("tenant_model_instance", "idx_api_key_provider_id"),       # ← doesn't exist
    ("tenant_model",          "idx_provider_model_instance"),
]:
```

Peewee's auto-derived index name is `<lowercase
classname>_<col1>_<col2>` →
**`tenantmodelinstance_api_key_provider_id`**, which matches the user's
error verbatim. The drop raises `OperationalError: 1091 (HY000): Can't
DROP …`, the surrounding `except` clause at
[db_models.py:1736](api/db/db_models.py#L1736) swallows it as
expected-on-fresh-installs, and the legacy unique index lives on
indefinitely.

### Why Ollama hits it specifically

Ollama doesn't require an API key. The form posts `api_key: ""`. The
app-layer dedupe at
[provider_api_service.py:288-292](api/apps/services/provider_api_service.py#L288-L292):

```python
api_key_str = ""
if api_key:                                                     # ← skipped for ""
    ...
    same_key_instance = TenantModelInstanceService.get_by_provider_id_and_api_key(...)
    if same_key_instance:
        return False, f"Already exist instance: ... with api_key {api_key}"
```

falls through for empty keys. Control reaches
`TenantModelInstanceService.create_instance(..., api_key="")` which
inserts a row whose `(api_key, provider_id) = ("", <provider_uuid>)`
collides with any prior Ollama row that already shipped that same pair →
the still-present unique index throws.

(`dbaafbfe608a11f1a5516d6066988224` in the user's error is the
duplicated `provider_id` UUID, paired with the empty `api_key`.)

### Fix

Add the Peewee auto-name alongside the existing `idx_*` entry so the
migration finally drops the obsolete index on next restart:

```python
legacy_indexes = [
    ("tenant_model_instance", "idx_api_key_provider_id"),
    ("tenant_model_instance", "tenantmodelinstance_api_key_provider_id"),  # ← added
    ("tenant_model",          "idx_provider_model_instance"),
]
```

The surrounding `try/except (OperationalError, ProgrammingError)`
matches `1091` / `can't DROP` / `does not exist` and treats them as
success, so every state is idempotent (see Test plan).

### Idempotency matrix

| Database state | First entry (`idx_api_key_provider_id`) | New entry
(`tenantmodelinstance_api_key_provider_id`) |
| --- | --- | --- |
| Fresh install (≥ infiniflow#15460) — neither index exists | `1091` → swallowed |
`1091` → swallowed |
| Upgraded from before dc4b825 (the user's case) — auto-name present |
`1091` → swallowed | **drops the index** |
| Upgraded after a manual rename to `idx_*` | drops the index | `1091` →
swallowed |
| Re-run of `migrate_db()` after either of the above | `1091` →
swallowed | `1091` → swallowed |

No rollback hazard: nothing depends on this unique constraint anymore
(`create_instance` dedupes by `instance_name` via `duplicate_name`, see
[tenant_model_instance_service.py:27](api/db/services/tenant_model_instance_service.py#L27)).

### What this PR does NOT change

- **`provider_api_service.create_provider_instance`** — its `if
api_key:` gate is correct *for the post-migration world*: multiple
Ollama instances with empty keys under one provider are legitimate, so
we shouldn't tighten the app-layer check.
- **`TenantModelInstance` Peewee model** — the `indexes` tuple was
already removed in infiniflow#15460. New databases never get the constraint in the
first place.
- **The `except → get_error_data_result` → HTTP 200 pattern at
`provider_api.py:354`** — that's a project-wide convention; changing one
route to HTTP 500 would be inconsistent and out of scope.

## Test plan

- [ ] **Reproducer (pre-fix):** on a database originally created before
infiniflow#15460, configure an Ollama provider with an empty `api_key`, then try
to create a *second* instance under the same provider — confirm the
`Duplicate entry … 'tenantmodelinstance_api_key_provider_id'` error in
the server log.
- [ ] **Verify the index is present pre-restart:** `SHOW INDEX FROM
tenant_model_instance WHERE Key_name =
'tenantmodelinstance_api_key_provider_id';` — non-empty result.
- [ ] **Restart with the fix applied:** server starts cleanly,
`migrate_db()` runs, no `Failed to drop index` in critical logs.
- [ ] **Verify the index is gone post-restart:** same `SHOW INDEX` query
— empty result.
- [ ] **Re-run the reproducer:** two Ollama instances under the same
provider, both `api_key=""`, both succeed.
- [ ] **Restart a second time** — no new errors; the matching `1091`
swallow keeps the migration idempotent.
- [ ] **Fresh install smoke test:** drop the DB volume, start clean — no
`1091` noise (the new index never existed), no functional regression.

## Files changed

- [api/db/db_models.py](api/db/db_models.py) — extend the legacy-index
drop list with `tenantmodelinstance_api_key_provider_id`; refactor the
inline list to a named `legacy_indexes` local with a comment pointing at
infiniflow#15460 and infiniflow#15699.

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
- [ ] New Feature (non-breaking change which adds functionality)
- [ ] Documentation Update
- [ ] Refactoring
- [ ] Performance Improvement
- [ ] Other (please describe):

Co-authored-by: Wang Qi <[email protected]>
…w#15731)

## Summary
- Normalize WebDAV file-size metadata before applying the sync size
threshold.
- Enforce the same threshold for numeric string sizes in both document
sync and slim snapshot paths.
- Add focused WebDAV unit coverage for size parsing and over-threshold
skips.

## Why
Some WebDAV servers return file sizes from PROPFIND metadata as strings.
The previous threshold check only handled integer values, so oversized
files could still be downloaded and sent into the chunking pipeline.

Closes infiniflow#15724.

## Validation
- `uv run --no-project --with pytest --with pytest-asyncio pytest
test/unit_test/data_source/test_webdav_connector_unit.py -q`
- `uvx ruff check common/data_source/webdav_connector.py
test/unit_test/data_source/test_webdav_connector_unit.py`
- `python -m compileall -q common/data_source/webdav_connector.py
test/unit_test/data_source/test_webdav_connector_unit.py`
- `git diff --check`

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
…ters (infiniflow#15789)

### What problem does this PR solve?

`POST /api/v1/datasets/{dataset_id}/documents/stop`
(`stop_parse_documents`) cancels parsing tasks and sets `run` to
`CANCEL`, but it does **not** remove chunks already indexed in the doc
store or reset `progress` / `chunk_num`. REST callers can end up with a
“cancelled” document that still returns partial chunks in `GET
.../chunks` and in retrieval.

Legacy `DELETE /api/v1/datasets/{dataset_id}/chunks` (`stop_parsing`)
already performs full cleanup: it resets counters and calls
`docStoreConn.delete`. This PR aligns the newer stop endpoint with that
behavior so both paths leave the dataset consistent.

Fixes [infiniflow#15788](infiniflow#15788).

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
- [ ] New Feature (non-breaking change which adds functionality)
- [ ] Documentation Update
- [ ] Refactoring
- [ ] Performance Improvement
- [ ] Other (please describe):

### Changes

- Update `stop_parse_documents` in `document_api.py` to reset `progress`
and `chunk_num` to `0` and delete partial chunks via
`docStoreConn.delete` after `cancel_all_task_of`.
- Add unit test `test_stop_parse_documents_cleans_partial_chunks` to
assert counters reset and doc store delete is invoked.

### Test plan

- [x] Unit test: `pytest
test/testcases/test_http_api/test_file_management_within_dataset/test_doc_sdk_routes_unit.py::TestDocRoutesUnit::test_stop_parse_documents_cleans_partial_chunks
-v`
- [ ] Manual: upload a slow document, start parse, call `POST
.../documents/stop` while `RUNNING`, verify `GET .../chunks` returns
zero chunks and UI `chunk_count` is 0
- [ ] Control: legacy `DELETE .../chunks` behavior unchanged

---------

Co-authored-by: Wang Qi <[email protected]>
…iflow#15530)

Fixes infiniflow#15529 .

### Problem

`async_ask()` accessed `kbs[0]` without verifying that
`KnowledgebaseService.get_by_ids()` returned any knowledge bases. Empty
or stale `kb_ids` raised `IndexError`, which surfaced as HTTP 500 on
search/bot SSE endpoints.

### Fix

- Add an early guard when `kbs` is empty, yielding a final SSE error
event (consistent with `gen_mindmap()` in the same module).
- Add regression tests for empty `kb_ids` and deleted/invalid KB IDs.

### Test plan

- [ ] `pytest
test/unit_test/api/db/services/test_dialog_service_final_answer.py -k
"async_ask_empty or async_ask_stale"`
- [ ] Manual: `POST /api/v1/searchbots/ask` with invalid `kb_ids`
returns SSE error, not HTTP 500

---------

Co-authored-by: Wang Qi <[email protected]>
infiniflow#15877)

Fixes infiniflow#15587

## Problem

`AzureEmbed.__init__` in `rag/llm/embedding_model.py` and
`AzureGptV4.__init__` in `rag/llm/cv_model.py` both call
`json.loads(key)` unconditionally:

```python
api_key = json.loads(key).get("api_key", "")
api_version = json.loads(key).get("api_version", "2024-02-01")
```

When a user stores a plain API key string (not a JSON object) in the
model configuration — which is a valid and common way to configure Azure
OpenAI — `json.loads` raises `JSONDecodeError`. This makes the model
fail to initialize and causes document parsing/embedding to return a 500
error.

## Fix

Wrap `json.loads` in `try/except (json.JSONDecodeError, TypeError)` and
fall back to using the raw string as the `api_key` with the default
`api_version`. This is the same pattern already applied to the Azure
chat model in PR infiniflow#15604.

## Files changed

- `rag/llm/embedding_model.py` — `AzureEmbed.__init__`
- `rag/llm/cv_model.py` — `AzureGptV4.__init__`

Fixes infiniflow#15857

---------

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Wang Qi <[email protected]>
…sing (infiniflow#15876)

## What problem does this PR solve?

Closes infiniflow#15874

Both the `POST /api/v1/datasets/<dataset_id>/chunks` (re-parse) and
`DELETE /api/v1/datasets/<dataset_id>/chunks` (stop-parsing) handlers
called `settings.docStoreConn.delete` unconditionally. When the
tenant/dataset index has not been created yet — fresh dataset, first
parse interrupted before any chunks were indexed, or index manually
removed — the delete call throws and the handler returns HTTP 500
**after** the document state was already mutated (RUNNING with zeroed
counters for the parse path; CANCEL with zeroed counters for the stop
path), leaving the document in an inconsistent state.

The newer `parse_documents` path in `document_api.py` already uses
`index_exist` before deleting:



## How to fix?

Apply the same `index_exist` guard to both call sites in `chunk_api.py`:

- **`parse`** (POST path, line ~192): guard the delete before
`TaskService.filter_delete`.
- **`stop_parsing`** (DELETE path, line ~242): guard the delete after
`DocumentService.update_by_id`.

Both sites already have the correct `search.index_name(tenant_id)` and
`dataset_id` parameters; the guard is a one-line addition at each site.

## Type of change

- [x] Bug fix (non-breaking change which fixes an issue)

---------

Co-authored-by: Cursor <[email protected]>
Co-authored-by: Wang Qi <[email protected]>
@Harry-Hz-Zhang

Copy link
Copy Markdown
Contributor

@Helios531 would you please fix the conflicts?

and i promise i'll check your PR

cike8899 and others added 15 commits June 11, 2026 16:36
…niflow#15942)

### What problem does this PR solve?

Fix: Remove the pagination from the search and retrieval pages.

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
### What problem does this PR solve?

- Add `web/src/locales/ko.ts` with full Korean translation (~3100 keys)
- Register `Ko = 'ko'` in `LanguageAbbreviation` enum (`common.ts`)
- Add `[LanguageAbbreviation.Ko]: '한국어'` to `LanguageAbbreviationMap`
- Add lazy-load entry in `web/src/locales/config.ts`
- Add `korean` key to all existing locale files (`ja`, `id`, `es`,
`pt-br`, `vi`, `zh-traditional`)
- Fix duplicate enum value `FileMimeType.Mdx` (`'text/markdown'` →
`'text/mdx'`)

### Type of change

- [x] New Feature (non-breaking change which adds functionality)
- [x] Other (please describe): Korean (한국어) i18n translation + fix
duplicate FileMimeType.Mdx enum value
…nfiniflow#15945)

## Summary

`get_model_config_from_provider_instance()` was not including
`max_tokens` in its returned dict, causing all downstream consumers
(dialog truncation, message fitting, knowledge base trimming, embedding,
graphrag, RAPTOR) to fall back to the hardcoded default of **8192
tokens** regardless of the actual model context window size (e.g.,
GPT-4o 128K, Claude 200K).

Closes infiniflow#15944

## Root Cause

The function builds `model_config` with only: `llm_factory`, `api_key`,
`llm_name`, `api_base`, `model_type`, `is_tools`. `max_tokens` is never
included.

Yet the data exists in four independent sources:
1. `TenantModel.extra` JSON field — written by
`provider_api_service.py:659`
2. `conf/llm_factories.json` — every model entry has `max_tokens`
3. `rag/llm/model_meta.py` — 9 provider classes fetch real context
windows from APIs
4. `TenantLLM.max_tokens` database column

None of them are read by this function.

## Fix

Two lines added, one per return path:

- **Path B** (model_obj exists → provider-instance model): reads
`max_tokens` from `model_obj.extra` JSON
- **Path C** (fallback → factory config): reads `max_tokens` from
`llm_info` (sourced from `llm_factories.json`)

Both fall back to 8192 when the value is absent, preserving backward
compatibility.

## Impact

This single 5-line change fixes the context window budget for all **78+
call sites** across **20 files** that construct `LLMBundle` or read
`max_tokens` from the config dict, including:

| Consumer | File | Effect |
|---|---|---|
| Dialog chat truncation | `dialog_service.py:562` |
`message_fit_in(msg, max_tokens * 0.95)` now uses real context window |
| Knowledge base trimming | `dialog_service.py:752` |
`kb_prompt(kbinfos, max_tokens)` now fits more retrieved content |
| Agent message fitting | `agent/component/llm.py:322` | Agent prompts
no longer truncated at 7946 tokens |
| Embedding truncation | `task_executor.py:704` | Embedding input uses
actual model limit |
| GraphRAG extraction | `graphrag/*/extractor.py` | Entity extraction
gets full context budget |
| LLM4Tenant.max_length | `tenant_llm_service.py:513` | Chat model
wrapper exposes real context window |
### What problem does this PR solve?

As title.

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
…#15939)

### What problem does this PR solve?

- Replace embedding model `dimension` metadata with `max_dimension`.
- Add optional `dimensions` metadata for models with fixed selectable
output dimensions.
- Include `max_dimension` and `dimensions` in model list responses.
- Validate requested embedding dimensions before calling provider
embedding APIs.
- Forward SiliconFlow embedding dimensions with the correct `dimensions`
request field.
- Add unit coverage for embedding dimension validation rules.
### What problem does this PR solve?

Initial draft for v0.26.0 release notes.

### Type of change


- [x] Documentation Update
…iflow#15941)

### What problem does this PR solve?

- Update version tags in README files (including translations) from
v0.25.6 to v0.26.0
- Modify Docker image references and documentation to reflect new
version
- Update version badges and image descriptions
- Maintain consistency across all language variants of README files

### Type of change

- [x] Documentation Update
infiniflow#15940)

### What problem does this PR solve?

As title

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
- [x] New Feature (non-breaking change which adds functionality)
- [x] Refactoring
…r Go model drivers (infiniflow#15821)

### What problem does this PR solve?

The Go model-driver layer () has ~38,700 lines across 109 files. Roughly
74% of that is boilerplate duplicated into every driver: identical HTTP
client setup, the same 65-line SSE scanner loop, and 10-11 one-line "not
supported" stub methods per driver. Any fix must be manually propagated
to every file. Closes infiniflow#15820.

This PR establishes the three shared utility files that form the
foundation for incremental driver migration:

---

### Type of change

- [x] New Feature (non-breaking change which adds functionality)
- [x] Refactoring

---------

Co-authored-by: Haruko386 <[email protected]>
…iniflow#15678)

## Summary

Improves the responsiveness of the User Settings layout by converting
the left navigation sidebar into a compact icon-only rail on mobile
devices.

Previously, the sidebar retained its full desktop width on narrow
viewports, reducing the available space for settings content and making
pages such as **Data Sources** difficult to use on phones and smaller
tablets.

With this change:

- Desktop layouts retain the existing full sidebar experience
- Mobile layouts (<768px) display a compact 64px icon-only navigation
rail
- Main content receives significantly more horizontal space
- Navigation and logout actions remain fully accessible on mobile

## Type of Change

- [x] Bug fix
## Screenshots

| Before | After |
|---------|---------|
| <img width="557" height="760" alt="image"
src="https://github.com/user-attachments/assets/fb0d6a90-2d57-464c-90c6-9097418c7c13"
/> | <img width="557" height="760" alt="image"
src="https://github.com/user-attachments/assets/8db36d0f-7070-41e1-b7b2-0fe9d0cceefb"
/> |

## What Changed

### Mobile Sidebar Optimization

- Added responsive mobile behavior using `useIsMobile()`
- Displays avatar and navigation icons only on mobile
- Hides user email, navigation labels, version information, theme
switcher, and logout text on smaller screens
- Preserves navigation and logout functionality through icon actions

### Layout Improvements

- Updated settings page grid layout to use fixed sidebar widths:
  - Mobile: `4rem` (64px)
  - Desktop: `303px`
- Uses `minmax(0, 1fr)` for the content panel to prevent overflow and
allow proper shrinking
- Prevents sidebar width from expanding based on content

## Impact

- Improves usability of User Settings pages on phones and small tablets
- Increases available space for settings content
- Reduces horizontal crowding and overflow issues
- Maintains the existing desktop experience

## Test Plan

### Desktop (≥768px)

- Verify the full sidebar is displayed
- Confirm email, navigation labels, version information, theme switch,
and logout text are visible
- Ensure all navigation items function correctly

### Mobile (<768px)

- Verify the sidebar collapses to a 64px icon-only rail
- Confirm main content remains readable without horizontal crowding
- Verify navigation icons route correctly:
  - Data Sources
  - Model Providers
  - MCP
  - Team
  - Profile
  - API
- Confirm logout works from the icon button

### Verification

- Run `npm run build`
- Hard refresh when testing production or Docker deployments
- Verify responsive behavior using browser device emulation
… embedding providers (infiniflow#15424)

### Summary

Closes infiniflow#15423

`rag/llm/embedding_model.py` hosts about 40 embedding providers that
shared several defects affecting indexing reliability, cost accounting,
and error visibility. This PR fixes four concrete bugs.

**Masked, inconsistent errors (27 sites).** Nearly every provider ran
`log_exception(_e, res)` followed by `raise Exception(f"Error: {res}")`.
Because `log_exception` always raises, the second line was dead code,
and the surfaced exception varied with whether the SDK response exposed
a `.text` attribute. Every failure path now raises a single
`EmbeddingError` that includes the underlying response detail, so the
cause of a failed embedding is consistent and visible.

**Fabricated token counts.** `LocalAIEmbed` returned a hardcoded `1024`
and `OllamaEmbed` added `128` per text. These values feed `used_tokens`
and therefore billing and usage tracking. Both now report the real count
from the API (Ollama `prompt_eval_count`, LocalAI `usage`) and fall back
to a local token count only when the server omits it.

**Truncation overshoot.** The `8196` limit used by Mistral and Bedrock
exceeded the standard `8192` ceiling and could push boundary sized
inputs past the model limit. Limits are corrected to `8192` and made
intentional per provider, and providers that rely on server side
truncation now request it explicitly (Ollama `truncate=True`, Cohere
`truncate="END"`).

**Missing batching on Zhipu and Ollama.** Both issued one request per
text. They now batch like the other OpenAI compatible providers, turning
N round trips into `ceil(N / batch_size)`. Batched results are realigned
by response `index` so a chunk always keeps its own vector.

A shared `Base._batched_encode` helper owns the batch loop, optional
truncation, result accumulation, and the single error path. It is the
mechanism that lets these fixes live in one place instead of across 27
duplicated sites. The public `encode()` and `encode_queries()` contract
stays the same, so existing callers are unaffected.

Tests covering all four fixes are added under
`test/unit_test/rag/llm/test_embedding_model.py`.

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
## Summary

Fixes infiniflow#15695.

The Python GraphRAG path already accumulates similarity when several
N-hop paths produce the same edge, but PageRank was overwritten by the
last path. That makes ranking depend on path order for repeated edges.

This keeps the strongest PageRank seen for a repeated edge in the Python
implementation:

- `rag/graphrag/search.py`

The similarity score still accumulates exactly as before.

## To verify

- `python -m py_compile rag\graphrag\search.py`
- `git diff --check`
- `git diff --stat upstream/main` -> only `rag/graphrag/search.py`

I originally included the Go implementation too, but removed it after
maintainer feedback because the Go version is still under development
and not released yet.
@Harry-Hz-Zhang

Copy link
Copy Markdown
Contributor

@Helios531 ur ci failing, could u fix this ?

@Helios531

Copy link
Copy Markdown
Contributor Author

Hi, @JinHai-CN, I have fixed CI failing. Could you review and merge my PR, plz?

@JinHai-CN

Copy link
Copy Markdown
Member

@Helios531 would you please fix the conflicts?

@JinHai-CN JinHai-CN self-assigned this Sep 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.