Skip to content

Refa: migrate MCP APIs to RESTful api - #14317

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
buua436:r005
Apr 23, 2026
Merged

JinHai-CN merged 3 commits into
infiniflow:mainfrom
buua436:r005

Conversation

@buua436

@buua436 buua436 commented Apr 23, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

migrate MCP APIs to RESTful api

Type of change

  • Refactoring

@coderabbitai

coderabbitai Bot commented Apr 23, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds a new Quart REST API module for MCP server management (list, detail, create, update, delete, import, test) and updates frontend API endpoints, service calls, hooks, types, and unit tests to use the new REST paths and response shapes.

Changes

Cohort / File(s) Summary
Backend REST API
api/apps/restful_apis/mcp_api.py
New Quart REST API registering handlers for list/detail/create/update/delete/import/test. Implements query parsing, pagination, tenant scoping, allowlisted server types, UTF-8 name checks, JSON parsing for headers/variables, duplicate-name resolution, threaded tool discovery with timeout, batch import with per-entry results, and test endpoint with MCPToolCallSession lifecycle.
Backend Tests
test/testcases/test_web_api/test_mcp_server_app/test_mcp_server_app_unit.py
Updated test loader to import the new API module and stub quart/constants; replaced request-args handling with _Args.getlist(), adjusted endpoint invocation patterns to direct calls, updated assertions and removed legacy export/tool-route tests; added download-mode detail tests.
Frontend API Definitions
web/src/utils/api.ts
Repointed MCP endpoints to REST v1 (/api/v1/mcp/servers), converted several endpoints to (id: string) => string builders, added export ?mode=download, added per-id test URL, and fixed minor spacing.
Frontend Service Layer
web/src/services/mcp-server-service.ts
Replaced registerServer with explicit request.get/post/put/delete functions; listMcpServers now uses GET with merged query params; get/export/update/delete/test flows updated to call new API builders and payload shapes.
Frontend Hooks
web/src/hooks/use-mcp-request.ts
useDeleteMcpServer and useExportMcpServer now perform per-id parallel requests (Promise.all), detect first failing response, aggregate successful results into a synthesized success payload, and control success toasts accordingly.
Frontend Types
web/src/interfaces/database/mcp.ts
IExportedMcpServers.mcpServers changed from a fixed-property interface to Record<string, IExportedMcpServer> to allow arbitrary keyed export objects.

Sequence Diagram

sequenceDiagram
    participant Client
    participant MCP_API as "MCP API (Quart)"
    participant ToolSvc as "MCPToolCallSession"
    participant ThreadPool as "ThreadPool"
    participant DB

    Client->>MCP_API: POST /mcp/servers/import (mcpServers map)
    MCP_API->>MCP_API: validate payload, resolve names
    loop per server entry
        MCP_API->>ThreadPool: schedule tool discovery task
        ThreadPool->>ToolSvc: run discovery (with timeout)
        ToolSvc-->>ThreadPool: return tools / error
        ThreadPool-->>MCP_API: tools result
        MCP_API->>MCP_API: attach tools to variables
        MCP_API->>DB: insert tenant-scoped server record
        DB-->>MCP_API: ack / error
    end
    MCP_API->>Client: aggregated per-server results (success/failure, rename info)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Poem

🐰 I hopped through new routes, one by one,
Threads chased tools till discovery was done,
Names reconciled and imports in store,
Tenants safe, responses returned — encore!
— A rabbit’s nibble of MCP fun.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 'Refa: migrate MCP APIs to RESTful api' clearly summarizes the main change: migrating MCP APIs to RESTful architecture, matching the refactoring changes across backend and frontend files.
Description check ✅ Passed The description includes the required template sections (What problem/Type of change) with 'Refactoring' checked, but provides only minimal detail about the migration scope and impact.
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.

@buua436 buua436 added the ci Continue Integration label Apr 23, 2026
@buua436
buua436 marked this pull request as ready for review April 23, 2026 02:59
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Apr 23, 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: 9

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
test/testcases/test_web_api/test_mcp_server_app/test_mcp_server_app_unit.py (1)

371-383: ⚠️ Potential issue | 🟡 Minor

Assertions codify a backend bug; update after fixing get_data_error_result calls.

assert res["code"] == "tools error" and assert res["code"] == "Failed to create MCP server." (and the equivalents in test_update_service_paths around Line 479) encode the current behavior in mcp_api.py where a str is passed positionally as the code arg of get_data_error_result. Once the backend is fixed to pass these as message=..., these assertions should be switched to check res["message"] instead of res["code"].

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/testcases/test_web_api/test_mcp_server_app/test_mcp_server_app_unit.py`
around lines 371 - 383, The tests currently assert error text against the
response "code" because the backend passes strings positionally to
get_data_error_result; after fixing mcp_api.py to pass those strings as
message=..., update the unit tests (e.g., in test_mcp_server_app_unit.py
assertions around create and update service paths) to assert the human-readable
string appears in res["message"] instead of res["code"] (replace the two
assertions in the shown diff and the equivalents in test_update_service_paths to
check res["message"] for "tools error" and "Failed to create MCP server.").
web/src/hooks/use-mcp-request.ts (1)

143-157: ⚠️ Potential issue | 🟠 Major

Partial-failure: list cache not invalidated when some deletes succeeded.

Promise.all resolves with every per-id response, and a partial failure (some ids deleted, others not) takes the failed branch, which skips both message.success and queryClient.invalidateQueries. The list will continue to show already-deleted entries until the user triggers another refetch. Consider invalidating the list whenever at least one delete succeeded (or unconditionally), independent of the aggregated failure status.

♻️ Proposed fix
       const failed = results.find(({ data = {} }) => data.code !== 0);
-      const data = failed?.data ?? { code: 0, data: true };
-      if (!failed) {
-        message.success(i18n.t(`message.deleted`));
-
-        queryClient.invalidateQueries({
-          queryKey: [McpApiAction.ListMcpServer],
-        });
-      }
+      const data = failed?.data ?? { code: 0, data: true };
+      const anySucceeded = results.some(({ data = {} }) => data.code === 0);
+      if (anySucceeded) {
+        queryClient.invalidateQueries({
+          queryKey: [McpApiAction.ListMcpServer],
+        });
+      }
+      if (!failed) {
+        message.success(i18n.t(`message.deleted`));
+      }
       return data;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/hooks/use-mcp-request.ts` around lines 143 - 157, The current
mutationFn uses Promise.all and, if any per-id delete fails, it treats the whole
operation as "failed" and skips message.success and
queryClient.invalidateQueries, leaving deleted items in the list; update
mutationFn (the function passed as mutationFn that calls
mcpServerService.delete) to detect whether any individual delete succeeded
(e.g., check results for any response with data.code === 0) and call
queryClient.invalidateQueries({ queryKey: [McpApiAction.ListMcpServer] }) when
at least one success (or simply always invalidate regardless of failures), and
still surface the appropriate aggregated data/result and call message.success
only when all or at least one deletion succeeded as desired; keep using the
existing mcpServerService.delete calls and message.success but ensure
invalidateQueries runs independently of the aggregated failed variable.
🧹 Nitpick comments (2)
test/testcases/test_web_api/test_mcp_server_app/test_mcp_server_app_unit.py (1)

667-719: Consider adding coverage for @login_required / tenant-ownership on sensitive endpoints.

