Skip to content

Supersedes #23296: fix(retrieval): harden app_tools schema validation, method normalization, and config extraction - #25629

Open
omiagent[bot] wants to merge 1 commit into
mainfrom
community/revive-23296
Open

omiagent[bot] wants to merge 1 commit into
mainfrom
community/revive-23296

Conversation

@omiagent

@omiagent omiagent Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

What this does, in plain terms

Apps can define their own tools ("chat tools") that the Omi backend calls over HTTP on the user's behalf. Those definitions arrive from outside the repo, so malformed ones — a missing or non-dictionary parameter schema, a null HTTP method, a config object that isn't shaped as expected — used to raise AttributeError/TypeError while loading tools or serving a chat response, failing the whole request.

This change makes that path defensive: malformed tool definitions now register cleanly or return a readable per-tool error (e.g. Error: Configuration not available for <tool>) instead of crashing tool loading or the chat turn. For users this means one broken app definition can no longer break tool calls for otherwise-healthy apps. Well-formed manifests behave exactly as before.

What changed

  • _create_pydantic_model_from_schema: non-dict parameters builds an empty input model; properties/required are guarded against non-dict/non-iterable values; malformed individual parameter schemas degrade to Optional[str] instead of aborting registration; non-string/empty parameter names are skipped.
  • _supplied_arguments: non-dict kwargs returns {}.
  • create_app_tool: parameters/properties are dict-checked; MCP mcp_oauth_tokens is dict-checked; transport is normalized with an "sse" fallback (only fires for explicitly-empty values — the ChatTool model default is streamable_http).
  • _call_tool_endpoint: non-dict config returns a readable error instead of AttributeError; uid resolution additionally accepts top-level config['user_id']/config['uid'] and configurable['uid'] aliases (a compatibility widening beyond pure crash-hardening — the accepted alias set becomes an implicit contract); method is normalized (None/whitespace/lowercase safe, default POST); DELETE and other non-POST/PUT/PATCH methods now send the payload as query params instead of dropping it (GET already did; this extends the same routing to DELETE et al — note query strings commonly land in access logs).

Credit: @ghazy2001 — supersedes #23296

This branch cherry-picks the author's commit from #23296 (fix-app-tools-resilience-and-validation) with original authorship preserved in git history (ghazy2001 is the commit author; this bot is committer only). The original PR stalled without a maintainer review; the repo's AI reviewer verified the change at the original head (63d179d) as a good, correctly scoped hardening change with tests, leaning positive, and left it for human maintainer review. The code is carried forward unchanged so it can meet current CI and repo conventions; the human merge gate applies as always.

Tests

  • New: backend/tests/unit/test_app_tools_resilience.py — 9 tests covering non-dict/malformed schema model creation, non-dict kwargs, non-dict parameters and transport defaults in create_app_tool, non-dict config and uid alias fallbacks in _call_tool_endpoint, and DELETE payload routing plus method normalization. Hermetic (httpx/circuit-breaker/db mocked).
  • Local run on this branch: 19 passed / 0 failures / 0 errors / 0 skipped across test_app_tools_resilience, test_app_tools_omitted_arguments, test_app_tools_status_cap, test_app_tool_method_null (counts via junitxml).
  • scripts/backend-python-format --check clean on both changed files.

Product invariants affected

none

Failure class (fixes)

Failure-Class: none

View guided diff Turn on auto-fix

@Git-on-my-level Git-on-my-level 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.

Verdict: right direction, well-tested hardening — but not mergeable as-is: the Backend unit suite is red from three type-checker errors in this PR's own file, and one data-handling widening needs an explicit maintainer call.

Blocking — turns "Backend unit suite" (shard 1/8) green:

  • backend/utils/retrieval/tools/app_tools.py:140 — pyright reportUnnecessaryIsInstance: the guard isinstance(parameters, dict) contradicts the declared parameters: Dict[str, Any] signature (app_tools.py:128). Widen the annotation to Any — as already done for _supplied_arguments(kwargs) at app_tools.py:186 — since callers really do pass arbitrary manifest JSON.
  • app_tools.py:333 — same error for isinstance(config, dict) against config: Optional[RunnableConfig].
  • app_tools.py:337 — configurable = configurable_val if isinstance(configurable_val, dict) else config assigns a RunnableConfig into a Dict[str, Any]-declared variable (reportAssignmentType); type it Any or cast.
    All three are annotation-only; the runtime logic itself is correct.

