Skip to content

Fix: close MCP sessions after canvas execution to prevent connection leaks - #13295

Merged
yuzhichang merged 7 commits into
infiniflow:mainfrom
Br1an67:fix/issue-12962-mcp-conn-release
Jul 2, 2026
Merged

yuzhichang merged 7 commits into
infiniflow:mainfrom
Br1an67:fix/issue-12962-mcp-conn-release

Conversation

@Br1an67

@Br1an67 Br1an67 commented Mar 1, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Closes #12962

MCPToolCallSessions created during agent execution (in Agent.__init__) are never explicitly closed. Each session starts its own event loop thread and opens an SSE/HTTP connection to the MCP server. When the canvas goes out of scope, these threads and connections remain alive indefinitely, accumulating over time and causing resource exhaustion after prolonged use.

Solution

  1. Add a Graph.close() method that iterates all components, finds MCPToolCallSessions held by Agent tools, and calls close_sync() on each to properly shut down the event loop, thread, and connection.
  2. Call canvas.close() in finally blocks after canvas.run() completes in canvas_service.py and canvas_app.py.
  3. Move MCP session cleanup to finally blocks in test_tool endpoint (mcp_server_app.py) and get_mcp_tools (api_utils.py) to ensure sessions are closed even on exceptions.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

…leaks

Add Graph.close() method that finds and closes all MCPToolCallSessions
held by Agent components. Call it in finally blocks after canvas.run()
in canvas_service.py and canvas_app.py. Also move session cleanup to
finally blocks in test_tool endpoint and get_mcp_tools to ensure
sessions are closed even on exceptions.
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Mar 1, 2026
@Br1an67 Br1an67 mentioned this pull request Mar 1, 2026
4 tasks done
@yingfeng
yingfeng requested a review from Copilot March 5, 2026 12:52

Copilot AI 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.

Pull request overview

This PR addresses MCP connection leaks by ensuring MCPToolCallSession instances created during canvas/agent execution are reliably closed after use, preventing accumulated threads/SSE connections from exhausting resources over time.

Changes:

  • Add Graph.close() to close any MCP tool-call sessions held by Agent tools.
  • Ensure canvas.close() is invoked in finally blocks after streaming execution paths complete.
  • Move MCP session cleanup into finally blocks for MCP-related API endpoints/utilities to run even on exceptions.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated no comments.

Show a summary per file
File Description
api/utils/api_utils.py Ensures MCP sessions created during get_mcp_tools are always closed via finally.
api/db/services/canvas_service.py Adds finally cleanup to close the canvas after streamed completion.
api/apps/mcp_server_app.py Ensures MCP tool-call sessions are closed even when test_tool errors/returns early.
api/apps/canvas_app.py Closes the canvas in a finally block for the SSE streaming route.
agent/canvas.py Introduces Graph.close() to clean up MCP tool-call sessions referenced by Agent tools.
Comments suppressed due to low confidence (4)

api/db/services/canvas_service.py:247

  • canvas.close() is a synchronous, potentially blocking cleanup (it calls MCPToolCallSession.close_sync() with timeouts). Calling it directly inside this async generator finally can block the event loop for up to several seconds per MCP session, impacting concurrent requests. Consider running the close in the thread pool (e.g., await thread_pool_exec(canvas.close)) or providing an async close path so cleanup doesn’t block the loop.
    finally:
        canvas.close()

api/apps/canvas_app.py:230

  • canvas.close() performs synchronous cleanup (including waiting on MCP session shutdown). Calling it directly in this async generator finally can block the Quart event loop during client disconnects/errors. Prefer executing the close via await thread_pool_exec(canvas.close) (already imported in this module) or implement an async close method.
        finally:
            canvas.close()

agent/canvas.py:152

  • Graph.close() currently only closes MCPToolCallSessions but does not shut down the per-canvas ThreadPoolExecutor created in __init__ (self._thread_pool). If callers start using canvas.close() for lifecycle management, this leaves worker threads alive and undermines the goal of preventing resource leaks. Consider calling self._thread_pool.shutdown(...) (and clearing references if appropriate) as part of close().
    def close(self):
        from common.mcp_tool_call_conn import MCPToolCallSession
        seen = set()
        for cpn in self.components.values():
            obj = cpn.get("obj")
            if obj and hasattr(obj, "tools"):
                for tool in obj.tools.values():
                    if isinstance(tool, MCPToolCallSession) and id(tool) not in seen:
                        seen.add(id(tool))
                        try:
                            tool.close_sync(timeout=3)
                        except Exception:
                            pass

agent/canvas.py:152

  • Graph.close() swallows all exceptions (except Exception: pass) when closing MCP sessions. If a session fails to close, this can silently reintroduce the original leak and makes diagnosing shutdown issues difficult. Consider at least logging the exception (or relying on close_sync’s internal logging without an outer blanket try/except).
                        try:
                            tool.close_sync(timeout=3)
                        except Exception:
                            pass

You can also share your feedback on Copilot code review. Take the survey.

@Br1an67