Because login_required and validate_request are stubbed out as identity decorators in _load_mcp_api, the test suite cannot catch regressions where a handler forgets @login_required (see comment on test_mcp in mcp_api.py) or skips a tenant-ownership check (see rm). Adding an integration-level test that verifies the presence of these decorators — or exercises them via the real Quart app — would close that gap.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/testcases/test_web_api/test_mcp_server_app/test_mcp_server_app_unit.py`
around lines 667 - 719, Add an integration test that exercises the real Quart
app (not the stubbed _load_mcp_api) to verify authentication and
tenant-ownership are enforced: start the Quart test client, call the test_mcp
and rm endpoints without authenticating and assert a 401/unauthorized response,
then call them authenticated as a different tenant and assert a 403/forbidden
(or equivalent) response; alternatively, add assertions that the handler
functions test_mcp and rm have the login_required/validate_request wrappers
present if you prefer static checks. Ensure the test references the handler
names test_mcp and rm and uses the real decorator behavior rather than the
identity stubs so regressions are caught.
web/src/hooks/use-mcp-request.ts (1)

194-215: Per-id export: consider fan-out cost and surfacing partial successes.

Exporting N servers now issues N parallel HTTP requests (each backend call also runs a DB lookup). For a "select all and export" UX this can get noisy quickly; the previous single-call contract was cheaper. If the backend can accept multiple mcp_ids on a single endpoint (the _get_mcp_ids_from_args helper in mcp_api.py already parses comma-separated/multi-value mcp_ids), routing export through a single GET /mcp/servers?mcp_ids=...&mode=download-style call would both reduce load and give a single transactional success/failure signal. Also note: on any failure, all succeeded exports are discarded — users with partial results get nothing. Consider merging successes into the returned mcpServers while still reporting the error.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/hooks/use-mcp-request.ts` around lines 194 - 215, The current
mutationFn fans out N calls via mcpServerService.export({ mcp_id }), which is
noisy and discards partial successes; change it to call the backend once with
all ids (e.g., mcpServerService.export({ mcp_ids: ids.join(','), mode:
'download' })) if the API accepts multi-value ids (use _get_mcp_ids_from_args on
the backend), otherwise keep the parallel calls but collect and merge all
successful results into a single IExportedMcpServers return value (merge into
mcpServers in the reducer) and surface any errors separately instead of throwing
away successes; preserve the existing message.success only when there are no
failures and include error details in the returned ResponseType so the UI can
show partial success/failure.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@api/apps/restful_apis/mcp_api.py`:
- Around line 58-66: The query-param integer coercion for page/page_size is
being done before the try block, so non-numeric inputs raise unhandled
exceptions; move the int() parsing for page_number and items_per_page into the
existing try block (around the code using keywords, orderby, desc and the DB
call) or use a helper to validate/parse (e.g., get_int/get_float) and on parse
failure return get_data_error_result; update references to
request.args.get("page", 0) and request.args.get("page_size", 0) so parsing
happens inside the try and ensures invalid inputs produce a controlled
get_data_error_result response instead of a 500.
- Around line 84-90: When handling the detail?mode=download path, detect when
_export_mcp_servers([mcp_id]) returns no accessible servers and convert that
into a NOT_FOUND response instead of returning the empty successful payload;
specifically, call _export_mcp_servers([mcp_id]), inspect the returned structure
(e.g. empty "mcpServers" or equivalent), and if empty call
get_json_result(code=RetCode.NOT_FOUND, data=None) rather than returning the
export; keep the existing behavior for non-empty exports. Ensure this logic
aligns with the existing MCPServerService.get_or_none(current_user.id) tenant
checks so cross-tenant or nonexistent IDs produce the 404.
- Around line 161-169: The update handler currently allows an explicit empty
name because server_name = req.get("name", mcp_server.name) + if server_name and
len(...) only rejects too-long names; update the validation around server_name
in the update function so an explicitly provided empty string is rejected
(mirror the create guard). Specifically, detect when "name" is present in req
and either strip(name) == "" or len(name.encode("utf-8")) > 255 and return
get_data_error_result; keep using mcp_server.name as the default only when
"name" is not provided so filter_update cannot persist an empty name. Ensure you
reference server_name, req.get("name", ...), mcp_server, and the update
handler/filter_update flow when making the change.
- Around line 138-141: The code assumes server_tools contains server_name and
indexes it directly (server_tools[server_name]) which raises KeyError for
unexpected helper results from get_mcp_tools; change the access to a safe lookup
like server_tools.get(server_name, []) or [] and validate the result type before
iterating or building the tools mapping used to set variables["tools"]; apply
the same safe lookup/validation in the update and import_multiple code paths so
server_name absence yields an empty list (or a logged warning) rather than a
KeyError.
- Around line 284-286: The endpoint function test_mcp is missing the
`@login_required` decorator which leaves it unauthenticated and vulnerable; add
`@login_required` to the test_mcp declaration (place it after the
`@manager.route`(...) decorator and before `@validate_request`(...) to match the
other MCP endpoints) so only authenticated users can call it, and ensure the
login_required symbol is imported if not already and adjust/extend tests to
verify authentication is enforced.
- Around line 136-145: The bug is that get_data_error_result is being called
with a string as the first positional argument (clobbering the numeric code);
update the three calls in mcp_api.py to pass the message as the message keyword
(e.g., message=err_message or message="Failed to create MCP server.") or call
with the correct positional order (code=int, message=str) instead of a lone
string; specifically change the call after the err_message check, the call after
MCPServerService.insert failure, and the analogous call in the update function
so get_data_error_result receives a proper numeric code and the string as
message.
- Around line 205-214: rm currently calls
MCPServerService.delete_by_ids([mcp_id]) without verifying tenant ownership;
before deleting, fetch the MCP server (e.g., via MCPServerService.get_by_id or a
get_by_ids method) and confirm its owner equals current_user.id (same check used
in update/detail), returning an authorization error (or get_data_error_result)
if the owner mismatches or the server is not found, and only then call
MCPServerService.delete_by_ids([mcp_id]); preserve existing response patterns
and exception handling.
- Around line 250-269: The create flow currently builds a full variables dict
(variables = {k: v for k, v in config.items() if k not in {"type", "url",
"headers"}}) for discovery but only persists authorization_token + tools into
create_data["variables"], dropping other fields like tool_configuration; update
the creation logic so that create_data["variables"] is initialized from that
full variables dict (i.e., assign create_data["variables"] = variables or merge
variables into create_data["variables"]) before calling
MCPServerService.insert(), ensuring MCPServer (and subsequent get_mcp_tools/tool
discovery) still works and create_data["variables"]["tools"] is set after tools
are discovered.

In `@web/src/services/mcp-server-service.ts`:
- Around line 20-21: The test function is building the URL with
api.testMcpServer(params.name || 'preview') which is fragile because params.name
can contain URI-sensitive characters; update the call in the test arrow function
to either always pass the stable placeholder 'preview' or safely encode the
provided name (use encodeURIComponent(params.name)) before passing it to
api.testMcpServer so the URL path cannot break; locate the test function and the
api.testMcpServer invocation in web/src/services/mcp-server-service.ts and apply
the chosen change to ensure safe URL construction.

---

Outside diff comments:
In `@test/testcases/test_web_api/test_mcp_server_app/test_mcp_server_app_unit.py`:
- Around line 371-383: The tests currently assert error text against the
response "code" because the backend passes strings positionally to
get_data_error_result; after fixing mcp_api.py to pass those strings as
message=..., update the unit tests (e.g., in test_mcp_server_app_unit.py
assertions around create and update service paths) to assert the human-readable
string appears in res["message"] instead of res["code"] (replace the two
assertions in the shown diff and the equivalents in test_update_service_paths to
check res["message"] for "tools error" and "Failed to create MCP server.").

In `@web/src/hooks/use-mcp-request.ts`:
- Around line 143-157: The current mutationFn uses Promise.all and, if any
per-id delete fails, it treats the whole operation as "failed" and skips
message.success and queryClient.invalidateQueries, leaving deleted items in the
list; update mutationFn (the function passed as mutationFn that calls
mcpServerService.delete) to detect whether any individual delete succeeded
(e.g., check results for any response with data.code === 0) and call
queryClient.invalidateQueries({ queryKey: [McpApiAction.ListMcpServer] }) when
at least one success (or simply always invalidate regardless of failures), and
still surface the appropriate aggregated data/result and call message.success
only when all or at least one deletion succeeded as desired; keep using the
existing mcpServerService.delete calls and message.success but ensure
invalidateQueries runs independently of the aggregated failed variable.

---

Nitpick comments:
In `@test/testcases/test_web_api/test_mcp_server_app/test_mcp_server_app_unit.py`:
- Around line 667-719: Add an integration test that exercises the real Quart app
(not the stubbed _load_mcp_api) to verify authentication and tenant-ownership
are enforced: start the Quart test client, call the test_mcp and rm endpoints
without authenticating and assert a 401/unauthorized response, then call them
authenticated as a different tenant and assert a 403/forbidden (or equivalent)
response; alternatively, add assertions that the handler functions test_mcp and
rm have the login_required/validate_request wrappers present if you prefer
static checks. Ensure the test references the handler names test_mcp and rm and
uses the real decorator behavior rather than the identity stubs so regressions
are caught.

In `@web/src/hooks/use-mcp-request.ts`:
- Around line 194-215: The current mutationFn fans out N calls via
mcpServerService.export({ mcp_id }), which is noisy and discards partial
successes; change it to call the backend once with all ids (e.g.,
mcpServerService.export({ mcp_ids: ids.join(','), mode: 'download' })) if the
API accepts multi-value ids (use _get_mcp_ids_from_args on the backend),
otherwise keep the parallel calls but collect and merge all successful results
into a single IExportedMcpServers return value (merge into mcpServers in the
reducer) and surface any errors separately instead of throwing away successes;
preserve the existing message.success only when there are no failures and
include error details in the returned ResponseType so the UI can show partial
success/failure.
🪄 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: 1aaf217b-732c-4bbe-b9c4-50fd0617156d

📥 Commits

Reviewing files that changed from the base of the PR and between f98597a and 84aa744.

📒 Files selected for processing (6)
  • api/apps/restful_apis/mcp_api.py
  • test/testcases/test_web_api/test_mcp_server_app/test_mcp_server_app_unit.py
  • web/src/hooks/use-mcp-request.ts
  • web/src/interfaces/database/mcp.ts
  • web/src/services/mcp-server-service.ts
  • web/src/utils/api.ts

Comment on lines +58 to +66
keywords = request.args.get("keywords", "")
page_number = int(request.args.get("page", 0))
items_per_page = int(request.args.get("page_size", 0))
orderby = request.args.get("orderby", "create_time")
if request.args.get("desc", "true").lower() == "false":
desc = False
else:
desc = True

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 | 🟡 Minor

Query-param coercion happens outside the try block.

int(request.args.get("page", 0)) / int(request.args.get("page_size", 0)) on Lines 59-60 are executed before the try at Line 68. A non-numeric page=abc query string therefore surfaces as an unhandled 500 rather than a clean validation error. Wrap the parsing in the try, or validate explicitly (e.g., via get_float/get_int helpers) and return get_data_error_result on bad input.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/mcp_api.py` around lines 58 - 66, The query-param
integer coercion for page/page_size is being done before the try block, so
non-numeric inputs raise unhandled exceptions; move the int() parsing for
page_number and items_per_page into the existing try block (around the code
using keywords, orderby, desc and the DB call) or use a helper to validate/parse
(e.g., get_int/get_float) and on parse failure return get_data_error_result;
update references to request.args.get("page", 0) and
request.args.get("page_size", 0) so parsing happens inside the try and ensures
invalid inputs produce a controlled get_data_error_result response instead of a
500.