Verified substance (both changed files):

  • backend/utils/retrieval/tools/app_tools.py — each guard is correct and has a matching test: non-dict parameters/properties/required (app_tools.py:140-146), malformed param schema degrading to Optional[str] (:152-154), non-string param names skipped (:150-151), non-dict mcp_oauth_tokens (:237), non-dict config returning a readable error (:333-334), method normalization with POST default (:380).
  • backend/tests/unit/test_app_tools_resilience.py — covers exactly the hardened paths, including the uid alias fallbacks and DELETE payload-as-params against a mocked httpx client; assertions check both the returned error strings and the outgoing request kwargs.

Non-blocking behavior widenings beyond crash-hardening (maintainer-visible):

  • uid resolution (app_tools.py:338) now also accepts configurable['uid'], config['user_id'], and config['uid']. This key set is the contract for whose data a third-party tool call acts on; the PR body flags it honestly, but expanding it should be an explicit maintainer decision, not a side effect of a hardening pass.
  • transport fallback (app_tools.py:240): an explicitly-empty transport resolves to "sse" while an absent one defaults to "streamable_http" (models/app.py:106) — two different defaults for two kinds of missing. Intentional?
  • app_tools.py:388: DELETE and other non-POST/PUT/PATCH methods now send the payload as query params (previously silently dropped). Reasonable fix, but a wire-behavior change for existing DELETE tools.
  • Nit: a whitespace-only method normalizes to "" (app_tools.py:380); method.strip().upper() or 'POST' would be safer.

Performance: O(1) isinstance guards only — no new queries or external calls. Security: malformed third-party manifests can no longer crash tool loading or a chat turn; the uid alias set is the one data-handling surface needing sign-off. Blast radius: only app-tool calls whose manifests are malformed; well-formed manifests behave exactly as before.

USER IMPACT: one broken third-party app tool definition will no longer break tool calls or chat turns for otherwise-healthy apps; everything else behaves the same.

Still wanted: the three annotation fixes to turn the suite green, a maintainer ruling on the accepted uid key set, and a one-liner on the sse-vs-streamable_http empty-transport intent. Leaving for human maintainer review specifically on the uid-alias contract; the rest is author-fixable.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added backend Backend Task (python) needs-maintainer-review Needs a human maintainer to sign off before merge labels Nov 17, 2026
@ghazy2001

Copy link
Copy Markdown

Thanks @omiagent[bot] and the Omi team for reviving this and keeping original authorship! 🙌

I checked the CI run on Backend unit shard 1/8 — all unit tests passed, and the single failure was caused by 3 Pyright typing errors in �ackend/utils/retrieval/tools/app_tools.py:

  1. Line 140 (
    eportUnnecessaryIsInstance)
    :
    parameters is annotated as Dict[str, Any] in _create_pydantic_model_from_schema(tool_name: str, parameters: Dict[str, Any]), so Pyright flags if not isinstance(parameters, dict): as redundant. Loosening the parameter annotation to parameters: Any allows the runtime check to remain defensive against malformed JSON without type checker complaints:
    diff -def _create_pydantic_model_from_schema(tool_name: str, parameters: Dict[str, Any]) -> type[BaseModel]: +def _create_pydantic_model_from_schema(tool_name: str, parameters: Any) -> type[BaseModel]:

  2. Lines 333 & 337 (
    eportUnnecessaryIsInstance &
    eportAssignmentType)
    :
    config is annotated as Optional[RunnableConfig] (a TypedDict), so if not isinstance(config, dict): is flagged, and falling back to config for configurable: Dict[str, Any] fails assignment. Treating config as
    aw_config: Any = config resolves both cleanly:
    `diff

    • if not isinstance(config, dict):
    •    return f"Error: Configuration not available for {app_tool.name}"
      
    • configurable_val = config.get('configurable')
    • configurable: Dict[str, Any] = configurable_val if isinstance(configurable_val, dict) else config
    • raw_config: Any = config
    • if not isinstance(raw_config, dict):
    •    return f"Error: Configuration not available for {app_tool.name}"
      
    • configurable_val = raw_config.get('configurable')
    • configurable: Dict[str, Any] = configurable_val if isinstance(configurable_val, dict) else dict(raw_config)
      `

Applying these small typing fixes will get Backend unit shard 1/8 100% green alongside the other 7 shards that already passed.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) needs-maintainer-review Needs a human maintainer to sign off before merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants