Commit Graph

32 Commits

Author SHA1 Message Date
Teknium
9cf5278eee fix(mcp-elicit): no form question opens after the elicitation has ended
When the elicitation deadline passed, the server got "cancel" but the form
worker (a to_thread call cancellation cannot stop) went on to ask the next
batch or re-ask. The handler now ends one shared form deadline when its wait
ends, and the form checks it before every prompt.
2026-11-14 11:26:33 -08:00
Teknium
f1aaabe2b2 fix(mcp-elicit): an elicitation outside a tool call still reaches the user
The captured prompt-callback slot is only filled inside call_tool; during
resources/read or prompts/get it was None and iterating it raised TypeError,
so the request was declined before any prompt. The slot is now an empty tuple
when unset, and the handler treats a missing capture as empty.
2026-11-14 11:26:33 -08:00
Teknium
b8aecc63ba fix(mcp): form elicitation asks the user for the requested fields on every surface
An MCP server that elicits a form (strings, numbers, enums, booleans) got a
yes/no approval card and then `accept` with empty content, which fails the
server's own schema. Form-mode elicitation now asks the user for each field
through the turn's clarify callback, which the classic CLI, Ink TUI, Desktop
and every messaging platform already render, validates the answers against
the requested schema (types, enum values, min/max, length, email/uri/date
formats), re-asks a wrong answer up to twice, and returns accept with typed
content, decline or cancel.

- The executor binds the agent's clarify callback per dispatched tool call
  (ContextVar); the elicitation reads it inside the call's contextvars
  snapshot on the MCP worker thread.
- A form with no fields is asked as the server's own question with Yes / No
  (the intent of #140136, delivered through the clarify surface so no
  gateway facade grows).