Comment thread api/apps/restful_apis/mcp_api.py Resolved
Comment thread api/apps/restful_apis/mcp_api.py Resolved
Comment on lines +138 to +141

tools = server_tools[server_name]
tools = {tool["name"]: tool for tool in tools if isinstance(tool, dict) and "name" in tool}
variables["tools"] = tools

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 | 🟡 Minor

server_tools[server_name] will raise KeyError on unexpected helper results.

If get_mcp_tools returns without err_message but with a dict that doesn't contain server_name (e.g., empty dict, or keyed differently), the subscript at Line 139 (and the equivalents at Lines 188 and 267 in update/import_multiple) raises KeyError. It will be caught by the outer except, but surfaces as an opaque 500. Prefer server_tools.get(server_name, []) or [] and validate before indexing.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/mcp_api.py` around lines 138 - 141, The code assumes
server_tools contains server_name and indexes it directly
(server_tools[server_name]) which raises KeyError for unexpected helper results
from get_mcp_tools; change the access to a safe lookup like
server_tools.get(server_name, []) or [] and validate the result type before
iterating or building the tools mapping used to set variables["tools"]; apply
the same safe lookup/validation in the update and import_multiple code paths so
server_name absence yields an empty list (or a logged warning) rather than a
KeyError.

Comment on lines +161 to +169
server_type = req.get("server_type", mcp_server.server_type)
if server_type and server_type not in VALID_MCP_SERVER_TYPES:
return get_data_error_result(message="Unsupported MCP server type.")
server_name = req.get("name", mcp_server.name)
if server_name and len(server_name.encode("utf-8")) > 255:
return get_data_error_result(message=f"Invalid MCP name or length is {len(server_name)} which is large than 255.")
url = req.get("url", mcp_server.url)
if not url:
return get_data_error_result(message="Invalid url.")

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 | 🟡 Minor

update accepts an empty name without validation.

server_name = req.get("name", mcp_server.name) followed by if server_name and len(...) > 255 means an explicitly empty "name": "" in the payload bypasses the length check and is then written straight into req and persisted via filter_update. Consider rejecting empty strings explicitly, mirroring the create guard on Line 108.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/mcp_api.py` around lines 161 - 169, The update handler
currently allows an explicit empty name because server_name = req.get("name",
mcp_server.name) + if server_name and len(...) only rejects too-long names;
update the validation around server_name in the update function so an explicitly
provided empty string is rejected (mirror the create guard). Specifically,
detect when "name" is present in req and either strip(name) == "" or
len(name.encode("utf-8")) > 255 and return get_data_error_result; keep using
mcp_server.name as the default only when "name" is not provided so filter_update
cannot persist an empty name. Ensure you reference server_name, req.get("name",
...), mcp_server, and the update handler/filter_update flow when making the
change.

Comment thread api/apps/restful_apis/mcp_api.py Resolved
Comment thread api/apps/restful_apis/mcp_api.py Resolved
Comment thread api/apps/restful_apis/mcp_api.py Resolved
Comment on lines +20 to +21
test: (params: Record<string, any>) =>
request.post(api.testMcpServer(params.name || 'preview'), { data: params }),

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 | 🟡 Minor

Using params.name as the URL path segment is fragile.

api.testMcpServer(params.name || 'preview') injects an arbitrary server name into the URL path. Backend test_mcp doesn't actually use mcp_id for lookup (it reads url/server_type from the body), so the value is purely a placeholder — but if params.name contains /, spaces, or other URI-sensitive characters, the request URL can break or collide with other routes. Either always pass 'preview' (or a stable constant) or encodeURIComponent(params.name).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/services/mcp-server-service.ts` around lines 20 - 21, The test
function is building the URL with api.testMcpServer(params.name || 'preview')
which is fragile because params.name can contain URI-sensitive characters;
update the call in the test arrow function to either always pass the stable
placeholder 'preview' or safely encode the provided name (use
encodeURIComponent(params.name)) before passing it to api.testMcpServer so the
URL path cannot break; locate the test function and the api.testMcpServer
invocation in web/src/services/mcp-server-service.ts and apply the chosen change
to ensure safe URL construction.

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

♻️ Duplicate comments (5)
api/apps/restful_apis/mcp_api.py (5)

139-140: ⚠️ Potential issue | 🟡 Minor

Use a safe lookup for discovered tools.

get_mcp_tools() can return an empty or differently keyed result on helper failures (api/utils/api_utils.py:720-750). Direct indexing still turns that into an opaque 500 instead of a controlled validation result.

🛠️ Proposed safe lookup
-        tools = server_tools[server_name]
+        tools = server_tools.get(server_name, []) or []
         tools = {tool["name"]: tool for tool in tools if isinstance(tool, dict) and "name" in tool}

Use server_tools.get(new_name, []) or [] in import_multiple().