Br1an67 commented Mar 8, 2026

Copy link
Copy Markdown
Contributor Author

Hi — just a gentle bump on this. Happy to make any changes if needed!

@yingfeng yingfeng added the ci Continue Integration label Mar 9, 2026
@yingfeng
yingfeng marked this pull request as draft March 9, 2026 03:48
@yingfeng
yingfeng marked this pull request as ready for review March 9, 2026 03:48
@codecov

codecov Bot commented Mar 9, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (45fc7fe) to head (0856923).
⚠️ Report is 29 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #13295      +/-   ##
==========================================
- 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.

Br1an67 added 2 commits March 9, 2026 04:51
…leaks

Add Graph.close() method that finds and closes all MCPToolCallSessions
held by Agent components. Call it in finally blocks after canvas.run()
in canvas_service.py and canvas_app.py. Also move session cleanup to
finally blocks in test_tool endpoint and get_mcp_tools to ensure
sessions are closed even on exceptions.
@yuzhichang

yuzhichang commented Jun 28, 2026 •

Copy link
Copy Markdown
Member

This PR currently has merge conflicts with main and cannot be auto-synced.

Please run locally:

git fetch origin main
git rebase origin/main
# or
git merge origin/main

After resolving the conflicts, push to the current head branch and CI will re-run the review checks.

Triggered by reviewer yuzhichang (request-for-action)

# Conflicts:
#	api/apps/canvas_app.py
#	api/apps/restful_apis/mcp_api.py
#	api/db/services/canvas_service.py
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels Jun 30, 2026
@coderabbitai

coderabbitai Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 7ea58be4-ee84-45a2-bcd2-4cfedec30415

📥 Commits

Reviewing files that changed from the base of the PR and between 5bc5ae5 and 0856923.

📒 Files selected for processing (1)
  • agent/canvas.py

📝 Walkthrough

Walkthrough

Adds Graph.close() to synchronously close deduplicated MCP sessions, ensures canvas and MCP cleanup runs in finally, and introduces a new Quart blueprint with canvas management, streaming, session, rerun, debug, and database connectivity endpoints.

Canvas API and MCP Cleanup

Layer / File(s) Summary
MCP and canvas cleanup
agent/canvas.py, api/db/services/canvas_service.py, api/utils/api_utils.py
Graph.close() closes unique MCPToolCallSession tools; canvas completion and MCP tool lookup now close resources in finally.
Canvas management endpoints
api/apps/canvas_app.py
Imports plus handlers for templates, delete, save/create, get, getsse, list, setting, versions, upload, input form, prompts, and download.
Completion, rerun, reset, trace, and debug
api/apps/canvas_app.py
Canvas SSE completion, agent completion with trace capture, rerun orchestration, cancel, reset, trace lookup, and debug execution handlers.
Sessions and database connectivity
api/apps/canvas_app.py
Conversation session list/create/get/delete handlers and multi-backend database connection testing.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

