Skip to content

AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).

Close four more routes to the same crash loop, found in adversarial review

Rufus48f0bd3542b6
diff --git a/.env.example b/.env.example
index dec19fc7..b9d5662e 100644
--- a/.env.example
+++ b/.env.example
@@ -220,11 +220,13 @@ GOOGLE_OAUTH_CLIENT_SECRET=
# explicitly to override that either way: MCP_ENABLED=false keeps MCP off with
# the file still in place, MCP_ENABLED=true is a no-op unless the file defines
# at least one server under "mcpServers".
-# A config that defines no servers, or a gateway that fails to start, is not
-# fatal — the API boots without MCP tools (and without the email poller) and
-# logs the reason at ERROR.
+# A config that defines no servers, a path that is not a readable file, or a
+# gateway that fails to start (or hangs) is not fatal — the API boots without
+# MCP tools (and without the email poller) and logs the reason at ERROR.
# MCP_ENABLED=false
-# MCP_SERVERS_CONFIG_PATH=./company/mcp_servers.json
+# MCP_SERVERS_CONFIG_PATH defaults to ./company/mcp_servers.json, relative to
+# the working directory. Docker keeps it on the /data volume instead and sets
+# the var explicitly — see docs/deployment.md.
# Outbound DM anti-spam guard (optional tuning)
# Applied at the send-tool chokepoint: a proactive Slack/Telegram/Discord DM is
diff --git a/packages/core/openexecutive/api/main.py b/packages/core/openexecutive/api/main.py
index b194e1dc..949f8e70 100644
--- a/packages/core/openexecutive/api/main.py
+++ b/packages/core/openexecutive/api/main.py
@@ -147,6 +147,43 @@ _UNAUTHENTICATED_PATHS: frozenset[str] = frozenset(
)
+# How long the MCP gateway gets to come up. The child is
+# `uvx --from git+https://…/extensible-mcp`, which resolves and may clone that
+# repo on a cold start, so this is generous; what it must not be is unbounded.
+# `MCPGateway.start` builds `ClientSession` with no `read_timeout_seconds`, so
+# `initialize()` waits forever on a child that is alive but silent — and a
+# lifespan that never yields is a healthcheck that never passes, which is
+# #122's symptom with none of its traceback. A dead child is already fine
+# (the session's receive loop fails every pending request on close); it is the
+# silent one that needs a clock.
+_MCP_START_TIMEOUT_S = 120.0
+# Tearing down a gateway that just failed walks the same stdio machinery that
+# failed, so it gets a clock too.
+_MCP_CLOSE_TIMEOUT_S = 10.0
+
+
+async def _close_mcp_gateway_quietly(gateway: Any, log: logging.Logger) -> None:
+ """Reap a gateway that failed to start. Never raises, never hangs.
+
+ `MCPGateway.close` suppresses `Exception` around each step, which is not
+ enough here: anyio raises `BaseExceptionGroup` as soon as one sub-exception
+ is a `BaseException` such as `CancelledError`, and that is not an
+ `Exception`. Since this runs from inside an `except` block, anything it
+ raises replaces the actionable log we just wrote with the crash that log
+ exists to prevent.
+ """
+ try:
+ await asyncio.wait_for(gateway.close(), timeout=_MCP_CLOSE_TIMEOUT_S)
+ except asyncio.CancelledError:
+ raise
+ except BaseException:
+ log.warning(
+ "MCP gateway teardown after a failed start did not finish cleanly; "
+ "continuing shutdown of the failed gateway anyway",
+ exc_info=True,
+ )
+
+
async def _start_mcp_gateway(
app: FastAPI, settings: Settings
) -> asyncio.Task[None] | None:
@@ -155,17 +192,26 @@ async def _start_mcp_gateway(
Sets ``app.state.mcp_gateway`` — the gateway on success, ``None`` otherwise
— and returns the email-poller task that rides on it, or ``None``.
- Never raises. The gateway spawns extensible-mcp as a subprocess, and a
- failure there used to propagate out of the lifespan and kill the container;
- under ``restart: unless-stopped`` that is a crash loop whose only outward
- symptom is a healthcheck that never passes (#122). Booting without MCP
- costs the Gmail/Calendar/Drive tool surface and the email poller; refusing
- to boot costs everything, so degrade and log loudly enough to alert on.
+ Never raises and never blocks indefinitely. The gateway spawns
+ extensible-mcp as a subprocess, and a failure there used to propagate out
+ of the lifespan and kill the container; under ``restart: unless-stopped``
+ that is a crash loop whose only outward symptom is a healthcheck that never
+ passes (#122). Booting without MCP costs the Gmail/Calendar/Drive tool
+ surface and the email poller; refusing to boot costs everything, so degrade
+ and log loudly enough to alert on.
+
+ ``except BaseException`` rather than ``except Exception``, with real
+ cancellation re-raised first: the failure in #122 surfaced from anyio, and
+ anyio wraps a task group's failures in ``BaseExceptionGroup`` as soon as one
+ of them is a ``BaseException`` such as ``CancelledError``. That group is not
+ an ``Exception``, so ``except Exception`` would let through the single
+ exception shape this function exists to contain.
"""
app.state.mcp_gateway = None
if not settings.mcp_enabled:
return None
+ from openexecutive.config import mcp_config_file_present
from openexecutive.orchestrator.mcp_gateway import (
MCPGateway,
configured_server_names,
@@ -177,33 +223,46 @@ async def _start_mcp_gateway(
servers = configured_server_names(config_path)
# With MCP_ENABLED unset it is the config file's presence that turned MCP
# on (config._resolve_mcp), so an operator can arrive here without having
- # asked for MCP at all. Naming which it was is the fact the original
- # traceback never carried.
+ # asked for MCP. Naming which it was is the fact the original traceback
+ # never carried — and the remedy has to track it, or we tell someone who
+ # set MCP_ENABLED=true to unset the file that enabled MCP.
+ auto = settings.mcp_auto_enabled
why = (
"auto-enabled by the presence of the config file"
- if settings.mcp_auto_enabled
+ if auto
else "MCP_ENABLED was set explicitly"
)
if not servers:
log.warning(
- "MCP is on (%s) but %s defines no servers under 'mcpServers'; "
- "starting without MCP tools. Add a server to that file, or set "
- "MCP_ENABLED=false to stop the file from enabling MCP.",
- why, config_path,
+ "MCP is on (%s) but %s %s; starting without MCP tools. %s.",
+ why,
+ config_path,
+ "defines no servers under 'mcpServers'"
+ if mcp_config_file_present(config_path)
+ else "is not a readable file",
+ "Add a server to that file, or set MCP_ENABLED=false so its "
+ "presence stops enabling MCP"
+ if auto
+ else "Point MCP_SERVERS_CONFIG_PATH at a config that defines a "
+ "server, or set MCP_ENABLED=false",
)
return None
gateway = MCPGateway()
try:
- await gateway.start(config_path)
- except Exception:
+ await asyncio.wait_for(
+ gateway.start(config_path), timeout=_MCP_START_TIMEOUT_S
+ )
+ except asyncio.CancelledError:
+ raise
+ except BaseException:
log.exception(
- "MCP gateway failed to start; continuing WITHOUT MCP tools and "
- "without the email poller. config=%s servers=[%s] (%s)",
- config_path, ", ".join(servers), why,
+ "MCP gateway failed to start within %.0fs; continuing WITHOUT MCP "
+ "tools and without the email poller. config=%s servers=[%s] (%s)",
+ _MCP_START_TIMEOUT_S, config_path, ", ".join(servers), why,
)
- await gateway.close()
+ await _close_mcp_gateway_quietly(gateway, log)
return None
app.state.mcp_gateway = gateway
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index 13be4544..3466912f 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -2929,8 +2929,21 @@ integrations:
for MCP to be off (#122; the trap is easy to fall into because
docs/deployment.md lists /data/company/mcp_servers.json under persistent
state, so shipping the file there is the expected setup). It now reads
+ INVARIANT: probe the config path through config.mcp_config_file_present,
+ never Path.exists/is_file directly. Those re-raise any OSError outside
+ (ENOENT, ENOTDIR, EBADF, ELOOP), so an EACCES on a parent directory whose
+ ownership does not match the container user propagates — and from inside
+ this validator that is out of Settings() itself, which api/main.py calls at
+ module level, making it an IMPORT-time crash rather than a degraded boot.
+ The helper tests is_file, so a directory at the config path counts as
+ absent too; it used to be enough to auto-enable MCP.
+ The check reads
model_fields_set — the field names the env/init actually supplied — and
- records the outcome on the derived Settings field mcp_auto_enabled.
+ stores that on the private attr Settings._mcp_enabled_explicit, which the
+ read-only Settings.mcp_auto_enabled property reads. Private attr, not a
+ field: it is derived on every load, so an env var for it could only ever be
+ discarded, and a field with an alias would advertise a knob that does not
+ exist.
INVARIANT: read model_fields_set BEFORE assigning mcp_enabled. Pydantic
adds a field to that set on assignment too, so after the auto-enable the
set no longer distinguishes the two cases; anything downstream that wants
@@ -2948,7 +2961,19 @@ integrations:
from stdio_client unwinding a subprocess that had already gone — a
traceback that names nothing about configuration. configured_server_names()
(mcp_gateway) reads the names up front for that check and for the log; it
- returns [] for a missing, unreadable, non-object, or serverless config.
+ returns [] for a missing, unreadable, oversized, non-object, or serverless
+ config. INVARIANT: it NEVER raises, and its except is deliberately broad.
+ It reads an operator-owned path during startup, where an exception is the
+ crash loop rather than a bug report, and the narrow catch it started with
+ had two holes: Path.is_file/exists re-raise any OSError outside (ENOENT,
+ ENOTDIR, EBADF, ELOOP), so an EACCES on a parent directory whose ownership
+ does not match the container user propagates — and with an explicit
+ MCP_ENABLED=true this is the FIRST stat of the path, because _resolve_mcp
+ short-circuits its own exists() check; and json.loads answers
+ deeply-nested input with RecursionError, which is not a ValueError. It
+ tests is_file() rather than exists() so a directory or a symlink to a FIFO
+ at that path is never opened, and caps the read at _MAX_CONFIG_BYTES
+ (1 MiB) so a symlink to something huge cannot stall the boot.
A gateway that fails anyway is logged at ERROR via logger.exception with the
config path, the server names, and whether the config file or an explicit
MCP_ENABLED turned MCP on, then close()d; app.state.mcp_gateway stays None,
@@ -2960,6 +2985,30 @@ integrations:
(#122 hit 15 restarts). Losing the Gmail/Calendar/Drive surface and the
email poller beats losing the whole API. Same degradation pattern as the
Discord bot block in the lifespan.
+ INVARIANT: catch BaseException there, not Exception, with a bare
+ asyncio.CancelledError re-raised first. The #122 failure surfaced from
+ anyio, and anyio wraps a task group's failures in BaseExceptionGroup as
+ soon as one of them is a BaseException such as CancelledError.
+ BaseExceptionGroup is NOT an Exception subclass, so `except Exception`
+ lets through the exact shape the guard exists for. The re-raise keeps the
+ lifespan's own cancellation (a bare CancelledError in our frame) meaning
+ shut down rather than degrade.
+ INVARIANT: the teardown after a failed start is itself contained and
+ bounded (_close_mcp_gateway_quietly, _MCP_CLOSE_TIMEOUT_S=10s). It runs
+ from inside the except block, so anything it raises replaces the
+ actionable log with the crash that log prevents — the operator then reads
+ the right message and the container dies anyway. MCPGateway.close's own
+ contextlib.suppress(Exception) does not cover the BaseExceptionGroup case.
+ INVARIANT: the start is bounded (_MCP_START_TIMEOUT_S=120s, generous
+ because the child is `uvx --from git+…` and may clone extensible-mcp on a
+ cold start). MCPGateway.start builds ClientSession with no
+ read_timeout_seconds, so initialize() waits forever on a child that is
+ ALIVE BUT SILENT — a slow or unreachable network on that clone, for
+ instance. No try/except can see that: the lifespan simply never yields, so
+ the healthcheck never passes, which is #122's symptom with none of its
+ traceback. A DEAD child was always fine (BaseSession's receive loop fails
+ every pending request with CONNECTION_CLOSED, so initialize() raises
+ McpError); only the silent one needed a clock.
Egress gating: MCPGateway.call_tool intercepts three tool families before
delegating to the MCP subprocess. All three resolve the allow-list from the
diff --git a/packages/core/openexecutive/architecture/prebuilt/integrations.json b/packages/core/openexecutive/architecture/prebuilt/integrations.json
index a1d902b6..35a704d3 100644
--- a/packages/core/openexecutive/architecture/prebuilt/integrations.json
+++ b/packages/core/openexecutive/architecture/prebuilt/integrations.json
@@ -1,7 +1,7 @@
{
"section_id": "integrations",
"title": "Integrations",
- "markdown": "External channels connect callers to the Executive. Each inbound adapter resolves the sender to a Person via `find_person_by_{slack,discord,telegram,email}_id` and threads `person_id` into `Executive.chat()`.\n\n### Inbound channels\n\n- **Slack** (`integrations.slack_bot`) — Bolt socket-mode; responds to `@mention`s, DMs, and thread continuations.\n- **Discord** (`integrations.discord_bot`) — discord.py gateway embedded in the lifespan; per-thread auto-titling, session-scoped memory, author attribution, configurable `@mention` thread promotion.\n- **Telegram** — webhook gating + per-chat history.\n- **Google Chat** — webhook + service-account auth.\n- **Email** (`integrations.email_poller`) — IMAP poll loop; strips Reply-To, filters auto-replies.\n\nSlack, Discord, and Telegram are roster-gated on inbound: an unrostered sender's message is silently dropped (`details.outcome=\"rejected_unknown_sender\"`). Email is not inbound-gated — non-roster mail flows through with a `[POLICY]` notice so triage can classify it. Slack/Discord thread continuations pass the shared `integrations.response_gate` (utility-fast model, biased toward replying).\n\n### Attachments\n\n`integrations.attachments` handles web chat, Discord, and Telegram. Images become Anthropic vision blocks; documents (PDF/DOCX/TXT/MD/CSV) are inlined into the turn that carried them and indexed into the ChromaDB `inbound_attachments` collection. 20 MB/file cap; web chat uses `POST /chat/upload`.\n\nIndexed chunks are keyed on `attachment:<bare filename>` and tagged `type=attachment`. An attachment's name is chosen by whoever sent the message and the name is the chunk-id namespace, so without the prefix an inbound `strategy-2026.md` would upsert over the curated company document of that name. The prefix separates inbound content from curated uploads and keeps provenance visible; it does not separate senders from one another.\n\nIsolation is the **collection**: `retriever.retrieve` never queries `inbound_attachments` at all, so an attachment cannot resurface as company knowledge in a later, unrelated turn. Attachment processing is roster-gated on Discord too — it previously ran before the gate, so an unrostered sender's file was downloaded and indexed before their message was dropped. These rows still have no operator surface: they are never written to `company/docs/`, so `GET /documents` does not list them.\n\nThis replaced a domain-based scheme that did not work. The chunks lived in `company_docs` under a domain outside the specialist set, on the premise that an unrecognised domain matched no filter. It matched every one — `ChromaDBStore.query` attaches a `where` clause only when a domain filter is present, and an Executive-level retrieval passes none — so attachments came back under “From your company documents”, top-ranked and indistinguishable from a curated upload. Legacy rows are migrated across on boot.\n\n### MCP gateway & outbound\n\nMCP runs in **both directions**. As a *client*, `orchestrator.mcp_gateway.MCPGateway` proxies MCP servers (Gmail, Calendar, Drive — whatever `mcp_servers.json` configures) as Executive tools, with egress gating on Gmail recipients, Calendar attendees, and Drive share grantees against the roster (and a refusal of public / whole-domain Drive sharing). The Google Workspace server (`workspace-mcp`) behind those Gmail/Calendar/Drive tools runs **co-located inside the API** as a stdio child of the gateway — fitting the single-tenant model (one install = one company = one exec Google account), so there's no separate service to operate. It's baked into the API image and launched by `docker/workspace-mcp-launch.sh`, which selects single-user OAuth (token persisted at `/data/google_credentials`) or service-account domain-wide delegation from `GWORKSPACE_AUTH_MODE`. The gateway forwards the Google secrets to the child via `_FORWARDED_ENV_VARS`. As a *server*, `openexecutive.mcp_server` exposes OE's own company context and specialist council to external MCP clients at `/mcp` — the inverse direction; see the dedicated **MCP Server** section. The gateway launches extensible-mcp as a `uvx` subprocess whose fastembed tool-search index uses an embedding model baked into the API image and loaded offline, so it no longer re-downloads that model from the Hugging Face Hub on every cold start. Because the MCP stdio client does not inherit the parent environment, `MCPGateway.start()` explicitly forwards the embedding-cache/offline env vars (`FASTEMBED_CACHE_PATH`, `HF_HUB_OFFLINE`, …) into the child.\n\n**Enablement, and why it degrades instead of dying.** `MCP_ENABLED` left unset is inferred from the presence of `mcp_servers_config_path` — dropping an `mcp_servers.json` next to `profile.yaml` turns MCP on with no further configuration. An **explicit** setting always wins in both directions: `MCP_ENABLED=false` keeps MCP off with the file still in place. It did not: `_resolve_mcp` tested `not self.mcp_enabled`, which cannot tell \"never set\" from \"set to false\", so the file's presence silently overrode the operator. It now reads `model_fields_set` (the fields the env actually supplied) and records the outcome on `mcp_auto_enabled`, because the validator's own assignment joins that set and would otherwise make every auto-enable look explicit downstream.\n\nStartup is **best-effort**, in `main._start_mcp_gateway`. Two checks come before the subprocess: MCP off is a no-op, and a config defining no servers under `mcpServers` is logged and skipped — extensible-mcp's own loader raises on that and exits, and because the child is already gone the only thing that surfaces is anyio's \"Attempted to exit cancel scope in a different task\" from `stdio_client` unwinding, a traceback naming nothing about configuration. A gateway that fails anyway is logged at ERROR with the config path, the servers it named, and whether the config file or an explicit `MCP_ENABLED` turned MCP on, then closed; the API boots **without MCP tools and without the email poller** rather than refusing to boot. That exception used to propagate out of the lifespan and kill the container — under `restart: unless-stopped`, a crash loop whose only outward symptom was a healthcheck that never passed. Outbound tools: per-Person DMs (`send_slack_dm`, `send_discord_dm`, `send_telegram_message`) plus room-targeted `send_department_message` and `send_company_broadcast`. The per-Person DMs are additionally rate-limited and de-duplicated by the outbound anti-spam guard (below).\n\n### Outbound anti-spam guard\n\nEvery per-Person DM passes a deterministic guard (`orchestrator.outbound_guard.check_outbound_allowed`) after the roster gate and recipient-id recovery but before the network send — the single chokepoint **all** proactive DM paths reach (ad-hoc chat sends, the scheduler's followup/nudge dispatch, principal-brief delivery, the reflection turn, and research-finding routing). On a violation it returns a human-readable reason and the handler **suppresses** the send (`{\"status\":\"suppressed\",\"reason\":…}`), writes a `tool_invocation` audit row with `suppressed=true`, and writes **no** `done` activity row — so a blocked attempt never counts toward its own rate cap, and the Executive can read the reason and hold or `schedule_followup` for the recipient's next window. Three controls: **content dedup** (a near-identical message — whitespace/case-normalized, first 160 chars — already sent to the same recipient within `OUTBOUND_DEDUP_WINDOW_MINUTES`, default 360); a **per-recipient rate cap** (`OUTBOUND_MAX_PER_RECIPIENT_PER_WINDOW`, default 5, over `OUTBOUND_RATE_WINDOW_MINUTES`, default 60); and **quiet hours / availability** (`OUTBOUND_RESPECT_QUIET_HOURS`, default on — refuse while the recipient is on leave or outside their `people.channel` availability windows, surfacing the next open window). Delivery history is read from the existing `status='done'` `scheduled_actions` rows (`episodic.recent_sends_for_channel_ref`), so there is no new table. The guard is **fail-open**: any internal lookup error returns \"allow\", so it can never turn a working send into a crash or a silently-dropped message. Principal briefs and the internal heartbeat kinds use the `__internal__` channel and never reach these handlers, so they are unaffected.\n\n### Calendar & Google Meet\n\nThe Executive books meetings through two typed tools over the Calendar MCP. `create_calendar_event` schedules a **future** meeting (propose→approve by default, or auto-execute once that decision class is promoted) and may be used proactively when a stalled goal warrants a sync. `create_instant_meeting` spins up an **impromptu call starting now**, auto-executing without the approval step and skipping the business-hours/horizon caps, so the Executive can hand back a join link immediately. Both attach a **Google Meet** link by default (`add_google_meet`; opt out for in-person), parsed from the created event's `conferenceData` and surfaced to the caller plus persisted on the decision ledger. Either way the caps that matter still hold — roster membership, principal-protection, max attendees, and a daily booking ceiling.\n\n**Around-the-meeting participation.** The Executive doesn't join the call as a live voice; instead, on every successful booking it schedules a best-effort post-meeting follow-up (~5 min after the end) that DMs a human attendee asking for a quick recap — key decisions and action items. The reply flows back through the same cross-session DM context linkage described below, so the Executive can act on it (summarize, follow up) in a later turn. No meeting-transcript or Drive integration is required.\n\n### Cross-session DM context\n\nWhen the principal says \"DM Alex about X\" in one session, OE sends the DM and — if a live conversation is active — records an `outbound_context` linkage row (recipient, full outbound text, originating session id). Email is covered too but recorded one layer deeper — there is no `send_email` tool, so the linkage is written in `orchestrator.mcp_gateway` after a successful `google_workspace__send_gmail_message`, one row per `to`/`cc` recipient keyed by the bare lowercased address (OE's own address skipped). When Alex later replies on the 1:1 DM path — or by email — the shared helper `integrations.inbound_hydration.hydrate_user_message` (called by the Discord, Telegram, and Slack handlers, and by the email poller keyed on the sender address) looks up the most-recent `open` linkage for that sender within 72h and prepends an `<outbound_reply_context>` block — the outbound text plus a backstory excerpt from the originating session — to the message handed to `Executive.chat()`. So OE knows what the reply is about instead of starting from an empty per-person session. The block lands in the user turn (caching rule) and is injected into a copy only — the pristine reply is persisted to history. The linkage is one-shot (consumed on first matched reply, race-safe) so an unrelated later DM isn't re-hydrated. This is deterministic and independent of the per-person `peer_memory` (Honcho) layer.",
+ "markdown": "External channels connect callers to the Executive. Each inbound adapter resolves the sender to a Person via `find_person_by_{slack,discord,telegram,email}_id` and threads `person_id` into `Executive.chat()`.\n\n### Inbound channels\n\n- **Slack** (`integrations.slack_bot`) — Bolt socket-mode; responds to `@mention`s, DMs, and thread continuations.\n- **Discord** (`integrations.discord_bot`) — discord.py gateway embedded in the lifespan; per-thread auto-titling, session-scoped memory, author attribution, configurable `@mention` thread promotion.\n- **Telegram** — webhook gating + per-chat history.\n- **Google Chat** — webhook + service-account auth.\n- **Email** (`integrations.email_poller`) — IMAP poll loop; strips Reply-To, filters auto-replies.\n\nSlack, Discord, and Telegram are roster-gated on inbound: an unrostered sender's message is silently dropped (`details.outcome=\"rejected_unknown_sender\"`). Email is not inbound-gated — non-roster mail flows through with a `[POLICY]` notice so triage can classify it. Slack/Discord thread continuations pass the shared `integrations.response_gate` (utility-fast model, biased toward replying).\n\n### Attachments\n\n`integrations.attachments` handles web chat, Discord, and Telegram. Images become Anthropic vision blocks; documents (PDF/DOCX/TXT/MD/CSV) are inlined into the turn that carried them and indexed into the ChromaDB `inbound_attachments` collection. 20 MB/file cap; web chat uses `POST /chat/upload`.\n\nIndexed chunks are keyed on `attachment:<bare filename>` and tagged `type=attachment`. An attachment's name is chosen by whoever sent the message and the name is the chunk-id namespace, so without the prefix an inbound `strategy-2026.md` would upsert over the curated company document of that name. The prefix separates inbound content from curated uploads and keeps provenance visible; it does not separate senders from one another.\n\nIsolation is the **collection**: `retriever.retrieve` never queries `inbound_attachments` at all, so an attachment cannot resurface as company knowledge in a later, unrelated turn. Attachment processing is roster-gated on Discord too — it previously ran before the gate, so an unrostered sender's file was downloaded and indexed before their message was dropped. These rows still have no operator surface: they are never written to `company/docs/`, so `GET /documents` does not list them.\n\nThis replaced a domain-based scheme that did not work. The chunks lived in `company_docs` under a domain outside the specialist set, on the premise that an unrecognised domain matched no filter. It matched every one — `ChromaDBStore.query` attaches a `where` clause only when a domain filter is present, and an Executive-level retrieval passes none — so attachments came back under “From your company documents”, top-ranked and indistinguishable from a curated upload. Legacy rows are migrated across on boot.\n\n### MCP gateway & outbound\n\nMCP runs in **both directions**. As a *client*, `orchestrator.mcp_gateway.MCPGateway` proxies MCP servers (Gmail, Calendar, Drive — whatever `mcp_servers.json` configures) as Executive tools, with egress gating on Gmail recipients, Calendar attendees, and Drive share grantees against the roster (and a refusal of public / whole-domain Drive sharing). The Google Workspace server (`workspace-mcp`) behind those Gmail/Calendar/Drive tools runs **co-located inside the API** as a stdio child of the gateway — fitting the single-tenant model (one install = one company = one exec Google account), so there's no separate service to operate. It's baked into the API image and launched by `docker/workspace-mcp-launch.sh`, which selects single-user OAuth (token persisted at `/data/google_credentials`) or service-account domain-wide delegation from `GWORKSPACE_AUTH_MODE`. The gateway forwards the Google secrets to the child via `_FORWARDED_ENV_VARS`. As a *server*, `openexecutive.mcp_server` exposes OE's own company context and specialist council to external MCP clients at `/mcp` — the inverse direction; see the dedicated **MCP Server** section. The gateway launches extensible-mcp as a `uvx` subprocess whose fastembed tool-search index uses an embedding model baked into the API image and loaded offline, so it no longer re-downloads that model from the Hugging Face Hub on every cold start. Because the MCP stdio client does not inherit the parent environment, `MCPGateway.start()` explicitly forwards the embedding-cache/offline env vars (`FASTEMBED_CACHE_PATH`, `HF_HUB_OFFLINE`, …) into the child.\n\n**Enablement, and why it degrades instead of dying.** `MCP_ENABLED` left unset is inferred from the presence of `mcp_servers_config_path` — dropping an `mcp_servers.json` next to `profile.yaml` turns MCP on with no further configuration. An **explicit** setting always wins in both directions: `MCP_ENABLED=false` keeps MCP off with the file still in place. It did not: `_resolve_mcp` tested `not self.mcp_enabled`, which cannot tell \"never set\" from \"set to false\", so the file's presence silently overrode the operator. The file is probed through `config.mcp_config_file_present`, never `Path.exists` directly — that re-raises an EACCES on a parent directory, and from inside a validator that comes out of `Settings()` itself, which `api/main.py` calls at module level. The check now reads `model_fields_set` (the fields the env actually supplied) and stores that on a private attr behind the read-only `mcp_auto_enabled` property, because the validator's own assignment joins that set and would otherwise make every auto-enable look explicit downstream.\n\nStartup is **best-effort**, in `main._start_mcp_gateway`. Two checks come before the subprocess: MCP off is a no-op, and a config defining no servers under `mcpServers` is logged and skipped — extensible-mcp's own loader raises on that and exits, and because the child is already gone the only thing that surfaces is anyio's \"Attempted to exit cancel scope in a different task\" from `stdio_client` unwinding, a traceback naming nothing about configuration. The start is also bounded (120s, generous because that child may clone extensible-mcp on a cold start): `ClientSession` carries no `read_timeout_seconds`, so `initialize()` waits forever on a child that is *alive but silent*, and an unbounded wait is a lifespan that never yields — the same healthcheck-never-passes symptom, which no `except` can see. A gateway that fails anyway is logged at ERROR with the config path, the servers it named, and whether the config file or an explicit `MCP_ENABLED` turned MCP on, then torn down under its own timeout; the API boots **without MCP tools and without the email poller** rather than refusing to boot. The guard catches `BaseException`, not `Exception`, re-raising a bare `CancelledError` first: the original failure came from anyio, which wraps a task group's failures in `BaseExceptionGroup` as soon as one is a `BaseException` — and that group is not an `Exception`, so `except Exception` would miss the very shape this contains. The teardown is contained too, since it runs from inside that `except` and would otherwise replace the actionable log with the crash it prevents. `configured_server_names` never raises either, and deliberately catches broadly: it reads an operator-owned path during startup, where an exception is the crash loop rather than a bug report — `Path.is_file` re-raises an EACCES on a parent directory, and `json.loads` answers deeply-nested input with `RecursionError`, which is not a `ValueError`. It tests `is_file()` so a directory or a symlink to a FIFO is never opened, and caps the read at 1 MiB. That exception used to propagate out of the lifespan and kill the container — under `restart: unless-stopped`, a crash loop whose only outward symptom was a healthcheck that never passed. Outbound tools: per-Person DMs (`send_slack_dm`, `send_discord_dm`, `send_telegram_message`) plus room-targeted `send_department_message` and `send_company_broadcast`. The per-Person DMs are additionally rate-limited and de-duplicated by the outbound anti-spam guard (below).\n\n### Outbound anti-spam guard\n\nEvery per-Person DM passes a deterministic guard (`orchestrator.outbound_guard.check_outbound_allowed`) after the roster gate and recipient-id recovery but before the network send — the single chokepoint **all** proactive DM paths reach (ad-hoc chat sends, the scheduler's followup/nudge dispatch, principal-brief delivery, the reflection turn, and research-finding routing). On a violation it returns a human-readable reason and the handler **suppresses** the send (`{\"status\":\"suppressed\",\"reason\":…}`), writes a `tool_invocation` audit row with `suppressed=true`, and writes **no** `done` activity row — so a blocked attempt never counts toward its own rate cap, and the Executive can read the reason and hold or `schedule_followup` for the recipient's next window. Three controls: **content dedup** (a near-identical message — whitespace/case-normalized, first 160 chars — already sent to the same recipient within `OUTBOUND_DEDUP_WINDOW_MINUTES`, default 360); a **per-recipient rate cap** (`OUTBOUND_MAX_PER_RECIPIENT_PER_WINDOW`, default 5, over `OUTBOUND_RATE_WINDOW_MINUTES`, default 60); and **quiet hours / availability** (`OUTBOUND_RESPECT_QUIET_HOURS`, default on — refuse while the recipient is on leave or outside their `people.channel` availability windows, surfacing the next open window). Delivery history is read from the existing `status='done'` `scheduled_actions` rows (`episodic.recent_sends_for_channel_ref`), so there is no new table. The guard is **fail-open**: any internal lookup error returns \"allow\", so it can never turn a working send into a crash or a silently-dropped message. Principal briefs and the internal heartbeat kinds use the `__internal__` channel and never reach these handlers, so they are unaffected.\n\n### Calendar & Google Meet\n\nThe Executive books meetings through two typed tools over the Calendar MCP. `create_calendar_event` schedules a **future** meeting (propose→approve by default, or auto-execute once that decision class is promoted) and may be used proactively when a stalled goal warrants a sync. `create_instant_meeting` spins up an **impromptu call starting now**, auto-executing without the approval step and skipping the business-hours/horizon caps, so the Executive can hand back a join link immediately. Both attach a **Google Meet** link by default (`add_google_meet`; opt out for in-person), parsed from the created event's `conferenceData` and surfaced to the caller plus persisted on the decision ledger. Either way the caps that matter still hold — roster membership, principal-protection, max attendees, and a daily booking ceiling.\n\n**Around-the-meeting participation.** The Executive doesn't join the call as a live voice; instead, on every successful booking it schedules a best-effort post-meeting follow-up (~5 min after the end) that DMs a human attendee asking for a quick recap — key decisions and action items. The reply flows back through the same cross-session DM context linkage described below, so the Executive can act on it (summarize, follow up) in a later turn. No meeting-transcript or Drive integration is required.\n\n### Cross-session DM context\n\nWhen the principal says \"DM Alex about X\" in one session, OE sends the DM and — if a live conversation is active — records an `outbound_context` linkage row (recipient, full outbound text, originating session id). Email is covered too but recorded one layer deeper — there is no `send_email` tool, so the linkage is written in `orchestrator.mcp_gateway` after a successful `google_workspace__send_gmail_message`, one row per `to`/`cc` recipient keyed by the bare lowercased address (OE's own address skipped). When Alex later replies on the 1:1 DM path — or by email — the shared helper `integrations.inbound_hydration.hydrate_user_message` (called by the Discord, Telegram, and Slack handlers, and by the email poller keyed on the sender address) looks up the most-recent `open` linkage for that sender within 72h and prepends an `<outbound_reply_context>` block — the outbound text plus a backstory excerpt from the originating session — to the message handed to `Executive.chat()`. So OE knows what the reply is about instead of starting from an empty per-person session. The block lands in the user turn (caching rule) and is injected into a copy only — the pristine reply is persisted to history. The linkage is one-shot (consumed on first matched reply, race-safe) so an unrelated later DM isn't re-hydrated. This is deterministic and independent of the per-person `peer_memory` (Honcho) layer.",
"mermaid": "flowchart TD\n Channels[\"Slack / Discord<br/>Telegram / GChat / Email\"]\n Resolve[\"find_person_by_*_id\"]\n Gate[\"roster gate\"]\n Drop[\"drop unrostered\"]\n Exec[\"Executive.chat()\"]\n Attach[\"attachments<br/>(vision / inbound_attachments)\"]\n MCP[\"MCP gateway\"]\n Guard[\"outbound anti-spam guard<br/>(dedup / rate cap / quiet hours)\"]\n Out[\"DM / department<br/>/ broadcast tools\"]\n Channels --> Resolve\n Resolve --> Gate\n Gate -- \"unknown sender\" --> Drop\n Gate -- \"Person\" --> Exec\n Gate --> Attach\n Attach --> Exec\n Exec --> MCP\n Exec --> Guard\n Guard -- \"suppress\" --> Drop\n Guard -- \"allow\" --> Out\n Out --> Channels\n class Channels entry\n class Resolve compute\n class Gate compute\n class Drop external\n class Exec hot\n class Attach compute\n class MCP external\n class Guard compute\n class Out compute",
"generated_at": "2026-09-17T00:00:00+00:00"
}
diff --git a/packages/core/openexecutive/config.py b/packages/core/openexecutive/config.py
index 4ba2df71..fc29c28f 100644
--- a/packages/core/openexecutive/config.py
+++ b/packages/core/openexecutive/config.py
@@ -2,7 +2,7 @@ import re
from pathlib import Path
from typing import Annotated, Any, Literal
-from pydantic import Field, field_validator, model_validator
+from pydantic import Field, PrivateAttr, field_validator, model_validator
from pydantic_settings import BaseSettings, NoDecode, SettingsConfigDict
# Walk up from this file to find the repo root .env. If no .env exists
@@ -468,12 +468,10 @@ class Settings(BaseSettings):
# Left unset, this is inferred from the presence of mcp_servers_config_path
# (see _resolve_mcp). Set explicitly, the explicit value always wins.
mcp_enabled: bool = Field(False, alias="MCP_ENABLED")
- # Derived, not configured: _resolve_mcp overwrites this on every load. True
- # when MCP is on ONLY because the config file exists. The API lifespan
- # reports it when MCP then fails to come up — an operator who never set
- # MCP_ENABLED has to be told the file is what turned MCP on, which is the
- # diagnosis #122 cost 15 container restarts and a read of this file.
- mcp_auto_enabled: bool = Field(False, alias="MCP_AUTO_ENABLED")
+ # Whether mcp_enabled above came from the environment rather than from
+ # _resolve_mcp's inference. A private attr, not a field: it is derived on
+ # every load, so an env var for it would only ever be discarded.
+ _mcp_enabled_explicit: bool = PrivateAttr(default=False)
# ---- Calendar booking (first-climb autonomy, Build 1) ------------------
# When true, the `create_calendar_event` / `cancel_calendar_event` tools
@@ -815,30 +813,52 @@ class Settings(BaseSettings):
if not self.mcp_servers_config_path.is_absolute():
self.mcp_servers_config_path = Path.cwd() / self.mcp_servers_config_path
# Convenience for people who never touch the var: dropping an
- # mcp_servers.json next to profile.yaml is enough to turn MCP on.
- # An EXPLICIT setting always wins, in both directions.
- #
- # `model_fields_set` carries the field names the env/init actually
- # supplied, which is what separates "never set" from "set to false".
- # The plain `not self.mcp_enabled` this used to test could not tell
- # them apart, so the config file's presence silently overrode
- # MCP_ENABLED=false and there was no way to say "the file exists but I
- # do not want MCP running" short of moving it (#122).
- # `env_ignore_empty` means a bare `MCP_ENABLED=` in .env reads as
- # unset, which is the intent.
- #
- # Read it BEFORE the assignment below: pydantic adds a field to
- # `model_fields_set` on assignment too, so once this validator has
- # auto-enabled MCP the set no longer distinguishes the two cases for
- # anyone downstream. That is what `mcp_auto_enabled` records.
- explicit = "mcp_enabled" in self.model_fields_set
- self.mcp_auto_enabled = (
- not explicit and self.mcp_servers_config_path.exists()
- )
- if self.mcp_auto_enabled:
+ # mcp_servers.json next to profile.yaml turns MCP on. An EXPLICIT
+ # setting wins in both directions — `model_fields_set` holds the fields
+ # the env/init actually supplied, which is what separates "never set"
+ # from "set to false" (the `not self.mcp_enabled` this used to test
+ # could not, so the file silently overrode MCP_ENABLED=false — #122).
+ # Read it BEFORE assigning mcp_enabled below: pydantic adds a field to
+ # that set on assignment too. See architecture-facts.yaml →
+ # integrations → mcp_gateway for the full note.
+ self._mcp_enabled_explicit = "mcp_enabled" in self.model_fields_set
+ if not self._mcp_enabled_explicit and mcp_config_file_present(
+ self.mcp_servers_config_path
+ ):
self.mcp_enabled = True
return self
+ @property
+ def mcp_auto_enabled(self) -> bool:
+ """True when MCP is on ONLY because the config file exists.
+
+ The API lifespan reports this when MCP then fails to come up: an
+ operator who never set MCP_ENABLED has to be told that the file is what
+ turned MCP on, which is the diagnosis #122 cost 15 container restarts
+ and a read of this module.
+ """
+ return self.mcp_enabled and not self._mcp_enabled_explicit
+
+
+def mcp_config_file_present(config_path: Path) -> bool:
+ """Whether `config_path` is a regular file, without ever raising.
+
+ `Path.is_file` / `Path.exists` re-raise any OSError outside (ENOENT,
+ ENOTDIR, EBADF, ELOOP), so an EACCES on a parent directory whose ownership
+ does not match the container user propagates rather than answering False.
+ Raised from inside `_resolve_mcp` that means out of `Settings()` itself,
+ and `api/main.py` builds the app at module level — so it is an IMPORT-time
+ crash: #122's restart loop again, with even less to read. A path we cannot
+ stat is treated as absent.
+
+ `is_file` rather than `exists` so a directory at the config path counts as
+ absent too. It is not a config, and it used to be enough to auto-enable MCP.
+ """
+ try:
+ return config_path.is_file()
+ except (OSError, ValueError):
+ return False
+
def get_settings() -> Settings:
return Settings() # type: ignore[call-arg]
diff --git a/packages/core/openexecutive/orchestrator/mcp_gateway.py b/packages/core/openexecutive/orchestrator/mcp_gateway.py
index 69f63dd6..03fb4e1d 100644
--- a/packages/core/openexecutive/orchestrator/mcp_gateway.py
+++ b/packages/core/openexecutive/orchestrator/mcp_gateway.py
@@ -10,7 +10,7 @@ from email.utils import getaddresses
from pathlib import Path
from typing import Any
-from openexecutive.config import get_settings
+from openexecutive.config import get_settings, mcp_config_file_present
logger = logging.getLogger(__name__)
@@ -580,26 +580,64 @@ def _record_email_outbound_context(arguments: dict[str, Any]) -> None:
)
+# Ceiling on the MCP config we will read into memory. The real file is a
+# handful of server entries; anything past this is a mistake or a symlink to
+# something that is not a config, and reading it during startup is how you get
+# the boot hang this function exists to prevent.
+_MAX_CONFIG_BYTES = 1 << 20 # 1 MiB
+
+
def configured_server_names(config_path: Path) -> list[str]:
"""Names the MCP config at `config_path` defines under `mcpServers`.
- Empty when the file is absent, unreadable, not a JSON object, or defines no
- servers. Callers use this to decide whether starting the gateway can
- accomplish anything: extensible-mcp's own config loader ends with
+ Empty when the file is absent, unreadable, oversized, not a JSON object, or
+ defines no servers. Callers use this to decide whether starting the gateway
+ can accomplish anything: extensible-mcp's own config loader ends with
`ValueError("Config must define at least one server in 'mcpServers'")` and
exits, and because the child is already gone by then the only thing that
reaches us is anyio's "Attempted to exit cancel scope in a different task"
from `stdio_client` unwinding — a traceback that names nothing about
configuration (#122). Checking first is what makes the failure legible.
+
+ That an empty `mcpServers` is fatal to the child rather than merely idle is
+ confirmed in #122 by the maintainer reading extensible-mcp's own
+ `load_config`, so skipping the gateway here removes no working
+ configuration: a "servers are added at runtime via load_mcp_server" config
+ never brought the gateway up either. It only makes the failure legible.
+
+ NEVER RAISES, and the breadth of the `except` is deliberate: this reads an
+ operator-owned path during startup, where an exception is the crash loop
+ #122 was filed for rather than a bug report. Nothing here is subtle enough
+ to be worth a narrower catch — `json.loads` answers deeply-nested input
+ with `RecursionError`, which is not a `ValueError`, and a read can fail in
+ as many ways as the filesystem has moods. `mcp_config_file_present` keeps a
+ directory or a symlink to a FIFO from ever being opened.
+
+ Every key under `mcpServers` counts as a server, `_comment` included. That
+ is deliberate: a stray key there is a misconfiguration worth surfacing as a
+ server name in the log, not one worth hiding.
"""
- if not config_path.exists():
+ if not mcp_config_file_present(config_path):
return []
try:
- raw = json.loads(config_path.read_text())
- except (OSError, ValueError):
+ # Bounded read rather than stat-then-read: a stat cannot bind what a
+ # later read returns (a file that grows in between, or a /proc-style
+ # file reporting size 0), and one byte past the ceiling is all it takes
+ # to know we are over it.
+ with config_path.open("rb") as fh:
+ blob = fh.read(_MAX_CONFIG_BYTES + 1)
+ if len(blob) > _MAX_CONFIG_BYTES:
+ logger.warning(
+ "MCP config %s is larger than the %d-byte ceiling; treating it "
+ "as defining no servers",
+ config_path, _MAX_CONFIG_BYTES,
+ )
+ return []
+ raw = json.loads(blob)
+ except Exception:
logger.warning(
- "MCP config %s is not readable as JSON; treating it as defining "
- "no servers", config_path,
+ "MCP config %s could not be read as JSON; treating it as defining "
+ "no servers", config_path, exc_info=True,
)
return []
servers = raw.get("mcpServers") if isinstance(raw, dict) else None
diff --git a/packages/core/tests/unit/test_mcp_enablement.py b/packages/core/tests/unit/test_mcp_enablement.py
index a38c2f82..5fc0beb5 100644
--- a/packages/core/tests/unit/test_mcp_enablement.py
+++ b/packages/core/tests/unit/test_mcp_enablement.py
@@ -8,15 +8,18 @@ whose only symptom was a healthcheck that never passed.
from __future__ import annotations
import asyncio
+import errno
import json
import logging
+import os
from collections.abc import Iterator
from pathlib import Path
from typing import Any
-from unittest.mock import AsyncMock, MagicMock
+from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from openexecutive.api import main as main_mod
from openexecutive.api.main import _start_mcp_gateway
from openexecutive.config import Settings
from openexecutive.orchestrator.mcp_gateway import configured_server_names
@@ -172,14 +175,55 @@ def test_missing_config_file_reads_as_no_servers(tmp_path: Path) -> None:
assert configured_server_names(tmp_path / "absent.json") == []
-def test_unreadable_config_file_reads_as_no_servers(tmp_path: Path) -> None:
- """A directory at the config path raises OSError rather than a JSON error."""
+def test_a_directory_at_the_config_path_reads_as_no_servers(tmp_path: Path) -> None:
config = tmp_path / "mcp.json"
config.mkdir()
assert configured_server_names(config) == []
+def test_a_fifo_at_the_config_path_is_never_opened(tmp_path: Path) -> None:
+ """Reading a FIFO blocks forever. `is_file()` rejects it before the open,
+ so this test completing at all is the assertion."""
+ config = tmp_path / "mcp.json"
+ os.mkfifo(config)
+
+ assert configured_server_names(config) == []
+
+
+def test_an_oversized_config_reads_as_no_servers(tmp_path: Path) -> None:
+ config = tmp_path / "mcp.json"
+ config.write_text(" " * (1024 * 1024 + 1))
+
+ assert configured_server_names(config) == []
+
+
+def test_deeply_nested_json_reads_as_no_servers(tmp_path: Path) -> None:
+ """`json.loads` answers this with RecursionError, which is NOT a
+ ValueError — a narrower `except (OSError, ValueError)` lets it through and
+ it propagates out of the lifespan, killing the container (#122's own
+ failure mode)."""
+ config = tmp_path / "mcp.json"
+ depth = 100_000
+ config.write_text("[" * depth + "]" * depth)
+
+ assert configured_server_names(config) == []
+
+
+def test_a_stat_failure_reads_as_no_servers(tmp_path: Path) -> None:
+ """`Path.is_file` re-raises any OSError outside (ENOENT, ENOTDIR, EBADF,
+ ELOOP), so an EACCES on a parent directory whose ownership does not match
+ the container user reaches us. Injected rather than chmod-ed: the test
+ suite often runs as root, where chmod 000 does not deny traversal."""
+ config = tmp_path / "mcp.json"
+ config.write_text(json.dumps({"mcpServers": {"gw": {}}}))
+
+ with patch.object(
+ Path, "is_file", side_effect=PermissionError(errno.EACCES, "denied")
+ ):
+ assert configured_server_names(config) == []
+
+
# ---------------------------------------------------------------------------
# _start_mcp_gateway — a gateway failure must not take the container down
# ---------------------------------------------------------------------------
@@ -290,9 +334,9 @@ def test_warning_names_the_config_file_as_the_cause_when_auto_enabled(
def test_explicitly_enabled_is_not_reported_as_auto_enabled(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, oe_logs: list[str]
) -> None:
- """The mirror of the test above, and the one that catches the trap: the
- validator's own `self.mcp_enabled = True` lands in `model_fields_set`, so
- reading that set downstream reports every auto-enable as explicit."""
+ """The mirror of the test above. Note it is that one, not this one, that
+ pins the `model_fields_set` trap — this case sets MCP_ENABLED=true, so it
+ passes either way."""
_stub_gateway(monkeypatch, None)
settings = _mcp_settings(tmp_path, monkeypatch, json.dumps({"mcpServers": {}}))
assert settings.mcp_auto_enabled is False
@@ -343,3 +387,152 @@ def test_mcp_disabled_starts_nothing(
assert task is None
assert app.state.mcp_gateway is None
gateway.start.assert_not_awaited()
+
+
+def test_settings_survive_a_config_path_it_cannot_stat(
+ monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """`Path.is_file` re-raises an EACCES on a parent directory, and this probe
+ runs inside a model validator — so it would come out of `Settings()`
+ itself. `api/main.py` builds the app at module level, making that an
+ import-time crash rather than a degraded boot."""
+ with patch.object(
+ Path, "is_file", side_effect=PermissionError(errno.EACCES, "denied")
+ ):
+ settings = _settings(
+ monkeypatch, MCP_SERVERS_CONFIG_PATH="/restricted/mcp_servers.json"
+ )
+
+ assert settings.mcp_enabled is False
+ assert settings.mcp_auto_enabled is False
+
+
+def test_a_directory_at_the_config_path_does_not_enable_mcp(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ config = tmp_path / "mcp_servers.json"
+ config.mkdir()
+
+ settings = _settings(monkeypatch, MCP_SERVERS_CONFIG_PATH=str(config))
+
+ assert settings.mcp_enabled is False
+
+
+def test_an_anyio_exception_group_is_contained(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, oe_logs: list[str]
+) -> None:
+ """The shape #122's traceback actually had. anyio wraps a task group's
+ failures in `BaseExceptionGroup` as soon as one is a `BaseException` such
+ as `CancelledError`, and that group is NOT an `Exception` — so a plain
+ `except Exception` lets through the one shape this guard exists for."""
+ gateway, set_active = _stub_gateway(
+ monkeypatch,
+ BaseExceptionGroup(
+ "unhandled errors in a TaskGroup",
+ [
+ RuntimeError(
+ "Attempted to exit cancel scope in a different task than "
+ "it was entered in"
+ ),
+ asyncio.CancelledError(),
+ ],
+ ),
+ )
+ settings = _mcp_settings(
+ tmp_path, monkeypatch, json.dumps({"mcpServers": {"google_workspace": {}}})
+ )
+ app = _FakeApp()
+
+ task = asyncio.run(_start_mcp_gateway(app, settings)) # type: ignore[arg-type]
+
+ assert task is None
+ assert app.state.mcp_gateway is None
+ set_active.assert_not_called()
+ gateway.close.assert_awaited_once()
+ assert "google_workspace" in "\n".join(oe_logs)
+
+
+def test_a_teardown_that_also_fails_is_contained(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, oe_logs: list[str]
+) -> None:
+ """`close()` runs from inside the `except` block, so anything it raises
+ replaces the actionable log with the crash that log exists to prevent —
+ the worst outcome, because the operator sees the right message and the
+ container dies anyway."""
+ gateway, _ = _stub_gateway(monkeypatch, RuntimeError("start failed"))
+ gateway.close = AsyncMock(
+ side_effect=BaseExceptionGroup("g", [asyncio.CancelledError()])
+ )
+ settings = _mcp_settings(
+ tmp_path, monkeypatch, json.dumps({"mcpServers": {"gw": {}}})
+ )
+
+ task = asyncio.run(_start_mcp_gateway(_FakeApp(), settings)) # type: ignore[arg-type]
+
+ assert task is None
+ assert "did not finish cleanly" in "\n".join(oe_logs)
+
+
+def test_a_silent_child_times_out_instead_of_hanging_the_boot(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, oe_logs: list[str]
+) -> None:
+ """`MCPGateway.start` builds `ClientSession` with no
+ `read_timeout_seconds`, so `initialize()` waits forever on a child that is
+ alive but silent. An unbounded wait here means the lifespan never yields
+ and the healthcheck never passes — #122's symptom, which no `except` can
+ see."""
+ async def _never_returns(_path: Path) -> None:
+ await asyncio.Event().wait()
+
+ gateway, set_active = _stub_gateway(monkeypatch, None)
+ gateway.start = AsyncMock(side_effect=_never_returns)
+ monkeypatch.setattr(main_mod, "_MCP_START_TIMEOUT_S", 0.05)
+ settings = _mcp_settings(
+ tmp_path, monkeypatch, json.dumps({"mcpServers": {"gw": {}}})
+ )
+ app = _FakeApp()
+
+ task = asyncio.run(_start_mcp_gateway(app, settings)) # type: ignore[arg-type]
+
+ assert task is None
+ assert app.state.mcp_gateway is None
+ set_active.assert_not_called()
+ assert "failed to start within" in "\n".join(oe_logs)
+
+
+def test_a_real_cancellation_is_not_swallowed(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """`except BaseException` must not eat the lifespan's own cancellation —
+ a bare `CancelledError` in our frame means shut down, not degrade."""
+ _stub_gateway(monkeypatch, asyncio.CancelledError())
+ settings = _mcp_settings(
+ tmp_path, monkeypatch, json.dumps({"mcpServers": {"gw": {}}})
+ )
+
+ with pytest.raises(asyncio.CancelledError):
+ asyncio.run(_start_mcp_gateway(_FakeApp(), settings)) # type: ignore[arg-type]
+
+
+def test_the_no_servers_remedy_tracks_why_mcp_was_on(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, oe_logs: list[str]
+) -> None:
+ """With MCP_ENABLED=true and a path that is not a file, the old single
+ message said the file "defines no servers" and told the operator to set
+ MCP_ENABLED=false "to stop the file from enabling MCP" — in the same
+ sentence as "MCP_ENABLED was set explicitly"."""
+ _stub_gateway(monkeypatch, None)
+ settings = _settings(
+ monkeypatch,
+ MCP_ENABLED="true",
+ MCP_SERVERS_CONFIG_PATH=str(tmp_path / "typo.json"),
+ )
+
+ asyncio.run(_start_mcp_gateway(_FakeApp(), settings)) # type: ignore[arg-type]
+
+ logged = "\n".join(oe_logs)
+ assert "is not a readable file" in logged
+ assert "MCP_SERVERS_CONFIG_PATH" in logged
+ assert "stop the file from enabling MCP" not in logged
+ assert "defines no servers" not in logged
+