Also applies to: 188-189, 270-271

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/mcp_api.py` around lines 139 - 140, The code directly
indexes server_tools[server_name] which can raise a KeyError when
get_mcp_tools() returns an unexpected shape; change the lookup to a safe get
(e.g., tools = server_tools.get(server_name, []) or []) before filtering and
building the dict so missing or non-list results become an empty list, and apply
the same pattern to the other occurrences noted (the similar lookups in
import_multiple() and the other places around lines 188-189 and 270-271) to
avoid turning helper failures into 500s.

253-272: ⚠️ Potential issue | 🟠 Major

Persist imported variables and headers instead of auth-only variables.

The import path computes variables from the full config, but create_data["variables"] only retains authorization_token plus discovered tools. Other imported values are silently dropped.

🛠️ Proposed import persistence fix
+            headers = safe_json_parse(config.get("headers", {}))
+            variables = {k: v for k, v in config.items() if k not in {"type", "url", "headers"}}
             create_data = {
                 "id": get_uuid(),
                 "tenant_id": current_user.id,
                 "name": new_name,
                 "url": config["url"],
                 "server_type": config["type"],
-                "variables": {"authorization_token": config.get("authorization_token", "")},
+                "variables": variables,
+                "headers": headers,
             }
 
-            headers = {"authorization_token": config["authorization_token"]} if "authorization_token" in config else {}
-            variables = {k: v for k, v in config.items() if k not in {"type", "url", "headers"}}
             mcp_server = MCPServer(id=new_name, name=new_name, url=config["url"], server_type=config["type"], variables=variables, headers=headers)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/mcp_api.py` around lines 253 - 272, create_data
currently only persists authorization_token and discovered tools, dropping other
imported config entries; update the code that builds create_data["variables"] so
it merges the full extracted variables and headers into the persisted payload
instead of only authorization_token—use the existing variables dict computed
from config (variables = {k: v for k, v in config.items() if k not in {"type",
"url", "headers"}}) and the headers dict when constructing create_data (and
ensure create_data["variables"]["tools"] still gets set from tools after
get_mcp_tools returns); references: create_data, variables, headers, config,
MCPServer, get_mcp_tools, create_data["variables"]["tools"].

58-68: ⚠️ Potential issue | 🟡 Minor

Move query-param integer parsing inside the guarded path.

int(request.args.get(...)) still runs before the try, so ?page=abc or ?page_size=abc can bypass the error handling and return an unhandled 500.

🛠️ Proposed validation placement
-    keywords = request.args.get("keywords", "")
-    page_number = int(request.args.get("page", 0))
-    items_per_page = int(request.args.get("page_size", 0))
-    orderby = request.args.get("orderby", "create_time")
-    if request.args.get("desc", "true").lower() == "false":
-        desc = False
-    else:
-        desc = True
-
-    mcp_ids = _get_mcp_ids_from_args()
     try:
+        keywords = request.args.get("keywords", "")
+        page_number = int(request.args.get("page", 0))
+        items_per_page = int(request.args.get("page_size", 0))
+        orderby = request.args.get("orderby", "create_time")
+        desc = request.args.get("desc", "true").lower() != "false"
+        mcp_ids = _get_mcp_ids_from_args()
+
         servers = MCPServerService.get_servers(current_user.id, mcp_ids, 0, 0, orderby, desc, keywords) or []
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/mcp_api.py` around lines 58 - 68, The integer parsing
for query params is happening before the try block and can raise uncaught
ValueError for bad inputs; move parsing of page_number and items_per_page (and
the boolean desc derivation) into the guarded block that begins the try where
_get_mcp_ids_from_args() is used, so convert request.args.get("page", ...) and
request.args.get("page_size", ...) to int inside the try and validate/handle
ValueError (return a controlled error response or default) and keep keywords and
orderby retrieval as-is; update references to page_number, items_per_page, and
desc accordingly within the try so malformed query values are handled by the
existing error handling.

164-166: ⚠️ Potential issue | 🟠 Major

Validate update names consistently and prevent duplicate renames.

An explicit empty "name": "" still bypasses validation, and renaming to another server’s name is not checked. Duplicate names are especially risky because export keys by server name and can overwrite entries.

🛠️ Proposed update-name validation
-    server_name = req.get("name", mcp_server.name)
-    if server_name and len(server_name.encode("utf-8")) > 255:
+    name_provided = "name" in req
+    server_name = req.get("name", mcp_server.name)
+    if name_provided and not server_name:
+        return get_data_error_result(message="Invalid MCP name.")
+    if len(server_name.encode("utf-8")) > 255:
         return get_data_error_result(message=f"Invalid MCP name or length is {len(server_name)} which is large than 255.")
+    if name_provided and server_name != mcp_server.name:
+        e, _ = MCPServerService.get_by_name_and_tenant(name=server_name, tenant_id=current_user.id)
+        if e:
+            return get_data_error_result(message="Duplicated MCP server name.")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/mcp_api.py` around lines 164 - 166, When updating a
server name (server_name from req and current mcp_server), ensure empty strings
are rejected and duplicate names are prevented: if "name" is present in req and
differs from mcp_server.name, first validate server_name is non-empty and its
UTF-8 byte length <= 255 (return get_data_error_result on failure), then check
the data store for an existing server with that name (e.g., query the
MCPServer/model used elsewhere) and return get_data_error_result if a different
server already has that name; only apply the rename when both checks pass.

84-85: ⚠️ Potential issue | 🟠 Major

Return NOT_FOUND for inaccessible download exports.

For mode=download, a missing or cross-tenant mcp_id still returns code=0 with an empty mcpServers payload. Keep this consistent with the non-download detail path.

🛠️ Proposed not-found handling
         if request.args.get("mode") == "download":