🐇 Hop hop, the sessions now unwind,
No leaked connections left behind.
The canvas streams, then bows and rests,
Clean paws, fresh routes, and tidy tests.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The new canvas_app route module adds many endpoints unrelated to the MCP leak fix and appears broader than the linked issue scope. Limit the PR to leak-related cleanup and canvas.close calls, or split the unrelated canvas_app endpoint additions into a separate change if needed.
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 (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: closing MCP sessions after canvas execution to prevent leaks.
Description check ✅ Passed The description covers the problem, solution, and change type, which is enough for the repository template.
Linked Issues check ✅ Passed The changes address #12962 by ensuring MCP sessions are closed in Graph and finally blocks after canvas execution.

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.

@yuzhichang
yuzhichang force-pushed the fix/issue-12962-mcp-conn-release branch from f3caa7d to 06211dd Compare June 30, 2026 08:22

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

🧹 Nitpick comments (1)
api/apps/canvas_app.py (1)

160-238: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add structured logging for the new operational flows.

Completion streaming, DB connectivity checks, and session mutations should log key lifecycle events and failures consistently. As per coding guidelines, **/*.py: Add logging for new flows.

Also applies to: 421-523, 653-700

🤖 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 `@api/apps/canvas_app.py` around lines 160 - 238, The new completion streaming
flow in run() lacks consistent operational logging for key lifecycle events and
failures. Add structured logs around CanvasReplicaService.load_for_run, the
Canvas creation and canvas.run streaming loop, the commit_after_run result, and
the exception/cancel/close path so successes and failures are traceable. Use the
existing run, sse, CanvasReplicaService, and Canvas methods as anchors, and
follow the same logging style used elsewhere in the module for DB/session
mutation flows.

Source: Coding guidelines

🤖 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 `@agent/canvas.py`:
- Around line 155-158: The cleanup path in the `close_sync()` call is swallowing
exceptions silently, so update the new cleanup flow in `Canvas` to log any
failure instead of using a bare `except Exception: pass`. Use the existing
cleanup logic around `tool.close_sync(timeout=3)` to catch the exception, emit
an error-level log with the exception details, and keep the rest of the shutdown
path intact so MCP connection leaks can be diagnosed.
- Around line 146-158: The teardown in Graph.close currently closes
MCPToolCallSession instances but leaves the graph-owned ThreadPoolExecutor
alive, so add executor shutdown to the same cleanup path after the tool/session
loop. Locate the Graph.close method and ensure the per-graph executor created by
the Graph class is explicitly shut down during close, with any necessary guard
so repeated close calls remain safe.

In `@api/apps/canvas_app.py`:
- Line 53: The route decorators in canvas_app are using manager before it
exists, causing import-time failures when the module is loaded. Define or import
the shared manager object in this module before any `@manager.route` decorators,
and make sure the existing route functions in canvas_app register against that
same manager instance.
- Around line 526-546: The canvas version endpoints currently return
history/version data without an ownership check; update getlistversion and
getversion in canvas_app to verify current_user has access to the underlying
canvas before returning anything. Use the existing UserCanvasVersionService
lookups in these handlers to resolve the canvas/version owner, compare it
against current_user, and return an error response when the user is not
authorized.
- Around line 421-523: The test_db_connect endpoint is allowing unrestricted
user-controlled outbound connections, which can be abused as a network probe. In
test_db_connect, add an allowlist and/or privileged-role check before creating
any database client (MySQLDatabase, PostgresqlDatabase, pyodbc.connect,
ibm_db.connect, trino.dbapi.connect) so only approved hosts/ports can be tested.
Also set driver-level connection/login timeouts for each branch to prevent
hanging workers, and keep the existing success/failure flow unchanged.
- Around line 603-615: The trace endpoint is currently public and can return
sensitive execution logs without any authorization. Update the trace() handler
in canvas_app.py to require authentication and verify the caller has access to
the requested canvas before reading Redis, using the existing request/context
auth helpers and canvas permission checks already used by other endpoints. Make
sure the /trace route only serves data after validating canvas_id and message_id
against the authenticated user’s permitted canvas, and return a
forbidden/unauthorized response when access is not allowed.
- Around line 688-700: The session read/delete handlers in canvas_app.py only
check canvas ownership and then operate on API4ConversationService by
session_id, which leaves an IDOR gap. In both the session fetch flow and
del_session, use the existing canvas_id and session_id to verify the loaded
conversation belongs to the requested canvas before calling conv.to_dict() or
API4ConversationService.delete_by_id. Update the relevant logic around
API4ConversationService.get_by_id, del_session, and UserCanvasService.accessible
so the session is scoped to the canvas and rejected if it does not match.
- Around line 337-341: The Canvas usage in the affected routes leaves MCP tool
sessions open because `canvas.close()` is never called after `Canvas(...)` and
`canvas.reset()`. Update each route that creates a `Canvas` in
`api/apps/canvas_app.py` to wrap the existing Canvas work in a `try/finally` and
call `canvas.close()` in the `finally` block, matching the teardown path used by
`Graph.close()` in `agent/canvas.py`. Apply this to every `Canvas` instance in
the listed handlers so the session is always released even on errors.
- Around line 445-449: The database branches currently leave cursor/db handles
open when execution exits early or throws, especially in the MSSQL, DB2, and
Trino paths. Update the connection logic around the `req["db_type"]` branches to
use `try/finally` so every `cursor` is always closed and every `db` connection
is closed after use, even on exceptions. Make sure the MSSQL path that uses
`pyodbc.connect` closes both `cursor` and `db`, and apply the same cleanup
pattern consistently to the DB2 and Trino blocks.
- Around line 346-359: The upload endpoint currently allows file writes using
cvs["user_id"] without any authentication or canvas ownership/access validation.
Add the same login and canvas access guard used by other canvas routes to the
upload handler in upload(canvas_id), ensuring the caller is authenticated and
authorized for that canvas before calling UserCanvasService.get_by_canvas_id or
FileService.upload_info. Keep the existing upload flow intact, but block
unauthorized requests early with an appropriate error result.
- Around line 190-196: The DataFlow branch in canvas_app’s request handling
indexes files[0] without verifying that files is non-empty, which can crash a
valid completion request. Add an explicit guard before calling thread_pool_exec
in the canvas_category == CanvasCategory.DataFlow path to return a
get_data_error_result when files is empty, and keep the existing Pipeline,
queue_dataflow, and get_json_result flow unchanged for the valid case.
- Around line 138-146: The getsse endpoint currently assumes
request.headers.get('Authorization') always exists, so missing or malformed auth
headers can crash before the intended error response. Update getsse to validate
the Authorization header before calling split(), and return
get_data_error_result with the existing auth error message when the header is
missing or not in the expected two-part format. Keep the fix localized to getsse
and preserve the APIToken.query(beta=token) flow for valid tokens.
- Around line 718-723: The download endpoint currently trusts caller-supplied
query parameters, so update the download() route to authorize access before
calling FileService.get_blob. Use the authenticated user/context instead of the
request.args values for created_by, and validate that the requested blob id
belongs to that user or is otherwise permitted. Keep the fix localized around
download() and FileService.get_blob so unauthorized blob fetch attempts are
blocked.
- Around line 653-677: The set_session route currently loads the canvas with
UserCanvasService.get_by_id before checking whether the current user can access
it, so add an authorization check using UserCanvasService.accessible(canvas_id,
tenant_id) before any canvas data is read or used. Update the logic in
set_session to reject unauthorized requests early, then proceed with the
existing Canvas and API4ConversationService flow only after access is confirmed;
keep the Canvas(..., canvas_id=cvs.id) call consistent with the intended canvas
identifier usage.

In `@api/db/services/canvas_service.py`:
- Around line 360-371: `completion()` currently calls `canvas.close()` directly
in the async `finally` block, which can block the event loop while MCP sessions
shut down. Update the cleanup in `canvas_service.py` so the `finally` path
offloads `canvas.close()` to a background thread or equivalent non-blocking
executor, preserving the existing `canvas.run` streaming flow and `session_id`
handling while avoiding synchronous shutdown work on the event loop.

In `@api/utils/api_utils.py`:
- Around line 664-666: The cleanup in get_mcp_tools() is unguarded, so an
exception from close_multiple_mcp_toolcall_sessions() can override the intended
(dict, str) return path. Wrap the finally-time
close_multiple_mcp_toolcall_sessions(tool_call_sessions) call in its own
try/except inside get_mcp_tools(), and log any failure with the module’s logger
instead of letting teardown escape. Keep the return contract intact and preserve
the existing tool_call_sessions cleanup behavior.

---

Nitpick comments:
In `@api/apps/canvas_app.py`:
- Around line 160-238: The new completion streaming flow in run() lacks
consistent operational logging for key lifecycle events and failures. Add
structured logs around CanvasReplicaService.load_for_run, the Canvas creation
and canvas.run streaming loop, the commit_after_run result, and the
exception/cancel/close path so successes and failures are traceable. Use the
existing run, sse, CanvasReplicaService, and Canvas methods as anchors, and
follow the same logging style used elsewhere in the module for DB/session
mutation flows.
🪄 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: 482965bc-85f6-4b1a-b28e-3f7d0beba830

📥 Commits

Reviewing files that changed from the base of the PR and between dc8b6d7 and 06211dd.

📒 Files selected for processing (4)
  • agent/canvas.py
  • api/apps/canvas_app.py
  • api/db/services/canvas_service.py
  • api/utils/api_utils.py

Comment thread agent/canvas.py
Comment on lines +146 to +158
def close(self):
from common.mcp_tool_call_conn import MCPToolCallSession
seen = set()
for cpn in self.components.values():
obj = cpn.get("obj")
if obj and hasattr(obj, "tools"):
for tool in obj.tools.values():
if isinstance(tool, MCPToolCallSession) and id(tool) not in seen:
seen.add(id(tool))
try:
tool.close_sync(timeout=3)
except Exception:
pass

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Graph.close() still leaks the graph-owned thread pool.

Line 95 allocates a per-graph ThreadPoolExecutor, but this new teardown path never shuts it down. That means short-lived canvases can still accumulate worker threads even after MCP sessions are closed.

Suggested fix
 def close(self):
     from common.mcp_tool_call_conn import MCPToolCallSession
     seen = set()
     for cpn in self.components.values():
         obj = cpn.get("obj")
         if obj and hasattr(obj, "tools"):
             for tool in obj.tools.values():
                 if isinstance(tool, MCPToolCallSession) and id(tool) not in seen:
                     seen.add(id(tool))
                     try:
                         tool.close_sync(timeout=3)
                     except Exception:
-                        pass
+                        logging.exception("Failed to close MCP tool session")
+    self._thread_pool.shutdown(wait=False, cancel_futures=True)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def close(self):
from common.mcp_tool_call_conn import MCPToolCallSession
seen = set()
for cpn in self.components.values():
obj = cpn.get("obj")
if obj and hasattr(obj, "tools"):
for tool in obj.tools.values():
if isinstance(tool, MCPToolCallSession) and id(tool) not in seen:
seen.add(id(tool))
try:
tool.close_sync(timeout=3)
except Exception:
pass
def close(self):
from common.mcp_tool_call_conn import MCPToolCallSession
seen = set()
for cpn in self.components.values():
obj = cpn.get("obj")
if obj and hasattr(obj, "tools"):
for tool in obj.tools.values():
if isinstance(tool, MCPToolCallSession) and id(tool) not in seen:
seen.add(id(tool))
try:
tool.close_sync(timeout=3)
except Exception:
logging.exception("Failed to close MCP tool session")
self._thread_pool.shutdown(wait=False, cancel_futures=True)
🤖 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 `@agent/canvas.py` around lines 146 - 158, The teardown in Graph.close
currently closes MCPToolCallSession instances but leaves the graph-owned
ThreadPoolExecutor alive, so add executor shutdown to the same cleanup path
after the tool/session loop. Locate the Graph.close method and ensure the
per-graph executor created by the Graph class is explicitly shut down during
close, with any necessary guard so repeated close calls remain safe.

Comment thread agent/canvas.py
Comment on lines +155 to +158
try:
tool.close_sync(timeout=3)
except Exception:
pass

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Don't swallow cleanup failures silently.

If close_sync() fails here, the MCP connection leak remains but there is no signal to debug it. At minimum, log the exception in this new cleanup flow. As per coding guidelines, **/*.py: Add logging for new flows.

🤖 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 `@agent/canvas.py` around lines 155 - 158, The cleanup path in the
`close_sync()` call is swallowing exceptions silently, so update the new cleanup
flow in `Canvas` to log any failure instead of using a bare `except Exception:
pass`. Use the existing cleanup logic around `tool.close_sync(timeout=3)` to
catch the exception, emit an error-level log with the exception details, and
keep the rest of the shutdown path intact so MCP connection leaks can be
diagnosed.

Source: Coding guidelines

Comment thread api/apps/canvas_app.py
from api.db.services.canvas_service import completion as agent_completion


@manager.route('/templates', methods=['GET']) # noqa: F821

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Define or import manager before registering routes.

manager is referenced by decorators throughout this new module but is never defined in the file, so importing api/apps/canvas_app.py will fail at route registration 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 `@api/apps/canvas_app.py` at line 53, The route decorators in canvas_app are
using manager before it exists, causing import-time failures when the module is
loaded. Define or import the shared manager object in this module before any
`@manager.route` decorators, and make sure the existing route functions in
canvas_app register against that same manager instance.

Comment thread api/apps/canvas_app.py
Comment on lines +138 to +146
@manager.route('/getsse/<canvas_id>', methods=['GET']) # type: ignore # noqa: F821
def getsse(canvas_id):
token = request.headers.get('Authorization').split()
if len(token) != 2:
return get_data_error_result(message='Authorization is not valid!')
token = token[1]
objs = APIToken.query(beta=token)
if not objs:
return get_data_error_result(message='Authentication error: API key is invalid!"')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Handle missing or malformed Authorization headers.

request.headers.get('Authorization') can be None; unauthenticated requests currently crash before returning the intended auth error.

Proposed fix
-    token = request.headers.get('Authorization').split()
-    if len(token) != 2:
+    auth_header = request.headers.get("Authorization", "")
+    token = auth_header.split()
+    if len(token) != 2:
         return get_data_error_result(message='Authorization is not valid!')
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@manager.route('/getsse/<canvas_id>', methods=['GET']) # type: ignore # noqa: F821
def getsse(canvas_id):
token = request.headers.get('Authorization').split()
if len(token) != 2:
return get_data_error_result(message='Authorization is not valid!')
token = token[1]
objs = APIToken.query(beta=token)
if not objs:
return get_data_error_result(message='Authentication error: API key is invalid!"')
`@manager.route`('/getsse/<canvas_id>', methods=['GET']) # type: ignore # noqa: F821
def getsse(canvas_id):
auth_header = request.headers.get("Authorization", "")
token = auth_header.split()
if len(token) != 2:
return get_data_error_result(message='Authorization is not valid!')
token = token[1]
objs = APIToken.query(beta=token)
if not objs:
return get_data_error_result(message='Authentication error: API key is invalid!"')
🤖 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 `@api/apps/canvas_app.py` around lines 138 - 146, The getsse endpoint currently
assumes request.headers.get('Authorization') always exists, so missing or
malformed auth headers can crash before the intended error response. Update
getsse to validate the Authorization header before calling split(), and return
get_data_error_result with the existing auth error message when the header is
missing or not in the expected two-part format. Keep the fix localized to getsse
and preserve the APIToken.query(beta=token) flow for valid tokens.

Comment thread api/apps/canvas_app.py
Comment on lines +190 to +196
if canvas_category == CanvasCategory.DataFlow:
task_id = get_uuid()
Pipeline(dsl_str, tenant_id=tenant_id, doc_id=CANVAS_DEBUG_DOC_ID, task_id=task_id, flow_id=req["id"])
ok, error_message = await thread_pool_exec(queue_dataflow, user_id, req["id"], task_id, CANVAS_DEBUG_DOC_ID, files[0], 0)
if not ok:
return get_data_error_result(message=error_message)
return get_json_result(data={"message_id": task_id})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Validate files before indexing DataFlow input.

files defaults to an empty list, but Line 193 unconditionally uses files[0], so a valid /completion request for a DataFlow canvas can crash.

Proposed fix
     if canvas_category == CanvasCategory.DataFlow:
+        if not files:
+            return get_data_error_result(message="files is required for DataFlow completion.")
         task_id = get_uuid()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if canvas_category == CanvasCategory.DataFlow:
task_id = get_uuid()
Pipeline(dsl_str, tenant_id=tenant_id, doc_id=CANVAS_DEBUG_DOC_ID, task_id=task_id, flow_id=req["id"])
ok, error_message = await thread_pool_exec(queue_dataflow, user_id, req["id"], task_id, CANVAS_DEBUG_DOC_ID, files[0], 0)
if not ok:
return get_data_error_result(message=error_message)
return get_json_result(data={"message_id": task_id})
if canvas_category == CanvasCategory.DataFlow:
if not files:
return get_data_error_result(message="files is required for DataFlow completion.")
task_id = get_uuid()
Pipeline(dsl_str, tenant_id=tenant_id, doc_id=CANVAS_DEBUG_DOC_ID, task_id=task_id, flow_id=req["id"])
ok, error_message = await thread_pool_exec(queue_dataflow, user_id, req["id"], task_id, CANVAS_DEBUG_DOC_ID, files[0], 0)
if not ok:
return get_data_error_result(message=error_message)
return get_json_result(data={"message_id": task_id})
🤖 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 `@api/apps/canvas_app.py` around lines 190 - 196, The DataFlow branch in
canvas_app’s request handling indexes files[0] without verifying that files is
non-empty, which can crash a valid completion request. Add an explicit guard
before calling thread_pool_exec in the canvas_category ==
CanvasCategory.DataFlow path to return a get_data_error_result when files is
empty, and keep the existing Pipeline, queue_dataflow, and get_json_result flow
unchanged for the valid case.

Comment thread api/apps/canvas_app.py
Comment on lines +653 to +677
@manager.route('/<canvas_id>/sessions', methods=['PUT']) # noqa: F821
@login_required
async def set_session(canvas_id):
req = await get_request_json()
tenant_id = current_user.id
e, cvs = UserCanvasService.get_by_id(canvas_id)
assert e, "Agent not found."
if not isinstance(cvs.dsl, str):
cvs.dsl = json.dumps(cvs.dsl, ensure_ascii=False)
session_id=get_uuid()
canvas = Canvas(cvs.dsl, tenant_id, canvas_id, canvas_id=cvs.id)
canvas.reset()
conv = {
"id": session_id,
"name": req.get("name", ""),
"dialog_id": cvs.id,
"user_id": tenant_id,
"exp_user_id": tenant_id,
"message": [],
"source": "agent",
"dsl": cvs.dsl,
"reference": []
}
API4ConversationService.save(**conv)
return get_json_result(data=conv)

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n== canvas_app slice ==\n'
sed -n '620,710p' api/apps/canvas_app.py

printf '\n== accessible usages ==\n'
rg -n "UserCanvasService\.accessible|accessible\(canvas_id" api -g '*.py'

printf '\n== Canvas constructor usages ==\n'
rg -n "Canvas\(" api -g '*.py'

printf '\n== Canvas class definition ==\n'
rg -n "class Canvas|def __init__" api -g '*.py'

Repository: infiniflow/ragflow

Length of output: 11002


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n== canvas_service slice around Canvas ==\n'
sed -n '1,220p' api/db/services/canvas_service.py

printf '\n== constructor signature and call sites around relevant lines ==\n'
sed -n '300,360p' api/db/services/canvas_service.py
sed -n '180,220p' api/apps/canvas_app.py
sed -n '430,470p' api/apps/restful_apis/agent_api.py

Repository: infiniflow/ragflow

Length of output: 14270


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n== Canvas definition ==\n'
fd -a 'canvas.py' agent api | sed -n '1,20p'
rg -n "^class Canvas\b|^    def __init__\(" agent api -g 'canvas.py' -g '*.py'

printf '\n== get_by_id implementations ==\n'
rg -n "def get_by_id\b" api/db/services api -g '*.py'

printf '\n== get_by_id on UserCanvasService/CommonService ==\n'
sed -n '1,240p' api/db/services/common_service.py
sed -n '220,320p' api/db/services/canvas_service.py

Repository: infiniflow/ragflow

Length of output: 19850


Authorize this session route before loading the canvas. set_session skips UserCanvasService.accessible(canvas_id, tenant_id), so any logged-in user who knows a canvas id can read its DSL and create a session for it. The Canvas(..., canvas_id=cvs.id) call is consistent with other call sites; the third positional argument is task_id.

🧰 Tools
🪛 ast-grep (0.44.0)

[info] 660-660: use jsonify instead of json.dumps for JSON output
Context: json.dumps(cvs.dsl, ensure_ascii=False)
Note: [CWE-116] Improper Encoding or Escaping of Output.

(use-jsonify)

🤖 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 `@api/apps/canvas_app.py` around lines 653 - 677, The set_session route
currently loads the canvas with UserCanvasService.get_by_id before checking
whether the current user can access it, so add an authorization check using
UserCanvasService.accessible(canvas_id, tenant_id) before any canvas data is
read or used. Update the logic in set_session to reject unauthorized requests
early, then proceed with the existing Canvas and API4ConversationService flow
only after access is confirmed; keep the Canvas(..., canvas_id=cvs.id) call
consistent with the intended canvas identifier usage.

Comment thread api/apps/canvas_app.py
Comment on lines +688 to +700
_, conv = API4ConversationService.get_by_id(session_id)
return get_json_result(data=conv.to_dict())


@manager.route('/<canvas_id>/sessions/<session_id>', methods=['DELETE']) # noqa: F821
@login_required
def del_session(canvas_id, session_id):
tenant_id = current_user.id
if not UserCanvasService.accessible(canvas_id, tenant_id):
return get_json_result(
data=False, message='Only owner of canvas authorized for this operation.',
code=RetCode.OPERATING_ERROR)
return get_json_result(data=API4ConversationService.delete_by_id(session_id))

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.

🔒 Security & Privacy | 🔴 Critical | ⚡ Quick win

Scope session reads/deletes to the requested canvas.

After checking canvas access, also verify the fetched session belongs to canvas_id before returning or deleting it; otherwise session_id is an IDOR.

🤖 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 `@api/apps/canvas_app.py` around lines 688 - 700, The session read/delete
handlers in canvas_app.py only check canvas ownership and then operate on
API4ConversationService by session_id, which leaves an IDOR gap. In both the
session fetch flow and del_session, use the existing canvas_id and session_id to
verify the loaded conversation belongs to the requested canvas before calling
conv.to_dict() or API4ConversationService.delete_by_id. Update the relevant
logic around API4ConversationService.get_by_id, del_session, and
UserCanvasService.accessible so the session is scoped to the canvas and rejected
if it does not match.

Comment thread api/apps/canvas_app.py
Comment on lines +718 to +723
@manager.route('/download', methods=['GET']) # noqa: F821
async def download():
id = request.args.get("id")
created_by = request.args.get("created_by")
blob = FileService.get_blob(created_by, id)
return await make_response(blob)

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.

🔒 Security & Privacy | 🔴 Critical | ⚡ Quick win

Authorize downloads instead of trusting query parameters.

/download is unauthenticated and trusts caller-supplied created_by, allowing arbitrary blob fetch attempts by id.

🤖 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 `@api/apps/canvas_app.py` around lines 718 - 723, The download endpoint
currently trusts caller-supplied query parameters, so update the download()
route to authorize access before calling FileService.get_blob. Use the
authenticated user/context instead of the request.args values for created_by,
and validate that the requested blob id belongs to that user or is otherwise
permitted. Keep the fix localized around download() and FileService.get_blob so
unauthorized blob fetch attempts are blocked.

Comment on lines +360 to +371
try:
async for ans in canvas.run(**run_kwargs):
ans["session_id"] = session_id
if ans["event"] == "message":
txt += ans["data"]["content"]
if ans["data"].get("start_to_think", False):
txt += "<think>"
elif ans["data"].get("end_to_think", False):
txt += "</think>"
yield "data:" + json.dumps(ans, ensure_ascii=False) + "\n\n"
finally:
canvas.close()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Offload canvas.close() from the event loop.

completion() is async, but canvas.close() now runs synchronously and ultimately calls close_sync(timeout=3) per MCP session. On canvases with multiple sessions, this finally block can block the event loop for seconds and stall unrelated requests.

Suggested fix
     try:
         async for ans in canvas.run(**run_kwargs):
             ans["session_id"] = session_id
             if ans["event"] == "message":
                 txt += ans["data"]["content"]
                 if ans["data"].get("start_to_think", False):
                     txt += "<think>"
                 elif ans["data"].get("end_to_think", False):
                     txt += "</think>"
             yield "data:" + json.dumps(ans, ensure_ascii=False) + "\n\n"
     finally:
-        canvas.close()
+        await thread_pool_exec(canvas.close)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try:
async for ans in canvas.run(**run_kwargs):
ans["session_id"] = session_id
if ans["event"] == "message":
txt += ans["data"]["content"]
if ans["data"].get("start_to_think", False):
txt += "<think>"
elif ans["data"].get("end_to_think", False):
txt += "</think>"
yield "data:" + json.dumps(ans, ensure_ascii=False) + "\n\n"
finally:
canvas.close()
try:
async for ans in canvas.run(**run_kwargs):
ans["session_id"] = session_id
if ans["event"] == "message":
txt += ans["data"]["content"]
if ans["data"].get("start_to_think", False):
txt += "<think>"
elif ans["data"].get("end_to_think", False):
txt += "</think>"
yield "data:" + json.dumps(ans, ensure_ascii=False) + "\n\n"
finally:
await thread_pool_exec(canvas.close)
🧰 Tools
🪛 ast-grep (0.44.0)

[info] 368-368: use jsonify instead of json.dumps for JSON output
Context: json.dumps(ans, ensure_ascii=False)
Note: [CWE-116] Improper Encoding or Escaping of Output.

(use-jsonify)

🤖 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 `@api/db/services/canvas_service.py` around lines 360 - 371, `completion()`
currently calls `canvas.close()` directly in the async `finally` block, which
can block the event loop while MCP sessions shut down. Update the cleanup in
`canvas_service.py` so the `finally` path offloads `canvas.close()` to a
background thread or equivalent non-blocking executor, preserving the existing
`canvas.run` streaming flow and `session_id` handling while avoiding synchronous
shutdown work on the event loop.

Comment thread api/utils/api_utils.py
Comment on lines +664 to +666
finally:
# PERF: blocking call to close sessions — consider moving to background thread or task queue
close_multiple_mcp_toolcall_sessions(tool_call_sessions)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Guard cleanup inside finally or it will break the return contract.

If close_multiple_mcp_toolcall_sessions() raises here, it overrides both return paths above and get_mcp_tools() no longer returns the declared (dict, str) tuple. Wrap the close in its own try/except and log failures instead of letting teardown escape. As per coding guidelines, **/*.py: Add logging for new flows.

Suggested fix
     except Exception as e:
         return {}, str(e)
     finally:
-        # PERF: blocking call to close sessions — consider moving to background thread or task queue
-        close_multiple_mcp_toolcall_sessions(tool_call_sessions)
+        try:
+            close_multiple_mcp_toolcall_sessions(tool_call_sessions)
+        except Exception:
+            logging.exception("Failed to close MCP tool call sessions")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
finally:
# PERF: blocking call to close sessions — consider moving to background thread or task queue
close_multiple_mcp_toolcall_sessions(tool_call_sessions)
finally:
try:
close_multiple_mcp_toolcall_sessions(tool_call_sessions)
except Exception:
logging.exception("Failed to close MCP tool call sessions")
🤖 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 `@api/utils/api_utils.py` around lines 664 - 666, The cleanup in
get_mcp_tools() is unguarded, so an exception from
close_multiple_mcp_toolcall_sessions() can override the intended (dict, str)
return path. Wrap the finally-time
close_multiple_mcp_toolcall_sessions(tool_call_sessions) call in its own
try/except inside get_mcp_tools(), and log any failure with the module’s logger
instead of letting teardown escape. Keep the return contract intact and preserve
the existing tool_call_sessions cleanup behavior.

Source: Coding guidelines

@yuzhichang
yuzhichang force-pushed the fix/issue-12962-mcp-conn-release branch from 2540f8a to 06211dd Compare June 30, 2026 08:45

@yuzhichang yuzhichang left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Jul 1, 2026
@yuzhichang
yuzhichang merged commit 27c9a09 into infiniflow:main Jul 2, 2026
4 of 6 checks passed
JinHai-CN pushed a commit that referenced this pull request Jul 2, 2026
### Summary

Port the following PRs to GO in this PR

#16420
#13295
wangq8 added a commit that referenced this pull request Jul 3, 2026
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 3, 2026
…leaks (infiniflow#13295)

### What problem does this PR solve?

Closes infiniflow#12962

MCPToolCallSessions created during agent execution (in `Agent.__init__`)
are never explicitly closed. Each session starts its own event loop
thread and opens an SSE/HTTP connection to the MCP server. When the
canvas goes out of scope, these threads and connections remain alive
indefinitely, accumulating over time and causing resource exhaustion
after prolonged use.

### Solution

1. Add a `Graph.close()` method that iterates all components, finds
MCPToolCallSessions held by Agent tools, and calls `close_sync()` on
each to properly shut down the event loop, thread, and connection.
2. Call `canvas.close()` in `finally` blocks after `canvas.run()`
completes in `canvas_service.py` and `canvas_app.py`.
3. Move MCP session cleanup to `finally` blocks in `test_tool` endpoint
(`mcp_server_app.py`) and `get_mcp_tools` (`api_utils.py`) to ensure
sessions are closed even on exceptions.

### Type of change

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

---------

Co-authored-by: conflict-resolver <conflict-resolver@local>
Co-authored-by: Zhichang Yu <[email protected]>
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 3, 2026
### Summary

Port the following PRs to GO in this PR

infiniflow#16420
infiniflow#13295
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 3, 2026
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 6, 2026
…leaks (infiniflow#13295)

### What problem does this PR solve?

Closes infiniflow#12962

MCPToolCallSessions created during agent execution (in `Agent.__init__`)
are never explicitly closed. Each session starts its own event loop
thread and opens an SSE/HTTP connection to the MCP server. When the
canvas goes out of scope, these threads and connections remain alive
indefinitely, accumulating over time and causing resource exhaustion
after prolonged use.

### Solution

1. Add a `Graph.close()` method that iterates all components, finds
MCPToolCallSessions held by Agent tools, and calls `close_sync()` on
each to properly shut down the event loop, thread, and connection.
2. Call `canvas.close()` in `finally` blocks after `canvas.run()`
completes in `canvas_service.py` and `canvas_app.py`.
3. Move MCP session cleanup to `finally` blocks in `test_tool` endpoint
(`mcp_server_app.py`) and `get_mcp_tools` (`api_utils.py`) to ensure
sessions are closed even on exceptions.

### Type of change

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

---------

Co-authored-by: conflict-resolver <conflict-resolver@local>
Co-authored-by: Zhichang Yu <[email protected]>
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 6, 2026
### Summary

Port the following PRs to GO in this PR

infiniflow#16420
infiniflow#13295
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration lgtm This PR has been approved by a maintainer size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: mcp connection not release

4 participants