- No clarify callback, or a session nobody can answer (cron, -q, unattended
  platforms): the existing approval path runs and declines headless; an
  approval there fills only the consent content it can honestly fill (#105496).
- Answers go to the MCP server only; they reach the model only when the
  server echoes them in its tool result.

Co-authored-by: David Lepaux <d.lepaux@gmail.com>
2026-11-14 11:26:33 -08:00
liuhao1024
ee02668f51 fix(mcp): carry the turn thread's prompt callbacks across the elicitation consent hop
A server-initiated elicitation mid tools/call routes its consent through
asyncio.to_thread. The handler already replays the owning call's contextvars
snapshot (_pending_call_context) so gateway-platform detection survives the
task hop, but the per-thread prompt callbacks (approval, sudo, vault unlock)
live in threading.local and do not follow: on the executor thread
_get_approval_callback() returns None, so a CLI/TUI/ACP session fails the
consent closed as "the user did not approve" even though a callback was
installed for the whole turn — the GHSA-qg5c-hvr5-hjgr class on the
elicitation path.

Capture the callbacks on the agent turn thread next to the contextvars
snapshot (capture_thread_callbacks), carry them in the same pending-call
slot, and install/clear them around the consent invocation (executor threads
are reused, so an install is never leaked past the call).
2026-11-14 11:26:33 -08:00
coldcrippy
b07be89cef fix(mcp): return schema-valid consent responses 2026-11-14 11:26:33 -08:00
Teknium
9bd4f7670d fix(mcp): names the server matches stay exact; only prose is stripped
Independent review round 2 on the hidden-character stripping:
- P2: prompt names and prompt argument names were stripped when listed, so
  get_prompt sent the altered name back and a prompt whose real name carries a
  hidden char became uncallable. They now round-trip byte-exact (logged, like
  schema names); descriptions are still stripped. Same rule for the resource
  uri (read_resource sends it back) and sampling tool names (tool_calls echo
  them). tool_use/tool_result ids stay stripped symmetrically so pairs match.
- P3: draft-07 `dependencies` array values list property names: kept exact;
  object values are sub-schemas and are walked as schema.
- P3: historical sampling tool-call arguments are execution data matched
  against the tool's exact schema names/enums: keys and values kept exact.
2026-11-08 11:53:54 -08:00
Teknium
a47ece974b fix(mcp): keep schema names and enum values exact; pair sampling tool-call ids
Review follow-up. Stripping every string in inputSchema also rewrote property names
and enum/const/required values, which are the server's call contract: a tool with a
hidden char in a property name or allowed value would get calls it rejects, and
unrename_tool_args cannot restore them. Free text (descriptions, titles, defaults,
examples) is still stripped at any depth; contract strings stay byte-exact and a
hidden char there is logged. strip_unicode_tags_deep goes back to its #118573 form,
since the schema walk now lives in mcp_tool_schema.strip_schema_annotations (which
returns the same object when nothing changed).

Sampling: the assistant tool call's id now gets the same TAG strip as the matching
result's tool_call_id, so a tagged pair still matches.
2026-11-08 11:53:54 -08:00
Teknium
4ed1b54276 fix(mcp): strip invisible Unicode from every tool-metadata string
_convert_mcp_schema stripped TAG chars from the tool description only. Parameter
descriptions, titles, enum values and defaults anywhere in inputSchema kept them, and
bidi override/isolate controls (U+202A-202E, U+2066-2069) survived in all tool metadata.
Both reach the model on every API call while rendering as nothing (or reordered) for the
user. Registration and sampling-forwarded tools now strip both from the description and
recursively from the schema; ZWJ/ZWNJ stay (emoji and some scripts need them).

strip_unicode_tags_deep now returns the same object when nothing matched, so a clean
schema's wire bytes and identity are unchanged.

Co-authored-by: Sahil-SS9 <218421507+Sahil-SS9@users.noreply.github.com>
2026-11-08 11:53:54 -08:00
beardthelion
b3a35c49c8 mcp: strip invisible unicode TAG chars from server-controlled metadata
The TAG-char sweep (#80689) covered MCP text content but left the
metadata fields around it raw: dropped-block notices, resource-link and
embedded-resource uri/name/mime, isError text, resource/prompt list
entries, get_prompt role/description, sampling messages and systemPrompt
written into call_llm, forwarded sampling tool metadata, elicitation
prompts, and server RPC error text via _sanitize_error. Each is a
prompt-injection channel: invisible to the user, readable by the model.

Strip every server-controlled string before it reaches model-facing
output, including nested JSON via new strip_unicode_tags_deep.
structuredContent/_meta deep-stripping is deliberately left to #88376.
2026-11-08 11:53:54 -08:00
Maciej Lisiewski
aff64c3eeb ci: UP007, UP022, UP028, UP031, UP041 linter fixes 2026-10-09 17:31:52 +02:00
Maciej Lisiewski
d76cce4f11 ci: apply all automatic linter fixes available 2026-10-08 17:22:54 +02:00
nikkoxgonzales
ffe73c37f0 fix(mcp): make sampling.tools capability opt-in via expose_client_tools 2026-10-05 16:47:32 -05:00
ethernet
ee2b165e78 chore: drop merge-resolution notes, dead imports and a dead probe module
- 15 `MERGE-CHECK:` conflict-resolution comments removed from prod code (two were
  TODOs already done: the utf-8-sig sessions.json read lives in session_persistence,
  the pm-aware cron script helpers in scheduler_script).
- 49 imports the branch left unused (ruff F401, none present at the merge base,
  none inside PLUGIN-COMPAT blocks). update_cmd's frozen-surface re-exports are
  trimmed to the names tests/compat/old_updater_surface.json actually lists under
  hermes_cli.update_cmd; the rest resolve through hermes_cli.main.__getattr__.
- tools/environments/local_gitbash_probe.py: nothing imported it once _find_bash
  delegated to pm.shell().
- Three try/except wrappers around calls that cannot raise (install_truststore,
  get_hermes_home, and a duplicated except clause in supermemory).
2026-09-18 19:31:50 -04:00
ethernet
7d2b3b767d merge: integrate upstream/main into ethie/pm-clean
Merge upstream b1f003e186 while preserving PM runtime ownership and
Python 3.14 worker startup, Windows signing, and macOS wait recovery.

Keep retired runtime modules deleted. Port upstream updater preflight
checks into the checkout strategy and preserve live build logging.
Carry checkpoint filename handling and process recovery into the current
module layout. Regenerate locks and adapt incoming platform test markers.

Focused Python and JavaScript tests, desktop and root-test typechecks,
conflict-path lint checks, lock validation, and retired-import checks pass.
The full test suite and packaged release builds were not run.
2026-09-08 19:17:39 -04:00
kshitijk4poor
2f1609a86c refactor: sms AIOHTTP_AVAILABLE flag; ElicitationHandler call_context defaults to a no-op thunk; drop stale TYPE_CHECKING/type-ignore in two tests
Self-review follow-ups on the F821 sweep:

- plugins/platforms/sms/adapter.py: the optional-import block now sets AIOHTTP_AVAILABLE like
  the homeassistant / webhook / whatsapp_cloud adapters, and both call sites test the flag.
  Removes the `if not aiohttp is not None:` double negation left by inlining
  `_aiohttp_available()`.
- tools/mcp_tool_sampling.py: `call_context` defaults to `lambda: None` so the use site is a
  single call instead of an Optional guard; the only None caller was a test. The
  `from __future__ import annotations` was noise (`Context` is a runtime import). Comment
  names the actual cycle (mcp_tool_server_run imports this module).
- gateway/platforms/helpers.py: drop the `from __future__ import annotations` — the only
  MessageEvent annotations are attribute-target locals, which are never evaluated.
- tests/gateway/test_telegram_audio_vs_voice.py, test_video_context_note.py: module-level
  `from gateway.run import GatewayRunner` like the ~100 sibling files; the
  TYPE_CHECKING block + `# type: ignore[name-defined]` were contradicting each other.
  (tests/e2e/conftest.py and test_feishu.py keep TYPE_CHECKING deliberately: they stub
  telegram/discord before importing, and FeishuAdapter is gated on optional lark_oapi.)

Mutation check: neutralising the thunk read (`captured = None`) fails
test_captured_context_is_replayed_in_consent_call; restored → 14/14 green. ty on the three
touched production files vs origin/main: 0 new, 6 resolved.
2026-09-07 22:47:33 +05:30
kshitijk4poor
ab2f4602de refactor: MessageEvent to gateway/platforms/event.py; ElicitationHandler takes a call_context thunk
Breaks the two import cycles that forced Protocol stand-ins in the F821 sweep, so the two
sites now name the real types.

gateway/platforms/event.py (new leaf): MessageType, ProcessingOutcome, MessageEvent moved
out of base.py verbatim. Their only dependency is gateway.session.SessionSource; base.py
imported helpers.py at module level, so helpers could not name MessageEvent. Now
TextBatchAggregator is typed by the real MessageEvent. 249 importers repointed
(`from gateway.platforms.base import` -> `.event`, preserving each import's layout);
gateway.platforms.__init__ re-exports from .event. The three revert-scheduled PLUGIN-COMPAT
pointers that named these symbols (gateway.slash_commands → MessageType, dingtalk → MessageType,
photon → ProcessingOutcome) and their COMPAT_MANIFEST rows now target gateway.platforms.event.
Docs updated: ADDING_A_PLATFORM.md, adding-platform-adapters.md (en + zh-Hans).

tools/mcp_tool_sampling.py: ElicitationHandler no longer holds a back-reference to its
MCPServerTask (mcp_tool imports sampling, so the task type cannot be named there). It only
ever read owner._pending_call_context, so it takes `call_context: Callable[[], Context | None]`
and MCPServerTask passes `lambda: self._pending_call_context`. The consent call is one
`functools.partial`, run directly or inside the captured Context.

ty on the 11 touched production files vs origin/main: 0 new diagnostics, 14 resolved.
(The one `source: SessionSource = None` diagnostic moves with the class; typing it Optional
exposes ~60 unguarded call sites — separate follow-up.)

Tests: tests/gateway + tests/plugins + tests/tools + touched files, 18,235 passed; the 31
failures reproduce identically on origin/main (macOS /private/tmp, systemd socket,
long-path fixtures, live-service tests).
2026-09-07 22:47:33 +05:30
kshitijk4poor
c5ff900761 fix: resolve the 33 F821 undefined names outside tui_gateway / feishu / godmode
Sweep of `ruff check . --select F821 --target-version py311`: 2,234 hits. 2,201 are left
alone on purpose: tui_gateway (2,169; bind_module rebinds bodies onto server.py globals,
all names verified to resolve there), the Feishu adapter (27; globals().update() SDK
binding) and the godmode script (5; dead standalone script). The other 33 were all
genuine defects. No lint config change; no TYPE_CHECKING escape hatches — every
annotation names a real, imported type; ty on the touched files: 0 new diagnostics.

- gateway/slash_commands.py: HISTORY_UNREADABLE never imported after #102117
  → NameError on the /btw error branch (same one-liner as #102952).
- gateway/platforms/whatsapp_common.py: `-> Path` return annotation with no Path
  import (the body uses `_Path`). Never raised at runtime thanks to
  `from __future__ import annotations`, but `typing.get_type_hints()` and ty
  both fail on it.
- gateway/run.py: ActivityProvenance imported at module level
  (agent.session_activity has no gateway deps); stringly annotation and the
  lazy in-function import are gone.
- tools/patch_parser.py: PatchResult imported at module level; real return
  annotation. The "avoid circular import" lazy import guarded a cycle that
  does not exist (file_operations_common never imports patch_parser).
- gateway/platforms/helpers.py: base.py imports helpers at module level, so
  MessageEvent cannot be named here; TextBatchAggregator only reads .text and
  .source, so it is typed by a BatchableEvent Protocol that MessageEvent
  satisfies structurally.
- tools/mcp_tool_sampling.py: mcp_tool imports this module, so MCPServerTask
  cannot be named here; ElicitationHandler only reads
  owner._pending_call_context, typed by an ElicitationOwner Protocol.
- plugins/platforms/sms/adapter.py: aiohttp is an optional dep ([messaging] extra) →
  module-level try/except ImportError binding `aiohttp = web = None`, the pattern the
  homeassistant / webhook / whatsapp_cloud adapters already use. Retires three lazy
  in-function imports and the `_aiohttp_available()` wrapper; `_handle_webhook` typed
  `web.Request -> web.Response`.
- plugins/platforms/teams/summary_writer.py: plain module-level `import httpx` — httpx is a
  hard core dependency (pyproject `httpx[socks]==0.28.1`), so the lazy import and the
  "imported on every CLI start" docstring premise were both wrong (plugin discovery never
  imports this module; it is reached only via the Teams adapter / meeting pipeline).

Tests:
- tests/hermes_cli/test_config.py: a test body orphaned by the wave-1 prune
  (6b81590c55) sat inside the class as dead code with self/tmp_path unbound
  — header restored, so the v11→12 custom_providers migration is covered.
- tests/tools/test_mcp_tool.py: @staticmethod recursing on `self` in the
  win32 branch; call portalocker directly.
- tests/test_background_review_list_shapes.py: main() still ran 3 pruned tests.
- tests/agent/test_cursor_optimizations_parity.py: bench() used names only
  imported inside a sibling test.
- GatewayRunner / FeishuAdapter / Dict / Optional: missing imports.
2026-09-07 22:47:33 +05:30
ethernet
92686159d1 fix(pm): integrate audited runtime and lifecycle repairs
Prepare dependency generations before selecting them. Keep shipped tool
bytes separate from writable additions, and store facts beside their entries.
Validate proposed plugin sets before config publication. Restore the previous
config if the facts write fails.

Consolidate duplicate updater, backup, setup, and voice helpers. Repair
launcher selection, dependency consumers, download ownership, update feeds,
and native Windows process and file handling.

Verification: 206 changed/prior-failing Python files reported 4630 passed,
one failed, and 330 skipped. Fix the remaining Hindsight fixture boundary.
The final targeted rerun reported 234 passed and two skipped. The store
review regression batch reported 83 passed and one skipped. Desktop
TypeScript checks, 56 selected Electron tests, 24 release tests, and the
removed-import/compatibility guards passed.

This is an integration checkpoint, not full audit acceptance. The complete
Python suite has not run on this fixed tree. Crash-atomic plugin publication,
generation cleanup, receipt correlation, and packaged lifecycle acceptance
remain open in docs/pm-audit-status.md.
2026-09-05 22:36:48 -04:00
Teknium
14791b4d4e simplify(compat): approval — drop 43 facade re-exports + _command_detection_variants late-bind seam, repoint 30 callers + 46 test files
tools/approval.py no longer re-exports sibling names (approval_context/prompt/floors/detection/
human_wait/smart/gateway_wait); it imports only what it uses. Siblings reference sibling-defined
names directly (module-attribute reads on tools.approval_context so patching the defining module
still works); only facade-owned state (_lock, _gateway_queues, _permanent_approved, _denied,
_denial_breaker_addendum, _gateway_notify_cb) is still read back through tools.approval.
approval_detection calls its own _command_detection_variants instead of late-binding through the facade.
2026-09-03 13:49:57 -07:00
Teknium
036907e328 refactor(tools): fold single-use locals into call sites in MCP stdio/loop/elicitation paths 2026-09-03 00:08:40 -07:00
Teknium
f7a4ccc081 refactor(tools): flatten identity-header/loop-stop control flow, inline SSE client factory 2026-09-03 00:01:18 -07:00
Teknium
e0bdc2324e refactor(tools): inline trivial sampling accessors, merge discovery branches 2026-09-02 23:54:08 -07:00
Teknium
a8f0249a31 refactor(tools): inline pgid capture, merge tool-loop guard branches, drop single-use locals 2026-09-02 23:47:41 -07:00
Teknium
672cd01c7c refactor(tools): fold legacy HTTP transport into streamable path, tighten MCP classifier/sampling bodies 2026-09-02 23:35:14 -07:00
Teknium
6a7d04e89d refactor(tools): collapse defensive layers and compact prose in MCP transport/loop/sampling/errors 2026-09-02 22:53:26 -07:00
Teknium
1ad360b3aa refactor(tools): compact MCP transport/loop/sampling/errors helpers, defensive collapse 2026-09-02 22:16:12 -07:00
Teknium
d9f6d9eda0 refactor(mcp): wrap overlong lines in reg/sampling/schema/agent 2026-09-02 16:01:24 -07:00
Teknium
97fbd7e232 refactor(mcp): table-drive elicitation answers, unify sampling response log, tighten collision diagnostics 2026-09-02 15:57:42 -07:00
Teknium
ade852f1d5 refactor(mcp): extract atomic snapshot publish from refresh_agent_mcp_tools; compact docstrings by hand 2026-09-02 15:55:38 -07:00
Teknium
f59fb2e292 refactor(mcp): tighten registration candidates and sampling handler; drop dead _extract_tool_result_text 2026-09-02 15:51:24 -07:00
Teknium
d6ec8c3018 refactor(mcp): unify live/cache registration into one candidate loop; phase-split sampling and elicitation handlers 2026-09-02 15:38:42 -07:00
Teknium
c1f8af1e86 refactor(tools/mcp): split mcp_tool.py into transport/lifecycle/schema/handlers/... sibling modules; compact watchdog and schema cache 2026-09-02 14:44:15 -07:00