-            return get_json_result(data=_export_mcp_servers([mcp_id]))
+            export_data = _export_mcp_servers([mcp_id])
+            if not export_data.get("mcpServers"):
+                return get_json_result(code=RetCode.NOT_FOUND, data=None)
+            return get_json_result(data=export_data)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/mcp_api.py` around lines 84 - 85, When handling
mode="download" in the route, you must mirror the non-download detail path's
not-found behavior: check that the mcp exists and is accessible for the current
tenant before calling _export_mcp_servers, and if it is missing/inaccessible
return the same NOT_FOUND get_json_result used by the detail path instead of
returning code=0 with empty payload. Locate the download branch (the if
request.args.get("mode") == "download" block), perform the same mcp
lookup/authorization check used elsewhere (the same function or logic that the
non-download detail path uses), and return the identical get_json_result(...)
NOT_FOUND response when the check fails; only call _export_mcp_servers([mcp_id])
when the mcp is present and accessible.
🧹 Nitpick comments (1)
api/apps/restful_apis/mcp_api.py (1)

97-325: Add minimal logging around the new MCP REST flows.

Create/update/delete/import/test paths currently return errors without route context. Add structured logs for validation failures, discovery failures, and persistence failures to make these new flows operable. As per coding guidelines, **/*.py: Add logging for new flows.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/mcp_api.py` around lines 97 - 325, Add structured
logging to the new MCP REST flows: in create(), update(), rm(),
import_multiple(), and test_mcp() log validation failures (invalid
name/url/type), tenant/context (current_user.id and mcp_id/new_name), discovery
errors from thread_pool_exec(get_mcp_tools, ...) or
MCPToolCallSession.get_tools, and persistence failures from
MCPServerService.insert / filter_update / delete_by_ids; include the
route/action, input summary (name/url/server_type), error messages, and
exceptions so failures are easy to trace back to the specific function and
failing call (refer to create, update, rm, import_multiple, test_mcp,
get_mcp_tools, thread_pool_exec, MCPToolCallSession.get_tools,
MCPServerService.insert/filter_update/delete_by_ids in your edits).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@api/apps/restful_apis/mcp_api.py`:
- Around line 124-145: The request dict `req` contains a transient "timeout"
value read via get_float but that key must not be passed into DB operations;
remove or exclude the "timeout" key from `req` before calling
MCPServerService.insert(**req) (and similarly before
MCPServerService.filter_update(**req) in update()), e.g. delete req["timeout"]
or construct a new dict without "timeout" after reading timeout with get_float
so only persistent fields reach the MCPServerService methods.
- Around line 233-240: import_multiple() currently only checks for presence of
"type" and "url" keys; update the validation inside the servers loop in
import_multiple() to validate the actual values: ensure server_name is non-empty
and <=255 bytes, ensure config["type"] is one of the allowed MCP types (reuse
the same enum/list used by create_server/update_server/test_connection), and
ensure config["url"] is a non-empty, well-formed URL (or run it through the same
URL validator used by create/update/test). On validation failure, append the
same shaped result object with success: False and a clear message referencing
the failing field (type or url) so invalid entries are rejected during import.
- Around line 44-50: The export currently only writes authorization_token and
tools into exported_servers[server_key], losing other persisted MCPServer
metadata; update the export to include the full persisted fields from the
MCPServer instance by adding the entire mcp_server.variables and
mcp_server.headers into the exported payload (e.g., set "variables":
mcp_server.variables and "headers": mcp_server.headers) while retaining existing
keys like "authorization_token" and "tools" for backwards compatibility so
imported servers preserve connection headers and custom variables used by
common/mcp_tool_call_conn.py.
- Around line 174-183: The code currently calls variables.pop("tools", None)
which removes the cached tool map before MCP discovery and causes
get_mcp_tools() to lose per-tool enabled flags; restore preservation by not
dropping variables["tools"] prior to discovery—either remove the pop or move it
after calling get_mcp_tools(), or explicitly merge the existing
variables.get("tools") map into the new tools payload returned by
get_mcp_tools() so MCPServer(...) construction (and get_mcp_tools) can see and
preserve each tool's enabled state.

---

Duplicate comments:
In `@api/apps/restful_apis/mcp_api.py`:
- Around line 139-140: The code directly indexes server_tools[server_name] which
can raise a KeyError when get_mcp_tools() returns an unexpected shape; change
the lookup to a safe get (e.g., tools = server_tools.get(server_name, []) or [])
before filtering and building the dict so missing or non-list results become an
empty list, and apply the same pattern to the other occurrences noted (the
similar lookups in import_multiple() and the other places around lines 188-189
and 270-271) to avoid turning helper failures into 500s.
- Around line 253-272: create_data currently only persists authorization_token
and discovered tools, dropping other imported config entries; update the code
that builds create_data["variables"] so it merges the full extracted variables
and headers into the persisted payload instead of only authorization_token—use
the existing variables dict computed from config (variables = {k: v for k, v in
config.items() if k not in {"type", "url", "headers"}}) and the headers dict
when constructing create_data (and ensure create_data["variables"]["tools"]
still gets set from tools after get_mcp_tools returns); references: create_data,
variables, headers, config, MCPServer, get_mcp_tools,
create_data["variables"]["tools"].
- Around line 58-68: The integer parsing for query params is happening before
the try block and can raise uncaught ValueError for bad inputs; move parsing of
page_number and items_per_page (and the boolean desc derivation) into the
guarded block that begins the try where _get_mcp_ids_from_args() is used, so
convert request.args.get("page", ...) and request.args.get("page_size", ...) to
int inside the try and validate/handle ValueError (return a controlled error
response or default) and keep keywords and orderby retrieval as-is; update
references to page_number, items_per_page, and desc accordingly within the try
so malformed query values are handled by the existing error handling.
- Around line 164-166: When updating a server name (server_name from req and
current mcp_server), ensure empty strings are rejected and duplicate names are
prevented: if "name" is present in req and differs from mcp_server.name, first
validate server_name is non-empty and its UTF-8 byte length <= 255 (return
get_data_error_result on failure), then check the data store for an existing
server with that name (e.g., query the MCPServer/model used elsewhere) and
return get_data_error_result if a different server already has that name; only
apply the rename when both checks pass.
- Around line 84-85: When handling mode="download" in the route, you must mirror
the non-download detail path's not-found behavior: check that the mcp exists and
is accessible for the current tenant before calling _export_mcp_servers, and if
it is missing/inaccessible return the same NOT_FOUND get_json_result used by the
detail path instead of returning code=0 with empty payload. Locate the download
branch (the if request.args.get("mode") == "download" block), perform the same
mcp lookup/authorization check used elsewhere (the same function or logic that
the non-download detail path uses), and return the identical
get_json_result(...) NOT_FOUND response when the check fails; only call
_export_mcp_servers([mcp_id]) when the mcp is present and accessible.

---

Nitpick comments:
In `@api/apps/restful_apis/mcp_api.py`:
- Around line 97-325: Add structured logging to the new MCP REST flows: in
create(), update(), rm(), import_multiple(), and test_mcp() log validation
failures (invalid name/url/type), tenant/context (current_user.id and
mcp_id/new_name), discovery errors from thread_pool_exec(get_mcp_tools, ...) or
MCPToolCallSession.get_tools, and persistence failures from
MCPServerService.insert / filter_update / delete_by_ids; include the
route/action, input summary (name/url/server_type), error messages, and
exceptions so failures are easy to trace back to the specific function and
failing call (refer to create, update, rm, import_multiple, test_mcp,
get_mcp_tools, thread_pool_exec, MCPToolCallSession.get_tools,
MCPServerService.insert/filter_update/delete_by_ids in your edits).
🪄 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: 1347496b-706a-44ed-9363-339c9887d1e8

📥 Commits

Reviewing files that changed from the base of the PR and between 84aa744 and 9543c81.

📒 Files selected for processing (1)
  • api/apps/restful_apis/mcp_api.py

Comment on lines +44 to +50
exported_servers[server_key] = {
"type": mcp_server.server_type,
"url": mcp_server.url,
"name": mcp_server.name,
"authorization_token": mcp_server.variables.get("authorization_token", ""),
"tools": mcp_server.variables.get("tools", {}),
}

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

Export the full persisted MCP connection metadata.

MCPServer stores both variables and headers (api/db/db_models.py:1087-1097), and MCP sessions template headers from those values (common/mcp_tool_call_conn.py:42-110). Exporting only authorization_token and tools drops custom variables/headers, so a download → import cycle can produce a server that no longer connects.

♻️ Proposed export preservation
-            exported_servers[server_key] = {
-                "type": mcp_server.server_type,
-                "url": mcp_server.url,
-                "name": mcp_server.name,
-                "authorization_token": mcp_server.variables.get("authorization_token", ""),
-                "tools": mcp_server.variables.get("tools", {}),
-            }
+            variables = dict(mcp_server.variables or {})
+            exported_servers[server_key] = {
+                **variables,
+                "type": mcp_server.server_type,
+                "url": mcp_server.url,
+                "name": mcp_server.name,
+                "headers": mcp_server.headers or {},
+            }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/mcp_api.py` around lines 44 - 50, The export currently
only writes authorization_token and tools into exported_servers[server_key],
losing other persisted MCPServer metadata; update the export to include the full
persisted fields from the MCPServer instance by adding the entire
mcp_server.variables and mcp_server.headers into the exported payload (e.g., set
"variables": mcp_server.variables and "headers": mcp_server.headers) while
retaining existing keys like "authorization_token" and "tools" for backwards
compatibility so imported servers preserve connection headers and custom
variables used by common/mcp_tool_call_conn.py.

Comment on lines +124 to +145
timeout = get_float(req, "timeout", 10)

try:
req["id"] = get_uuid()
req["tenant_id"] = current_user.id

e, _ = TenantService.get_by_id(current_user.id)
if not e:
return get_data_error_result(message="Tenant not found.")

mcp_server = MCPServer(id=server_name, name=server_name, url=url, server_type=server_type, variables=variables, headers=headers)
server_tools, err_message = await thread_pool_exec(get_mcp_tools, [mcp_server], timeout)
if err_message:
return get_data_error_result(message=err_message)

tools = server_tools[server_name]
tools = {tool["name"]: tool for tool in tools if isinstance(tool, dict) and "name" in tool}
variables["tools"] = tools
req["variables"] = variables

if not MCPServerService.insert(**req):
return get_data_error_result(message="Failed to create MCP server.")

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

