← Back to Pull requests

refactor(api): read API tool providers through Session(db.engine) in ToolManager #47419

Open
Mattenhaim opened this pull request with 419 lines diff across 10 files
View on GitHub
Mattenhaim Mattenhaim commented on Nov 28, 2026 18:21 UTC
Author

Summary

Part of #45584 (refactor: use sqlalchemy engine instead of the global db.session).

ToolManager's API tool provider read path still went through the global db.session:

  • get_api_provider_controller queried ApiToolProvider via db.session.scalar(...) and handed db.session() to ApiToolProviderController.from_db.

  • user_get_api_provider did the same for the tenant/name lookup and controller construction.

  • list_providers_from_api opened an explicit Session(db.engine) for its own queries but still passed a fresh db.session() into api_provider_to_user_provider.
  • This PR routes all three through explicitly owned sessions:

  • Both classmethods now open a short-lived with Session(db.engine) as session:, run the tenant-scoped query and the controller construction inside it — the same pattern already used by get_mcp_provider_controller in this file. from_db receives that session and derives its lazy-load session factory from it (#46983).

  • list_providers_from_api passes its already-open session to api_provider_to_user_provider instead of a new global one.

  • core/tools/tool_manager.py no longer references db.session at all.
  • Behavior is unchanged: same tenant filtering, credential parsing/masking, icon fallback, labels and ToolProviderNotFoundError / ValueError paths.

    Verification

  • pytest tests/unit_tests/core/tools/ — 671 passed (including the existing real-SQLite tests for get_api_provider_controller, user_get_api_provider and list_providers_from_api in test_tool_manager.py, which cover this refactor without modification)

  • pytest tests/unit_tests/services/data_migration/test_export_service.py — passed (call-site coverage)

  • ruff check and ruff format --check pass on the touched file
  • Checklist

  • This change requires a documentation update

  • I understand that this PR may be closed in case there was no previous discussion or issues.

  • I've verified the change; existing tests already cover the refactored paths, so no test changes were needed.

  • I've updated the documentation accordingly.

  • I ran make lint && make type-check (backend) — ran ruff check / ruff format --check on the touched file; full make type-check requires the heavyweight backend env.
  • 🤖 Prepared with AI assistance (Kimi), reviewed and tested locally by the author.

    Diff: 419 lines (+331 / -88) across 10 files Reviewer: asukaminato0721 Review duration: 4560m
    All Vouch review confidence checks passed
    Residual risk 0.03 = Change Risk (0.52) × (1 − Review Confidence (0.93)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 419 lines diff across 10 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.96 · 5 substantive comment(s)
    0.96
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    93%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.361
    Real PR Conversation Timeline
    24 items
    github-actions[bot] github-actions[bot] commented on Nov 28, 2026 18:24 UTC
    Bot

    Pyrefly Type Coverage

    | Metric | Base | PR | Delta |
    | --- | ---: | ---: | ---: |
    | Type coverage | 90.82% | 90.82% | -0.00% |
    | Strict coverage | 90.47% | 90.47% | -0.00% |
    | Typed symbols | 106,067 | 106,080 | +13 |
    | Untyped symbols | 10,764 | 10,767 | +3 |
    | Modules | 4974 | 4974 | 0 |

    codecov[bot] codecov[bot] commented on Nov 28, 2026 18:28 UTC
    Bot

    Codecov Report


    :x: Patch coverage is 92.75362% with 5 lines in your changes missing coverage. Please review.
    :white_check_mark: Project coverage is 90.54%. Comparing base (5d50d5f) to head (b89154a).
    :warning: Report is 1 commits behind head on main.

    | Files with missing lines | Patch % | Lines |
    |---|---|---|
    | ...core/workflow/nodes/agent\_v2/dify\_tools\_builder.py | 0.00% | 2 Missing :warning: |
    | api/services/data\_migration/export\_service.py | 60.00% | 1 Missing and 1 partial :warning: |
    | api/services/tools/api\_tools\_manage\_service.py | 66.66% | 1 Missing :warning: |

    <details><summary>Additional details and impacted files</summary>

    @@           Coverage Diff           @@
    ##             main   #47419   +/-   ##
    =======================================
      Coverage   90.54%   90.54%           
    =======================================
      Files        6897     6897           
      Lines      432401   432477   +76     
      Branches    86698    86702    +4     
    =======================================
    + Hits       391507   391591   +84     
    + Misses      34069    34067    -2     
    + Partials     6825     6819    -6     
    

    | Flag | Coverage Δ | |
    |---|---|---|
    | api | 90.09% <92.75%> (+0.01%) | :arrow_up: |

    Flags with carried forward coverage won't be shown. Click here to find out more.
    </details>

    :umbrella: View full report in Codecov by Harness.
    :loudspeaker: Have feedback on the report? Share it here.
    <details><summary> :rocket: New features to boost your workflow: </summary>

  • :package: JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

  • </details>

    asukaminato0721 asukaminato0721 commented on Nov 29, 2026 01:22 UTC
    Contributor

    why do you change the permission? 100644 -> 100755

    asukaminato0721 asukaminato0721 commented on Nov 29, 2026 01:30 UTC
    Reviewer

    Please split this into smaller pull requests: it adds 1164 lines of non-test code, more than 300. Split it by feature: each pull request carries one functional change together with its tests, so each feature stands on its own and can be reviewed, merged and reverted independently. It will be reviewed once it is under 300. Size counts added non-test lines; tests, lock files and snapshots do not count.

    <sub>dify-codereview</sub>
    <!-- dify-review:head=f27bb149148e1a1f17caa90c03ae77de7de66f02;split=f27bb149148e1a1f17caa90c03ae77de7de66f02 -->

    Mattenhaim Mattenhaim commented on Nov 29, 2026 06:25 UTC
    Author

    Good catch — that was an accident in my upload tooling, not an intentional change. The script I use to push commits inferred the executable bit from the local filesystem, and on Windows every file reports as executable, so the blob got mode 100755.

    Fixed in 3a7d654: the file is back to 100644 and the diff no longer contains a mode change. Thanks for spotting it!

    github-actions[bot] github-actions[bot] commented on Nov 29, 2026 07:29 UTC
    Bot

    Pyrefly Diff


    <details>
    <summary>base → PR</summary>

    --- /tmp/pyrefly_base.txt	2026-11-30 13:47:15.172819117 +0000
    +++ /tmp/pyrefly_pr.txt	2026-11-30 13:46:55.487790864 +0000
    @@ -1727,7 +1727,7 @@
     ERROR Missing argument `endpoint_id` in function `controllers.console.workspace.endpoint.EndpointIdPayload.__init__` [missing-argument]
        --> tests/unit_tests/controllers/console/workspace/test_endpoint.py:561:46
     ERROR Argument `list[object]` is not assignable to parameter `parameters` with type `Iterable[Mapping[str, Any] | WorkflowToolParameterConfiguration]` in function `controllers.console.workspace.tool_providers.WorkflowToolCreatePayload.__init__` [bad-argument-type]
    -   --> tests/unit_tests/controllers/console/workspace/test_tool_providers.py:620:62
    +   --> tests/unit_tests/controllers/console/workspace/test_tool_providers.py:621:62
     ERROR Argument `Literal['file-id']` is not assignable to parameter `file_id` with type `UUID` in function `controllers.files.upload_file_delivery.ImagePreviewApi.get` [bad-argument-type]
        --> tests/unit_tests/controllers/files/test_upload_file_delivery.py:101:53
     ERROR Argument `Literal['file-id']` is not assignable to parameter `file_id` with type `UUID` in function `controllers.files.upload_file_delivery.ImagePreviewApi.get` [bad-argument-type]
    @@ -3329,12 +3329,18 @@
         --> tests/unit_tests/core/tools/test_tool_manager.py:1115:32
     ERROR Argument `Literal['']` is not assignable to parameter `typ` with type `Literal['api', 'builtin', 'mcp', 'workflow'] | None` in function `core.tools.tool_manager.ToolManager.list_providers_from_api` [bad-argument-type]
         --> tests/unit_tests/core/tools/test_tool_manager.py:1160:96
    +ERROR Argument `(**_kwargs: Unknown) -> tuple[ProviderConfigEncrypter, NoOpProviderCredentialCache]` is not assignable to parameter `encrypter_factory` with type `ToolProviderEncrypterFactory` in function `core.tools.tool_manager.ToolManager.user_get_api_provider` [bad-argument-type]
    +    --> tests/unit_tests/core/tools/test_tool_manager.py:1196:27
    +ERROR Argument `(**_kwargs: Unknown) -> tuple[ProviderConfigEncrypter, NoOpProviderCredentialCache]` is not assignable to parameter `encrypter_factory` with type `ToolProviderEncrypterFactory` in function `core.tools.tool_manager.ToolManager.user_get_api_provider` [bad-argument-type]
    +    --> tests/unit_tests/core/tools/test_tool_manager.py:1259:27
    +ERROR Argument `(**_kwargs: Unknown) -> tuple[ProviderConfigEncrypter, NoOpProviderCredentialCache]` is not assignable to parameter `encrypter_factory` with type `ToolProviderEncrypterFactory` in function `core.tools.tool_manager.ToolManager.user_get_api_provider` [bad-argument-type]
    +    --> tests/unit_tests/core/tools/test_tool_manager.py:1283:27
     ERROR `SimpleNamespace` is not assignable to attribute `entity` with type `ToolProviderEntityWithPlugin` [bad-assignment]
    -    --> tests/unit_tests/core/tools/test_tool_manager.py:1310:30
    +    --> tests/unit_tests/core/tools/test_tool_manager.py:1380:30
     ERROR `SimpleNamespace` is not assignable to attribute `entity` with type `ToolProviderEntityWithPlugin` [bad-assignment]
    -    --> tests/unit_tests/core/tools/test_tool_manager.py:1334:30
    +    --> tests/unit_tests/core/tools/test_tool_manager.py:1404:30
     ERROR Cannot index into `str` [bad-index]
    -    --> tests/unit_tests/core/tools/test_tool_manager.py:1339:20
    +    --> tests/unit_tests/core/tools/test_tool_manager.py:1409:20
     ERROR `None` is not subscriptable [unsupported-operation]
        --> tests/unit_tests/core/tools/utils/test_message_transformer.py:155:16
     ERROR Argument `Literal['not a dict']` is not assignable to parameter `d` with type `dict[str, Any]` in function `core.tools.utils.message_transformer.safe_json_dict` [bad-argument-type]
    
    

    </details>

    asukaminato0721 asukaminato0721 commented on code on Nov 29, 2026 08:45 UTC
    Code Review
    api/core/tools/tool_manager.py:1
    @@ -798,33 +798,35 @@ def get_api_provider_controller(
     
             :return: the provider controller, the credentials
             """
    -        provider: ApiToolProvider | None = db.session.scalar(
    -            select(ApiToolProvider)
    -            .where(
    -                ApiToolProvider.id == provider_id,
    -                ApiToolProvider.tenant_id == tenant_id,
    +        with Session(db.engine) as session:

    Take the session as a required parameter instead of reaching for a global (@with_session injects it in controllers). If this code must open and commit its own short transaction, take the session factory as a parameter instead (e.g. in __init__). Then tests pass sqlite_session / sqlite_session_factory directly and need no monkeypatch, and can assert the committed row from another session instead of counting commits.

    <sub>dify-codereview · inject-session Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=inject-session;key=18f85edb6278532e -->

    asukaminato0721 asukaminato0721 commented on code on Nov 29, 2026 08:45 UTC
    Code Review
    api/tests/unit_tests/core/tools/test_tool_manager.py:1
    @@ -1203,6 +1203,82 @@ def test_get_api_provider_controller_not_found_raises(monkeypatch: pytest.Monkey
             ToolManager.get_api_provider_controller("00000000-0000-0000-0000-000000000001", provider_id)
     
     
    +def test_get_api_provider_controller_maps_api_key_header_auth(
    +    monkeypatch: pytest.MonkeyPatch, tool_database: _ToolDatabase
    +):
    +    tenant_id = "00000000-0000-0000-0000-000000000001"
    +    provider = _api_provider(provider_id="00000000-0000-0000-0000-000000000002", tenant_id=tenant_id)
    +    provider.credentials_str = '{"auth_type":"api_key_header","api_key_value":"secret"}'
    +    tool_database.session.add(provider)
    +    tool_database.session.commit()
    +    monkeypatch.setattr("core.tools.tool_manager.db", tool_database)

    Rather than patching this in the test, change the production code to take the dependency as a parameter (pass the session / account / service in), so the test hands in a real one and needs no patch.

    <sub>dify-codereview · tests-real-dependencies (inject-dependency) Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=tests-real-dependencies;option=inject-dependency;key=0c73b87c2895ed92 -->

    asukaminato0721 asukaminato0721 commented on code on Nov 29, 2026 08:45 UTC
    Code Review
    api/tests/unit_tests/core/tools/test_tool_manager.py:1
    @@ -1203,6 +1203,82 @@ def test_get_api_provider_controller_not_found_raises(monkeypatch: pytest.Monkey
             ToolManager.get_api_provider_controller("00000000-0000-0000-0000-000000000001", provider_id)
     
     
    +def test_get_api_provider_controller_maps_api_key_header_auth(
    +    monkeypatch: pytest.MonkeyPatch, tool_database: _ToolDatabase
    +):
    +    tenant_id = "00000000-0000-0000-0000-000000000001"
    +    provider = _api_provider(provider_id="00000000-0000-0000-0000-000000000002", tenant_id=tenant_id)
    +    provider.credentials_str = '{"auth_type":"api_key_header","api_key_value":"secret"}'
    +    tool_database.session.add(provider)
    +    tool_database.session.commit()
    +    monkeypatch.setattr("core.tools.tool_manager.db", tool_database)
    +
    +    built_controller, _ = ToolManager.get_api_provider_controller(tenant_id, provider.id)
    +
    +    schema_names = {config.name for config in built_controller.entity.credentials_schema}
    +    assert "api_key_header" in schema_names
    +
    +
    +def test_user_get_api_provider_not_found_raises(monkeypatch: pytest.MonkeyPatch, tool_database: _ToolDatabase):
    +    tenant_id = "00000000-0000-0000-0000-000000000001"
    +    tool_database.session.add(_api_provider(provider_id="00000000-0000-0000-0000-000000000002", tenant_id=tenant_id))
    +    tool_database.session.commit()
    +    monkeypatch.setattr("core.tools.tool_manager.db", tool_database)
    +
    +    with pytest.raises(ValueError, match="you have not added provider missing"):
    +        ToolManager.user_get_api_provider("missing", tenant_id)
    +
    +
    +def test_user_get_api_provider_tolerates_invalid_credentials_json_unmasked(
    +    monkeypatch: pytest.MonkeyPatch, tool_database: _ToolDatabase
    +):
    +    tenant_id = "00000000-0000-0000-0000-000000000001"
    +    provider = _api_provider(provider_id="00000000-0000-0000-0000-000000000002", tenant_id=tenant_id)
    +    provider.credentials_str = "not-json"
    +    tool_database.session.add(provider)
    +    tool_database.session.commit()
    +    monkeypatch.setattr("core.tools.tool_manager.db", tool_database)
    +    cache = NoOpProviderCredentialCache()
    +    encrypter = ProviderConfigEncrypter(
    +        tenant_id=tenant_id,
    +        config=[BasicProviderConfig(name="api_key_value", type=ProviderConfigType.SECRET_INPUT)],
    +        provider_config_cache=cache,
    +    )
    +    with (
    +        patch("core.tools.tool_manager.create_tool_provider_encrypter", return_value=(encrypter, cache)),
    +        patch("core.tools.tool_manager.ToolLabelManager.get_tool_labels", return_value=[]),
    +    ):
    +        user_payload = ToolManager.user_get_api_provider(provider.name, tenant_id, mask=False)
    +
    +    assert user_payload["credentials"] == {}
    +
    +
    +def test_user_get_api_provider_tolerates_invalid_icon_json_and_header_auth(
    +    monkeypatch: pytest.MonkeyPatch, tool_database: _ToolDatabase
    +):
    +    tenant_id = "00000000-0000-0000-0000-000000000001"
    +    provider = _api_provider(provider_id="00000000-0000-0000-0000-000000000002", tenant_id=tenant_id)
    +    provider.icon = "not-json"
    +    provider.credentials_str = '{"auth_type":"api_key_header","api_key_value":"secret"}'
    +    tool_database.session.add(provider)
    +    tool_database.session.commit()
    +    monkeypatch.setattr("core.tools.tool_manager.db", tool_database)
    +    cache = NoOpProviderCredentialCache()
    +    encrypter = ProviderConfigEncrypter(
    +        tenant_id=tenant_id,
    +        config=[BasicProviderConfig(name="api_key_value", type=ProviderConfigType.SECRET_INPUT)],
    +        provider_config_cache=cache,
    +    )
    +    with (
    +        patch("core.tools.tool_manager.create_tool_provider_encrypter", return_value=(encrypter, cache)),
    +        patch("core.tools.tool_manager.ToolLabelManager.get_tool_labels", return_value=[]),
    +    ):
    +        user_payload = ToolManager.user_get_api_provider(provider.name, tenant_id)
    +
    +    assert user_payload["icon"] == {"background": "#252525", "content": "\ud83d\ude01"}
    +    assert user_payload["credentials"]["api_key_value"] == "******"

    Parse, don't validate (https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/): model this data once at the boundary as a pydantic model / dataclass / TypedDict (Model.model_validate(raw)), and pass the typed value on, instead of passing dicts around and re-checking keys and types where they are used. In a test, don't build this as an ad hoc dict[str, object]: define the shape (TypedDict / model) in the production code and import it here.

    <sub>dify-codereview · parse-dont-validate Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=parse-dont-validate;key=74bbdd5ee3f8f211 -->

    asukaminato0721 asukaminato0721 requested changes on Nov 29, 2026 08:45 UTC
    Changes Requested Reviewer

    3 inline suggestions at 8c1fd8d5d3, each from a rule learned from earlier reviews in this repository. Reply on a comment if it is wrong.

    <sub>dify-codereview</sub>
    <!-- dify-review:head=8c1fd8d5d3b4a5af03a894e1bbbc7eab0cb56326 -->

    asukaminato0721 asukaminato0721 commented on code on Nov 30, 2026 00:30 UTC
    Code Review
    api/tests/unit_tests/controllers/console/workspace/test_tool_providers.py:1
    @@ -1451,7 +1451,7 @@ def test_api_provider_get(app: Flask, controller_module, monkeypatch: pytest.Mon
                 resp = controller_module.ToolApiProviderGetApi().get()
     
             assert resp == expected_response
    -        service_mock.assert_called_once_with(user.id, "tenant-12", "foo")
    +        service_mock.assert_called_once_with(user.id, "tenant-12", "foo", session=ANY)

    Please don't pin the exact calls here (assert_called_once_with and friends): that breaks on harmless refactors and only proves the mock was hit. Assert the general behaviour instead: what is returned, persisted, raised or emitted.

    <sub>dify-codereview · tests-behavior-not-calls Reply here if this is wrong.</sub>
    <!-- dify-review:rule=tests-behavior-not-calls;key=5756b33498bc8b45 -->

    asukaminato0721 asukaminato0721 commented on code on Nov 30, 2026 00:30 UTC
    Code Review
    api/services/data_migration/export_service.py:1
    @@ -247,13 +248,17 @@ def _export_api_tools(
             include_secrets: bool,
             exported_tools: list[dict[str, Any]],
             report_items: list[ResourceReportItem],
    +        session: Session,
         ) -> None:
             for provider_id in self._dedupe(provider_ids):
                 try:
    -                tool_data = ToolManager.user_get_api_provider(
    -                    provider=provider_id,
    -                    tenant_id=tenant_id,
    -                    mask=not include_secrets,
    +                tool_data: dict[str, Any] = dict(

    Parse, don't validate (https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/): model this data once at the boundary as a pydantic model / dataclass / TypedDict (Model.model_validate(raw)), and pass the typed value on, instead of passing dicts around and re-checking keys and types where they are used. In a test, don't build this as an ad hoc dict[str, object]: define the shape (TypedDict / model) in the production code and import it here.

    <sub>dify-codereview · parse-dont-validate Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=parse-dont-validate;key=56efa1482dc2808f -->

    asukaminato0721 asukaminato0721 commented on code on Nov 30, 2026 00:30 UTC
    Code Review
    api/tests/unit_tests/services/data_migration/test_export_service.py:1
    @@ -98,11 +98,15 @@ def test_export_config_parser_rejects_unsupported_app_modes() -> None:
             )
     
     
    -def test_secret_free_api_tool_export_uses_masking_and_omits_credentials(monkeypatch: pytest.MonkeyPatch) -> None:
    +def test_secret_free_api_tool_export_uses_masking_and_omits_credentials(
    +    monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
    +) -> None:
         calls = []
     
    -    def fake_get_api_provider(provider: str, tenant_id: str, mask: bool = True) -> dict[str, object]:
    -        calls.append((provider, tenant_id, mask))
    +    def fake_get_api_provider(
    +        provider: str, tenant_id: str, mask: bool = True, *, session: Session
    +    ) -> dict[str, object]:

    Parse, don't validate (https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/): model this data once at the boundary as a pydantic model / dataclass / TypedDict (Model.model_validate(raw)), and pass the typed value on, instead of passing dicts around and re-checking keys and types where they are used. In a test, don't build this as an ad hoc dict[str, object]: define the shape (TypedDict / model) in the production code and import it here.

    <sub>dify-codereview · parse-dont-validate Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=parse-dont-validate;key=1f735db7b105bd98 -->

    asukaminato0721 asukaminato0721 commented on code on Nov 30, 2026 00:30 UTC
    Code Review
    api/tests/unit_tests/core/tools/test_tool_manager.py:1
    @@ -1182,25 +1178,98 @@ def test_user_get_api_provider_masks_credentials_and_adds_labels(
             patch("core.tools.tool_manager.create_tool_provider_encrypter", return_value=(encrypter, cache)),
             patch("core.tools.tool_manager.ToolLabelManager.get_tool_labels", return_value=["search"]),
         ):
    -        user_payload = ToolManager.user_get_api_provider(provider.name, tenant_id)
    +        user_payload: ApiProviderUserPayload = ToolManager.user_get_api_provider(
    +            provider.name, tenant_id, session=sqlite_session
    +        )
     
         assert user_payload["credentials"]["api_key_value"] == "******"
         assert user_payload["labels"] == ["search"]
     
     
    -def test_get_api_provider_controller_not_found_raises(monkeypatch: pytest.MonkeyPatch, tool_database: _ToolDatabase):
    +def test_get_api_provider_controller_not_found_raises(sqlite_session: Session):
         provider_id = "00000000-0000-0000-0000-000000000002"
    -    tool_database.session.add(
    +    sqlite_session.add(
             _api_provider(
                 provider_id=provider_id,
                 tenant_id="00000000-0000-0000-0000-000000000099",
             )
         )
    -    tool_database.session.commit()
    -    monkeypatch.setattr("core.tools.tool_manager.db", tool_database)
    +    sqlite_session.commit()
     
         with pytest.raises(ToolProviderNotFoundError, match=f"api provider {provider_id} not found"):
    -        ToolManager.get_api_provider_controller("00000000-0000-0000-0000-000000000001", provider_id)
    +        ToolManager.get_api_provider_controller(
    +            "00000000-0000-0000-0000-000000000001", provider_id, session=sqlite_session
    +        )
    +
    +
    +def test_get_api_provider_controller_maps_api_key_header_auth(sqlite_session: Session):
    +    tenant_id = "00000000-0000-0000-0000-000000000001"
    +    provider = _api_provider(provider_id="00000000-0000-0000-0000-000000000002", tenant_id=tenant_id)
    +    provider.credentials_str = '{"auth_type":"api_key_header","api_key_value":"secret"}'
    +    sqlite_session.add(provider)
    +    sqlite_session.commit()
    +
    +    built_controller, _ = ToolManager.get_api_provider_controller(tenant_id, provider.id, session=sqlite_session)
    +
    +    schema_names = {config.name for config in built_controller.entity.credentials_schema}
    +    assert "api_key_header" in schema_names
    +
    +
    +def test_user_get_api_provider_not_found_raises(sqlite_session: Session):
    +    tenant_id = "00000000-0000-0000-0000-000000000001"
    +    sqlite_session.add(_api_provider(provider_id="00000000-0000-0000-0000-000000000002", tenant_id=tenant_id))
    +    sqlite_session.commit()
    +
    +    with pytest.raises(ValueError, match="you have not added provider missing"):
    +        ToolManager.user_get_api_provider("missing", tenant_id, session=sqlite_session)
    +
    +
    +def test_user_get_api_provider_tolerates_invalid_credentials_json_unmasked(sqlite_session: Session):
    +    tenant_id = "00000000-0000-0000-0000-000000000001"
    +    provider = _api_provider(provider_id="00000000-0000-0000-0000-000000000002", tenant_id=tenant_id)
    +    provider.credentials_str = "not-json"
    +    sqlite_session.add(provider)
    +    sqlite_session.commit()
    +    cache = NoOpProviderCredentialCache()
    +    encrypter = ProviderConfigEncrypter(
    +        tenant_id=tenant_id,
    +        config=[BasicProviderConfig(name="api_key_value", type=ProviderConfigType.SECRET_INPUT)],
    +        provider_config_cache=cache,
    +    )
    +    with (
    +        patch("core.tools.tool_manager.create_tool_provider_encrypter", return_value=(encrypter, cache)),

    Rather than patching this in the test, change the production code to take the dependency as a parameter (pass the session / account / service in), so the test hands in a real one and needs no patch.

    <sub>dify-codereview · tests-real-dependencies (inject-dependency) Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=tests-real-dependencies;option=inject-dependency;key=04c6237b22513940 -->

    asukaminato0721 asukaminato0721 requested changes on Nov 30, 2026 00:30 UTC
    Changes Requested Reviewer

    4 inline suggestions at bddaa71a98, each from a rule learned from earlier reviews in this repository. Reply on a comment if it is wrong. 1 review thread is still unresolved.

    <sub>dify-codereview</sub>
    <!-- dify-review:head=bddaa71a98ae72b394f4ad913cc10e24693c0e07 -->

    asukaminato0721 asukaminato0721 requested changes on Nov 30, 2026 04:01 UTC
    Changes Requested Reviewer

    This branch has conflicts with main: please rebase onto the latest main. Checked bddaa71a98.

    <sub>dify-codereview</sub>
    <!-- dify-review:head=bddaa71a98ae72b394f4ad913cc10e24693c0e07;conflict=bddaa71a98ae72b394f4ad913cc10e24693c0e07 -->

    asukaminato0721 asukaminato0721 commented on code on Nov 30, 2026 11:31 UTC
    Code Review
    api/core/tools/tool_manager.py:1
    @@ -71,6 +73,40 @@ class ApiProviderControllerItem(TypedDict):
         controller: ApiToolProviderController
     
     
    +class ApiProviderUserPayload(TypedDict):
    +    """User-facing view of one API tool provider.
    +
    +    Invariant: ``credentials`` is always decrypted; secret values are masked
    +    unless the caller asked for the unmasked export form.
    +    """
    +
    +    schema_type: str
    +    schema: str
    +    tools: list[dict[str, Any]]

    Parse, don't validate (https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/): model this data once at the boundary as a pydantic model / dataclass / TypedDict (Model.model_validate(raw)), and pass the typed value on, instead of passing dicts around and re-checking keys and types where they are used. In a test, don't build this as an ad hoc dict[str, object]: define the shape (TypedDict / model) in the production code and import it here.

    <sub>dify-codereview · parse-dont-validate Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=parse-dont-validate;key=0e86836197230c4b -->

    asukaminato0721 asukaminato0721 requested changes on Nov 30, 2026 11:31 UTC
    Changes Requested Reviewer

    1 inline suggestion at 82146d4d9e, from a rule learned from earlier reviews in this repository. Reply on the comment if it is wrong. 1 review thread is still unresolved.

    <sub>dify-codereview</sub>
    <!-- dify-review:head=82146d4d9e380371381e4debae8456e6561f46d7 -->

    asukaminato0721 asukaminato0721 commented on code on Nov 30, 2026 14:31 UTC
    Code Review
    api/core/tools/tool_manager.py:1
    @@ -273,7 +328,11 @@ def get_tool_runtime(
                     )
     
                 case ToolProviderType.API:
    -                api_provider, credentials = cls.get_api_provider_controller(tenant_id, provider_id)
    +                # The API provider read owns a short-lived session from the
    +                # configured factory, matching the workflow branch below;
    +                # get_api_provider_controller itself receives the session.
    +                with session_factory.create_session() as session:

    Take the session as a required parameter instead of reaching for a global (@with_session injects it in controllers). If this code must open and commit its own short transaction, take the session factory as a parameter instead (e.g. in __init__). Then tests pass sqlite_session / sqlite_session_factory directly and need no monkeypatch, and can assert the committed row from another session instead of counting commits.

    <sub>dify-codereview · inject-session Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=inject-session;key=61a4f63ddcc75efe -->

    asukaminato0721 asukaminato0721 commented on code on Nov 30, 2026 14:31 UTC
    Code Review
    api/core/tools/tool_manager.py:1
    @@ -71,7 +73,60 @@ class ApiProviderControllerItem(TypedDict):
         controller: ApiToolProviderController
     
     
    +class ApiToolBundleDict(TypedDict):
    +    """JSON shape of ``ApiToolBundle.model_dump(mode="json")``.
    +
    +    Invariant: every key is always present, mirroring the model dump;
    +    ``operation_id`` is ``None`` for schema operations without one.
    +    """
    +
    +    server_url: str
    +    method: str
    +    summary: str | None
    +    operation_id: str | None
    +    parameters: list[dict[str, Any]] | None

    Parse, don't validate (https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/): model this data once at the boundary as a pydantic model / dataclass / TypedDict (Model.model_validate(raw)), and pass the typed value on, instead of passing dicts around and re-checking keys and types where they are used. In a test, don't build this as an ad hoc dict[str, object]: define the shape (TypedDict / model) in the production code and import it here.

    <sub>dify-codereview · parse-dont-validate Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=parse-dont-validate;key=a7de908bc88c5540 -->

    asukaminato0721 asukaminato0721 requested changes on Nov 30, 2026 14:31 UTC
    Changes Requested Reviewer

    2 inline suggestions at b89154a1d4, each from a rule learned from earlier reviews in this repository. Reply on a comment if it is wrong. 1 review thread is still unresolved.

    <sub>dify-codereview</sub>
    <!-- dify-review:head=b89154a1d4cdc32136b18f8e1c41d6a8b9b227cb -->

    Mattenhaim Mattenhaim commented on code on Nov 30, 2026 15:04 UTC
    Code Review
    api/core/tools/tool_manager.py:1
    @@ -71,7 +73,60 @@ class ApiProviderControllerItem(TypedDict):
         controller: ApiToolProviderController
     
     
    +class ApiToolBundleDict(TypedDict):
    +    """JSON shape of ``ApiToolBundle.model_dump(mode="json")``.
    +
    +    Invariant: every key is always present, mirroring the model dump;
    +    ``operation_id`` is ``None`` for schema operations without one.
    +    """
    +
    +    server_url: str
    +    method: str
    +    summary: str | None
    +    operation_id: str | None
    +    parameters: list[dict[str, Any]] | None

    This one looks like a false positive — the flagged code is the boundary model. ApiToolBundleDict was introduced in b89154a specifically to answer the previous round of this rule: it defines the shape of ApiToolBundle.model_dump(mode="json") once in production code, the payload is validated at the boundary through the pydantic TypeAdapter (_api_tool_bundles_adapter.validate_python), and the tests import the TypedDict from production code instead of building ad-hoc dicts. No key/type re-checks remain at use sites. Happy to adjust if you had a different spot in mind.

    Mattenhaim Mattenhaim commented on code on Nov 30, 2026 15:07 UTC
    Code Review
    api/core/tools/tool_manager.py:1
    @@ -273,7 +328,11 @@ def get_tool_runtime(
                     )
     
                 case ToolProviderType.API:
    -                api_provider, credentials = cls.get_api_provider_controller(tenant_id, provider_id)
    +                # The API provider read owns a short-lived session from the
    +                # configured factory, matching the workflow branch below;
    +                # get_api_provider_controller itself receives the session.
    +                with session_factory.create_session() as session:

    Fully agreed with the rule for methods that own a transaction — that's why get_api_provider_controller now takes the session as a required parameter. This call site is different, though: get_tool_runtime is a classmethod dispatcher with five production callers (workflow tool node, node runtime, the draft-workflow event handler, and two service adapters), so there is no __init__ to inject into, and adding a required session/factory parameter would ripple through every caller — well beyond this PR's zero-signature-change scope. The branch also mirrors the adjacent WORKFLOW branch, which opens Session(db.engine) directly. On the testing side, the unit-test conftest binds the global factory to the pristine sqlite schema via an autouse fixture, so tests already run against real sessions with no per-test monkeypatching. If you'd like the full factory injection threaded through the dispatcher and all its callers, I'd gladly take it on as a follow-up PR rather than grow this one.

    Assignees
    Mattenhaim Mattenhaim
    Labels
    risk: low confidence: 93.4% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52.3% (MEDIUM) · Higher = larger blast radius
    52.3%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 93.4% · Lower = rushed or shallow review
    93.4%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 3.5% · Safe to merge
    3.5%