Do not pass transient timeout into database writes.

timeout is read from req, but req is later passed to MCPServerService.insert() / filter_update(). The MCPServer model has no timeout column (api/db/db_models.py:1087-1097), so requests that include this supported option can fail persistence.

🛠️ Proposed persistence guard
     timeout = get_float(req, "timeout", 10)
+    req.pop("timeout", None)

Apply the same immediately after Line 177 in update().

Also applies to: 177-194

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/mcp_api.py` around lines 124 - 145, The request dict
`req` contains a transient "timeout" value read via get_float but that key must
not be passed into DB operations; remove or exclude the "timeout" key from `req`
before calling MCPServerService.insert(**req) (and similarly before
MCPServerService.filter_update(**req) in update()), e.g. delete req["timeout"]
or construct a new dict without "timeout" after reading timeout with get_float
so only persistent fields reach the MCPServerService methods.

Comment on lines +174 to +183
variables = safe_json_parse(req.get("variables", mcp_server.variables))
variables.pop("tools", None)

timeout = get_float(req, "timeout", 10)

try:
req["tenant_id"] = current_user.id
req["id"] = mcp_id

mcp_server = MCPServer(id=server_name, name=server_name, url=url, server_type=server_type, variables=variables, headers=headers)

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

Preserve existing tool enabled flags during update discovery.

variables.pop("tools", None) removes the cached tool map before calling get_mcp_tools(), but that helper uses variables["tools"] to preserve each tool’s enabled state (api/utils/api_utils.py:720-750). Updating any server can reset disabled tools back to enabled.

🛠️ Proposed enabled-state preservation
     variables = safe_json_parse(req.get("variables", mcp_server.variables))
-    variables.pop("tools", None)
+    cached_tools = variables.get("tools", {}) or {}

@@
-        mcp_server = MCPServer(id=server_name, name=server_name, url=url, server_type=server_type, variables=variables, headers=headers)
+        discovery_variables = {**variables, "tools": cached_tools}
+        mcp_server = MCPServer(id=server_name, name=server_name, url=url, server_type=server_type, variables=discovery_variables, headers=headers)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/mcp_api.py` around lines 174 - 183, The code currently
calls variables.pop("tools", None) which removes the cached tool map before MCP
discovery and causes get_mcp_tools() to lose per-tool enabled flags; restore
preservation by not dropping variables["tools"] prior to discovery—either remove
the pop or move it after calling get_mcp_tools(), or explicitly merge the
existing variables.get("tools") map into the new tools payload returned by
get_mcp_tools() so MCPServer(...) construction (and get_mcp_tools) can see and
preserve each tool's enabled state.

Comment on lines +233 to +240
for server_name, config in servers.items():
if not all(key in config for key in {"type", "url"}):
results.append({"server": server_name, "success": False, "message": "Missing required fields (type or url)"})
continue

if not server_name or len(server_name.encode("utf-8")) > 255:
results.append({"server": server_name, "success": False, "message": f"Invalid MCP name or length is {len(server_name)} which is large than 255."})
continue

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

Validate imported server type and URL values, not just key presence.

import_multiple() accepts {"type": "bad", "url": ""} because it only checks that keys exist. This bypasses the validation used by create/update/test and can persist unusable MCP servers.

🛠️ Proposed import validation
             if not all(key in config for key in {"type", "url"}):
                 results.append({"server": server_name, "success": False, "message": "Missing required fields (type or url)"})
                 continue
+            if config["type"] not in VALID_MCP_SERVER_TYPES:
+                results.append({"server": server_name, "success": False, "message": "Unsupported MCP server type."})
+                continue
+            if not config["url"]:
+                results.append({"server": server_name, "success": False, "message": "Invalid url."})
+                continue
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/mcp_api.py` around lines 233 - 240, import_multiple()
currently only checks for presence of "type" and "url" keys; update the
validation inside the servers loop in import_multiple() to validate the actual
values: ensure server_name is non-empty and <=255 bytes, ensure config["type"]
is one of the allowed MCP types (reuse the same enum/list used by
create_server/update_server/test_connection), and ensure config["url"] is a
non-empty, well-formed URL (or run it through the same URL validator used by
create/update/test). On validation failure, append the same shaped result object
with success: False and a clear message referencing the failing field (type or
url) so invalid entries are rejected during import.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

♻️ Duplicate comments (7)
api/apps/restful_apis/mcp_api.py (7)

62-63: ⚠️ Potential issue | 🟡 Minor

Move query-param coercion inside validation handling.

int(...) still runs before the try, so ?page=abc or ?page_size=abc bypasses server_error_response and can surface as an unhandled request failure. This matches the prior finding and still appears unresolved.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/mcp_api.py` around lines 62 - 63, The code currently
calls int(...) on request.args.get("page") and request.args.get("page_size")
outside the try/validation block, so invalid params (e.g., ?page=abc) can raise
before server_error_response handles them; move the numeric coercion for
page_number and items_per_page into the validation/try block (or wrap each
int(...) in try/except/ValueError) where server_error_response is used, validate
that request.args.get returns a value or default first, and ensure the code uses
the same identifiers page_number and items_per_page after safe coercion so
invalid inputs are caught and responded to consistently.

145-147: ⚠️ Potential issue | 🟡 Minor

Avoid direct indexing into server_tools.

server_tools[server_name] / server_tools[new_name] still turns an unexpected helper result into a KeyError and opaque 500. Use .get(..., []) and validate the returned list shape. This matches the prior helper-result robustness finding and still appears unresolved.

Also applies to: 194-197, 276-278

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/mcp_api.py` around lines 145 - 147, Replace direct
indexing of server_tools (e.g., server_tools[server_name] and
server_tools[new_name]) with server_tools.get(server_name, []) /
server_tools.get(new_name, []) and explicitly validate the result is an
iterable/list before comprehending it; update the assignments that produce
variables["tools"] (and the analogous blocks around the other occurrences) to
first fetch with .get(..., []), check isinstance(result, (list, tuple)) or
coerce to [] if invalid, then build the dict comprehension only from dict items
with a "name" key.

180-197: ⚠️ Potential issue | 🟠 Major

Preserve existing tool enabled flags during rediscovery.

variables.pop("tools", None) still removes the cached tool map before get_mcp_tools() can preserve per-tool enabled state, so updating a server can re-enable disabled tools. This matches the prior enabled-state preservation finding and still appears unresolved.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/mcp_api.py` around lines 180 - 197, The code currently
removes the cached tools with variables.pop("tools", None) before calling
get_mcp_tools, which prevents preserving per-tool "enabled" flags; instead,
retain or capture the existing tool map from mcp_server.variables (e.g.,
old_tools = mcp_server.variables.get("tools") or similar) before calling
get_mcp_tools, call get_mcp_tools(mcp_server) to get fresh server_tools, then
merge the old "enabled" values into the newly discovered tools by matching on
tool["name"] (symbols: variables, mcp_server, variables.pop, get_mcp_tools,
server_tools, tools), and finally set variables["tools"] to the merged map and
put it back into req["variables"] so disabled flags persist.

44-50: ⚠️ Potential issue | 🟠 Major

Export the full persisted MCP connection metadata.

The download payload still drops headers and any variables entries beyond authorization_token/tools, so export → import can lose connection data needed by MCP sessions. This matches the prior data-preservation finding and still appears unresolved.

Proposed preservation shape
-            exported_servers[server_key] = {
-                "type": mcp_server.server_type,
-                "url": mcp_server.url,
-                "name": mcp_server.name,
-                "authorization_token": mcp_server.variables.get("authorization_token", ""),
-                "tools": mcp_server.variables.get("tools", {}),
-            }
+            variables = mcp_server.variables or {}
+            exported_servers[server_key] = {
+                **variables,
+                "type": mcp_server.server_type,
+                "url": mcp_server.url,
+                "name": mcp_server.name,
+                "headers": mcp_server.headers or {},
+            }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/mcp_api.py` around lines 44 - 50, The export currently
only writes selected fields (authorization_token and tools) into
exported_servers for each server_key, causing loss of persisted connection data;
update the export to include the full persisted metadata by adding the complete
variables map and any headers from the mcp_server object (e.g., include
"variables": mcp_server.variables and "headers": mcp_server.headers alongside
the existing type/url/name/authorization_token/tools entries) so import can
fully reconstruct MCP connections using the exported_servers and mcp_server
data.

130-150: ⚠️ Potential issue | 🟠 Major

Strip transient timeout before database writes.

timeout is read from req, but req is later passed to insert() / filter_update(). Since MCPServer has no timeout column, supported requests that include it can fail persistence. This matches the prior persistence-guard finding and still appears unresolved.

Remove transient request field
     timeout = get_float(req, "timeout", 10)
+    req.pop("timeout", None)

Apply the same immediately after the timeout read in update().

Also applies to: 183-199

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/mcp_api.py` around lines 130 - 150, The transient
"timeout" pulled with timeout = get_float(req, "timeout", 10) is left in req and
later passed into persistence calls (MCPServerService.insert and filter_update),
causing DB errors because MCPServer has no timeout column; remove or pop the
"timeout" key from req immediately after reading it (and do the same in the
update() path) so that req passed to MCPServerService.insert(...) and
MCPServerService.filter_update(...) does not contain the transient timeout
field.

259-278: ⚠️ Potential issue | 🟠 Major

Persist imported headers and full variables used for discovery.

headers and the wider variables dict are used for discovery, but only authorization_token plus discovered tools are persisted. Imported headers, tool_configuration, and custom variables are lost. This overlaps the prior import data-loss finding and still appears unresolved.

Persist import metadata
-            create_data = {
+            headers = safe_json_parse(config.get("headers", {}))
+            if not isinstance(headers, dict):
+                results.append({"server": server_name, "success": False, "message": "Invalid headers."})
+                continue
+            variables = {k: v for k, v in config.items() if k not in {"type", "url", "headers"}}
+
+            create_data = {
                 "id": get_uuid(),
                 "tenant_id": current_user.id,
                 "name": new_name,
                 "url": config["url"],
                 "server_type": config["type"],
-                "variables": {"authorization_token": config.get("authorization_token", "")},
+                "variables": variables,
+                "headers": headers,
             }
 
-            headers = {"authorization_token": config["authorization_token"]} if "authorization_token" in config else {}
-            variables = {k: v for k, v in config.items() if k not in {"type", "url", "headers"}}
             mcp_server = MCPServer(id=new_name, name=new_name, url=config["url"], server_type=config["type"], variables=variables, headers=headers)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/mcp_api.py` around lines 259 - 278, The code only
persists authorization_token and discovered tools into create_data, dropping
imported headers, tool_configuration and other custom variables; update the
creation logic around create_data, variables, headers and MCPServer so the
original discovery inputs are persisted: include the full variables dict (from
variables = {k: v for k, v in config.items() if k not in
{"type","url","headers"}}) into create_data (e.g., merge or assign into
create_data["variables"]), persist the imported headers (headers) into
create_data (e.g., create_data["headers"] = headers), and also capture any
config.get("tool_configuration") or other custom keys into create_data so
create_data contains authorization_token, headers, the full variables,
tool_configuration and the discovered tools (do not remove the existing
assignment to create_data["variables"]["tools"] and ensure MCPServer(...) still
receives the same headers/variables for discovery).

239-246: ⚠️ Potential issue | 🟠 Major

Validate imported config values, not only key presence.

import_multiple() still accepts unsupported type values and empty/malformed URLs as long as the keys exist, bypassing the create/update/test validation path. This matches the prior import validation finding and still appears unresolved.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/mcp_api.py` around lines 239 - 246, The
import_multiple() loop currently only checks for the presence of keys but not
the validity of their values; update the loop over servers.items() to validate
config["type"] against the allowed MCP types and validate config["url"] is
non-empty and a well-formed URL (use urllib.parse or the existing URL/validator
helper) before skipping to create/update; if validation fails append a failure
result and continue, otherwise pass the validated config into the existing
create/update/test validation path (e.g., call the same validator used by
create/update/test operations) so unsupported types or malformed URLs no longer
bypass validation.
🧹 Nitpick comments (1)
test/testcases/test_web_api/test_mcp_server_app/test_mcp_server_app_unit.py (1)

471-518: Add assertions for persistence payloads and duplicate-name behavior.

These tests exercise success paths but don’t verify that timeout/extra request fields are excluded, imported/exported headers and variables are preserved, or update rejects duplicate names. Add targeted assertions when fixing the API paths above. Based on learnings, test/**/*.py: Add/adjust tests for behavior changes.

Also applies to: 619-633, 656-658

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/testcases/test_web_api/test_mcp_server_app/test_mcp_server_app_unit.py`
around lines 471 - 518, Add assertions in the test block exercising
module.update to validate persistence payload/duplicate-name behavior: after
each _run(module.update("mcp-1")) call assert that returned res["data"] (on
success) does not include request-only fields like timeout or other extra keys,
and that imported/exported headers and variables from the mocked
existing/updated objects are preserved in res["data"] (check fields like
headers, exported_variables or similar names used by your models); for error
paths assert the response message/code indicates duplicate-name rejection when
MCPServerService.filter_update returns False and/or when thread_pool_exec
reports duplicate tool names; locate and update tests around the mocked
functions MCPServerService.get_by_id, MCPServerService.filter_update, and
thread_pool_exec to add these targeted assertions and also mirror the same
checks in similar test blocks mentioned (lines ~619-633 and ~656-658).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@api/apps/restful_apis/mcp_api.py`:
- Around line 125-128: The parsed headers and variables from safe_json_parse can
be non-dict JSON (e.g., list or string), so calls like variables.pop("tools",
None) and downstream persistence/sessions may fail or store wrong shapes; update
the code where headers and variables are parsed (the block using
safe_json_parse, assigning req["headers"], and variables.pop("tools", None)) to
validate that both parsed values are dicts and raise/return a data error if not;
apply the same shape-check logic in the update() and test_mcp() handlers so they
also verify that safe_json_parse(...) returns a dict for headers and variables
before using or modifying them.
- Around line 170-172: When updating an MCP server in update(), after extracting
server_name from req (and after the length check with
server_name.encode("utf-8") <= 255), add a duplicate-name guard: query the
datastore for an existing server with the same name and tenant_id (or owner) but
a different id than mcp_server.id; if such a record exists, return
get_data_error_result with a clear message rejecting duplicate names. Ensure you
reference the same lookup used elsewhere (the create()/import collision logic)
and exclude the current mcp_server by id when checking for collisions so
renaming to the same value is allowed but renaming to another server's name is
rejected.

---

Duplicate comments:
In `@api/apps/restful_apis/mcp_api.py`:
- Around line 62-63: The code currently calls int(...) on
request.args.get("page") and request.args.get("page_size") outside the
try/validation block, so invalid params (e.g., ?page=abc) can raise before
server_error_response handles them; move the numeric coercion for page_number
and items_per_page into the validation/try block (or wrap each int(...) in
try/except/ValueError) where server_error_response is used, validate that
request.args.get returns a value or default first, and ensure the code uses the
same identifiers page_number and items_per_page after safe coercion so invalid
inputs are caught and responded to consistently.
- Around line 145-147: Replace direct indexing of server_tools (e.g.,
server_tools[server_name] and server_tools[new_name]) with
server_tools.get(server_name, []) / server_tools.get(new_name, []) and
explicitly validate the result is an iterable/list before comprehending it;
update the assignments that produce variables["tools"] (and the analogous blocks
around the other occurrences) to first fetch with .get(..., []), check
isinstance(result, (list, tuple)) or coerce to [] if invalid, then build the
dict comprehension only from dict items with a "name" key.
- Around line 180-197: The code currently removes the cached tools with
variables.pop("tools", None) before calling get_mcp_tools, which prevents
preserving per-tool "enabled" flags; instead, retain or capture the existing
tool map from mcp_server.variables (e.g., old_tools =
mcp_server.variables.get("tools") or similar) before calling get_mcp_tools, call
get_mcp_tools(mcp_server) to get fresh server_tools, then merge the old
"enabled" values into the newly discovered tools by matching on tool["name"]
(symbols: variables, mcp_server, variables.pop, get_mcp_tools, server_tools,
tools), and finally set variables["tools"] to the merged map and put it back
into req["variables"] so disabled flags persist.
- Around line 44-50: The export currently only writes selected fields
(authorization_token and tools) into exported_servers for each server_key,
causing loss of persisted connection data; update the export to include the full
persisted metadata by adding the complete variables map and any headers from the
mcp_server object (e.g., include "variables": mcp_server.variables and
"headers": mcp_server.headers alongside the existing
type/url/name/authorization_token/tools entries) so import can fully reconstruct
MCP connections using the exported_servers and mcp_server data.
- Around line 130-150: The transient "timeout" pulled with timeout =
get_float(req, "timeout", 10) is left in req and later passed into persistence
calls (MCPServerService.insert and filter_update), causing DB errors because
MCPServer has no timeout column; remove or pop the "timeout" key from req
immediately after reading it (and do the same in the update() path) so that req
passed to MCPServerService.insert(...) and MCPServerService.filter_update(...)
does not contain the transient timeout field.
- Around line 259-278: The code only persists authorization_token and discovered
tools into create_data, dropping imported headers, tool_configuration and other
custom variables; update the creation logic around create_data, variables,
headers and MCPServer so the original discovery inputs are persisted: include
the full variables dict (from variables = {k: v for k, v in config.items() if k
not in {"type","url","headers"}}) into create_data (e.g., merge or assign into
create_data["variables"]), persist the imported headers (headers) into
create_data (e.g., create_data["headers"] = headers), and also capture any
config.get("tool_configuration") or other custom keys into create_data so
create_data contains authorization_token, headers, the full variables,
tool_configuration and the discovered tools (do not remove the existing
assignment to create_data["variables"]["tools"] and ensure MCPServer(...) still
receives the same headers/variables for discovery).
- Around line 239-246: The import_multiple() loop currently only checks for the
presence of keys but not the validity of their values; update the loop over
servers.items() to validate config["type"] against the allowed MCP types and
validate config["url"] is non-empty and a well-formed URL (use urllib.parse or
the existing URL/validator helper) before skipping to create/update; if
validation fails append a failure result and continue, otherwise pass the
validated config into the existing create/update/test validation path (e.g.,
call the same validator used by create/update/test operations) so unsupported
types or malformed URLs no longer bypass validation.

---

Nitpick comments:
In `@test/testcases/test_web_api/test_mcp_server_app/test_mcp_server_app_unit.py`:
- Around line 471-518: Add assertions in the test block exercising module.update
to validate persistence payload/duplicate-name behavior: after each
_run(module.update("mcp-1")) call assert that returned res["data"] (on success)
does not include request-only fields like timeout or other extra keys, and that
imported/exported headers and variables from the mocked existing/updated objects
are preserved in res["data"] (check fields like headers, exported_variables or
similar names used by your models); for error paths assert the response
message/code indicates duplicate-name rejection when
MCPServerService.filter_update returns False and/or when thread_pool_exec
reports duplicate tool names; locate and update tests around the mocked
functions MCPServerService.get_by_id, MCPServerService.filter_update, and
thread_pool_exec to add these targeted assertions and also mirror the same
checks in similar test blocks mentioned (lines ~619-633 and ~656-658).
🪄 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: 76afa719-637b-4a1f-8a85-f043d91b4ca9

📥 Commits

Reviewing files that changed from the base of the PR and between 9543c81 and eae9836.

📒 Files selected for processing (2)
  • api/apps/restful_apis/mcp_api.py
  • test/testcases/test_web_api/test_mcp_server_app/test_mcp_server_app_unit.py

Comment on lines +121 to +123
url = req.get("url", "")
if not url:
return get_data_error_result(message="Invalid url.")

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

Add SSRF-aware URL validation before outbound MCP calls.

These paths accept any non-empty URL and then initiate outbound MCP discovery/test calls. Validate scheme/host and block loopback, link-local, metadata, and private network targets unless explicitly allowed for the tenant/environment.

Also applies to: 173-175, 263-271, 299-319

Comment on lines +125 to +128
headers = safe_json_parse(req.get("headers", {}))
req["headers"] = headers
variables = safe_json_parse(req.get("variables", {}))
variables.pop("tools", None)

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

Validate parsed headers and variables are JSON objects.

safe_json_parse() can return non-dict JSON values; variables.pop("tools", None) then raises for lists, and headers/variables can be persisted or passed to sessions with the wrong shape. Return a data error unless both parse to dicts.

Guard parsed JSON shape
     headers = safe_json_parse(req.get("headers", {}))
+    if not isinstance(headers, dict):
+        return get_data_error_result(message="Invalid headers.")
     req["headers"] = headers
     variables = safe_json_parse(req.get("variables", {}))
+    if not isinstance(variables, dict):
+        return get_data_error_result(message="Invalid variables.")
     variables.pop("tools", None)

Apply the same shape check in update() and test_mcp().

Also applies to: 177-181, 307-311

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/mcp_api.py` around lines 125 - 128, The parsed headers
and variables from safe_json_parse can be non-dict JSON (e.g., list or string),
so calls like variables.pop("tools", None) and downstream persistence/sessions
may fail or store wrong shapes; update the code where headers and variables are
parsed (the block using safe_json_parse, assigning req["headers"], and
variables.pop("tools", None)) to validate that both parsed values are dicts and
raise/return a data error if not; apply the same shape-check logic in the
update() and test_mcp() handlers so they also verify that safe_json_parse(...)
returns a dict for headers and variables before using or modifying them.

Comment on lines +170 to +172
server_name = req.get("name", mcp_server.name)
if server_name and len(server_name.encode("utf-8")) > 255:
return get_data_error_result(message=f"Invalid MCP name or length is {len(server_name)} which is large than 255.")

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

Reject duplicate names on update.

create() and import collision handling prevent per-tenant duplicate names, but update() can rename a server to an existing name. That breaks the uniqueness assumption and can overwrite entries during name-keyed export.

Add duplicate-name guard
     server_name = req.get("name", mcp_server.name)
     if server_name and len(server_name.encode("utf-8")) > 255:
         return get_data_error_result(message=f"Invalid MCP name or length is {len(server_name)} which is large than 255.")
+    if "name" in req and server_name != mcp_server.name:
+        exists, existing_server = MCPServerService.get_by_name_and_tenant(name=server_name, tenant_id=current_user.id)
+        if exists and existing_server.id != mcp_id:
+            return get_data_error_result(message="Duplicated MCP server name.")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/mcp_api.py` around lines 170 - 172, When updating an
MCP server in update(), after extracting server_name from req (and after the
length check with server_name.encode("utf-8") <= 255), add a duplicate-name
guard: query the datastore for an existing server with the same name and
tenant_id (or owner) but a different id than mcp_server.id; if such a record
exists, return get_data_error_result with a clear message rejecting duplicate
names. Ensure you reference the same lookup used elsewhere (the create()/import
collision logic) and exclude the current mcp_server by id when checking for
collisions so renaming to the same value is allowed but renaming to another
server's name is rejected.

@codecov

codecov Bot commented Apr 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.97%. Comparing base (ffa8738) to head (eae9836).
⚠️ Report is 7 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #14317      +/-   ##
==========================================
- Coverage   97.41%   95.97%   -1.44%     
==========================================
  Files          10       10              
  Lines         695      695              
  Branches      111      111              
==========================================
- Hits          677      667      -10     
- Misses          7       11       +4     
- Partials       11       17       +6     

☔ View full report in Codecov by Sentry.
📢 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.

@JinHai-CN
JinHai-CN merged commit aa45262 into infiniflow:main Apr 23, 2026
1 check passed
@coderabbitai coderabbitai Bot mentioned this pull request Apr 23, 2026
1 task done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants