Skip to content

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

Honour an explicit MCP_ENABLED=false, and stop an MCP failure killing the API

Rufus0228e7268343
diff --git a/.env.example b/.env.example
index 84dbbcca..dec19fc7 100644
--- a/.env.example
+++ b/.env.example
@@ -213,6 +213,19 @@ GOOGLE_CHAT_SERVICE_ACCOUNT_EMAIL= # Option B: SA email for impersonation via
GOOGLE_OAUTH_CLIENT_ID=
GOOGLE_OAUTH_CLIENT_SECRET=
+# MCP gateway (the client side — external MCP servers surfaced as Executive
+# tools, including the Google Workspace one configured above).
+# Left unset, MCP turns itself on when MCP_SERVERS_CONFIG_PATH exists, so
+# copying mcp_servers.json.example into place is all that is needed. Set it
+# 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.
+# MCP_ENABLED=false
+# MCP_SERVERS_CONFIG_PATH=./company/mcp_servers.json
+
# Outbound DM anti-spam guard (optional tuning)
# Applied at the send-tool chokepoint: a proactive Slack/Telegram/Discord DM is
# suppressed (and audited) when it would exceed the per-recipient rate cap,
diff --git a/docs/deployment.md b/docs/deployment.md
index 289b2169..40c16206 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -51,7 +51,7 @@ One volume, mounted at `/data`:
- `/data/chroma_db/` — ChromaDB vector index (built-in knowledge + uploaded company docs)
- `/data/episodic_memory.db` — SQLite: episodic memory, people, alerts, scheduled actions, audit log
- `/data/company/profile.yaml` + `/data/company/docs/` — onboarding output + uploaded docs
-- `/data/company/mcp_servers.json` — MCP gateway config
+- `/data/company/mcp_servers.json` — MCP gateway config. Placing this file is what **enables** MCP when `MCP_ENABLED` is unset; set `MCP_ENABLED=false` to keep MCP off with the file in place. A config defining no servers under `mcpServers`, or a gateway that fails to start, is logged and skipped — the API boots without MCP tools (and without the email poller) rather than failing to boot.
- `/data/google_credentials/` — Google Workspace OAuth token, if that integration is enabled
Nothing hardcodes those paths. Each is an env var, and the defaults are
diff --git a/packages/core/openexecutive/api/main.py b/packages/core/openexecutive/api/main.py
index 91e34f8e..b194e1dc 100644
--- a/packages/core/openexecutive/api/main.py
+++ b/packages/core/openexecutive/api/main.py
@@ -8,7 +8,7 @@ import os
import sys
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
-from typing import Any
+from typing import TYPE_CHECKING, Any
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
@@ -50,6 +50,9 @@ from openexecutive.api.routes import (
from openexecutive.integrations.google_chat import router as google_chat_router
from openexecutive.integrations.telegram_bot import router as telegram_router
+if TYPE_CHECKING:
+ from openexecutive.config import Settings
+
class _OELogFormatter(logging.Formatter):
"""Compact, scannable formatter for openexecutive logs.
@@ -144,6 +147,72 @@ _UNAUTHENTICATED_PATHS: frozenset[str] = frozenset(
)
+async def _start_mcp_gateway(
+ app: FastAPI, settings: Settings
+) -> asyncio.Task[None] | None:
+ """Bring the MCP gateway up, or leave MCP off and say why.
+
+ 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.
+ """
+ app.state.mcp_gateway = None
+ if not settings.mcp_enabled:
+ return None
+
+ from openexecutive.orchestrator.mcp_gateway import (
+ MCPGateway,
+ configured_server_names,
+ set_active_gateway,
+ )
+
+ log = logging.getLogger("openexecutive")
+ config_path = settings.mcp_servers_config_path
+ 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.
+ why = (
+ "auto-enabled by the presence of the config file"
+ if settings.mcp_auto_enabled
+ 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,
+ )
+ return None
+
+ gateway = MCPGateway()
+ try:
+ await gateway.start(config_path)
+ except Exception:
+ 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,
+ )
+ await gateway.close()
+ return None
+
+ app.state.mcp_gateway = gateway
+ set_active_gateway(gateway)
+
+ from openexecutive.integrations.email_poller import run_email_poller
+ return asyncio.create_task(run_email_poller(gateway))
+
+
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
from openexecutive.alerts.store import initialize_db as initialize_alerts_db
@@ -393,18 +462,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
discord_bot: Any = None
discord_bot_task: asyncio.Task[None] | None = None
- if settings.mcp_enabled:
- from openexecutive.orchestrator.mcp_gateway import MCPGateway, set_active_gateway
-
- gateway = MCPGateway()
- await gateway.start(settings.mcp_servers_config_path)
- app.state.mcp_gateway = gateway
- set_active_gateway(gateway)
-
- from openexecutive.integrations.email_poller import run_email_poller
- email_poller_task = asyncio.create_task(run_email_poller(gateway))
- else:
- app.state.mcp_gateway = None
+ email_poller_task = await _start_mcp_gateway(app, settings)
if settings.scheduler_enabled:
from openexecutive.scheduler import run_scheduler
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index 5933bc77..13be4544 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -2919,6 +2919,48 @@ integrations:
INVARIANT: anything the subprocess needs from the environment must be added
to _FORWARDED_ENV_VARS — parent env is otherwise invisible to it.
+ Enablement (config._resolve_mcp): MCP_ENABLED left unset is INFERRED from
+ the presence of mcp_servers_config_path, so dropping an mcp_servers.json
+ next to profile.yaml turns MCP on with no further configuration. An
+ EXPLICIT setting wins in both directions — MCP_ENABLED=false keeps MCP off
+ with the file still in place. This needs care: the validator used to test
+ `not self.mcp_enabled`, which cannot distinguish "never set" from "set to
+ false", so the file's presence silently overrode an operator who had asked
+ 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
+ model_fields_set — the field names the env/init actually supplied — and
+ records the outcome on the derived Settings field mcp_auto_enabled.
+ 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
+ to know "was this explicit?" reads mcp_auto_enabled, never
+ model_fields_set.
+
+ Startup is BEST-EFFORT, in api.main._start_mcp_gateway (extracted from the
+ lifespan so it is unit-testable). It never raises. Two checks run before
+ the subprocess is spawned: MCP off is a no-op, and a config that defines no
+ servers under mcpServers is logged at WARNING and skipped — gateway not
+ started. That empty-config case is why the crash existed: extensible-mcp's
+ load_config ends with ValueError("Config must define at least one server in
+ 'mcpServers'") and the child exits, so the only thing reaching us is anyio's
+ "Attempted to exit cancel scope in a different task than it was entered in"
+ 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.
+ 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,
+ set_active_gateway is NOT called, and the email poller (which rides on the
+ gateway) is not started. The API then boots without MCP tools.
+ INVARIANT: an MCP failure must never propagate out of the lifespan. It used
+ to, which kills the container — under `restart: unless-stopped` that is a
+ crash loop whose only outward symptom is a healthcheck that never passes
+ (#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.
+
Egress gating: MCPGateway.call_tool intercepts three tool families before
delegating to the MCP subprocess. All three resolve the allow-list from the
shared _roster_allow_set() helper (People roster emails + the exec address):
diff --git a/packages/core/openexecutive/architecture/prebuilt/integrations.json b/packages/core/openexecutive/architecture/prebuilt/integrations.json
index a48ca524..a1d902b6 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. 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. 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.",
"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-16T12:39:20.262413+00:00"
+ "generated_at": "2026-09-17T00:00:00+00:00"
}
diff --git a/packages/core/openexecutive/config.py b/packages/core/openexecutive/config.py
index 4a757d12..4ba2df71 100644
--- a/packages/core/openexecutive/config.py
+++ b/packages/core/openexecutive/config.py
@@ -465,7 +465,15 @@ class Settings(BaseSettings):
mcp_servers_config_path: Path = Field(
_ROOT / "company" / "mcp_servers.json", alias="MCP_SERVERS_CONFIG_PATH"
)
+ # 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")
# ---- Calendar booking (first-climb autonomy, Build 1) ------------------
# When true, the `create_calendar_event` / `cancel_calendar_event` tools
@@ -806,7 +814,28 @@ class Settings(BaseSettings):
def _resolve_mcp(self) -> "Settings":
if not self.mcp_servers_config_path.is_absolute():
self.mcp_servers_config_path = Path.cwd() / self.mcp_servers_config_path
- if not self.mcp_enabled and self.mcp_servers_config_path.exists():
+ # 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:
self.mcp_enabled = True
return self
diff --git a/packages/core/openexecutive/orchestrator/mcp_gateway.py b/packages/core/openexecutive/orchestrator/mcp_gateway.py
index a8fe2749..69f63dd6 100644
--- a/packages/core/openexecutive/orchestrator/mcp_gateway.py
+++ b/packages/core/openexecutive/orchestrator/mcp_gateway.py
@@ -580,6 +580,34 @@ def _record_email_outbound_context(arguments: dict[str, Any]) -> None:
)
+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
+ `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.
+ """
+ if not config_path.exists():
+ return []
+ try:
+ raw = json.loads(config_path.read_text())
+ except (OSError, ValueError):
+ logger.warning(
+ "MCP config %s is not readable as JSON; treating it as defining "
+ "no servers", config_path,
+ )
+ return []
+ servers = raw.get("mcpServers") if isinstance(raw, dict) else None
+ if not isinstance(servers, dict):
+ return []
+ return sorted(str(name) for name in servers)
+
+
class MCPGateway:
"""Proxies search_tools / call_tool / load_mcp_server to an extensible-mcp subprocess.
diff --git a/packages/core/tests/unit/test_mcp_enablement.py b/packages/core/tests/unit/test_mcp_enablement.py
new file mode 100644
index 00000000..a38c2f82
--- /dev/null
+++ b/packages/core/tests/unit/test_mcp_enablement.py
@@ -0,0 +1,345 @@
+"""MCP enablement and gateway-startup degradation (#122).
+
+`_resolve_mcp` had no coverage at all, which is how the config file's presence
+came to silently override an explicit `MCP_ENABLED=false` — and, because the
+API lifespan started the gateway with no try/except, crash-loop a container
+whose only symptom was a healthcheck that never passed.
+"""
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+from collections.abc import Iterator
+from pathlib import Path
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from openexecutive.api.main import _start_mcp_gateway
+from openexecutive.config import Settings
+from openexecutive.orchestrator.mcp_gateway import configured_server_names
+
+
+def oe_logs() -> Iterator[list[str]]:
+ """Rendered messages from the ``openexecutive`` logger.
+
+ ``caplog`` listens on the root logger and would miss these: the app's
+ logging config (``main._configure_logging``, exercised by other tests in
+ the suite) sets ``propagate = False`` on the ``openexecutive`` tree so
+ uvicorn's dictConfig cannot clobber it. Attach to that logger directly.
+ """
+ messages: list[str] = []
+
+ class _Collect(logging.Handler):
+ def emit(self, record: logging.LogRecord) -> None:
+ messages.append(record.getMessage())
+
+ logger = logging.getLogger("openexecutive")
+ handler = _Collect(level=logging.DEBUG)
+ prior_level = logger.level
+ logger.addHandler(handler)
+ logger.setLevel(logging.DEBUG)
+ try:
+ yield messages
+ finally:
+ logger.removeHandler(handler)
+ logger.setLevel(prior_level)
+
+
+# ---------------------------------------------------------------------------
+# Settings._resolve_mcp — explicit beats inferred
+# ---------------------------------------------------------------------------
+
+
+def _settings(monkeypatch: pytest.MonkeyPatch, **env: str) -> Settings:
+ """Build Settings with MCP env controlled, ignoring the developer's .env.
+
+ `Settings` reads `.env` as well as the process env, so a real
+ `MCP_ENABLED` in the repo root would decide these tests. Point the
+ env_file at a path that does not exist.
+ """
+ monkeypatch.delenv("MCP_ENABLED", raising=False)
+ monkeypatch.delenv("MCP_SERVERS_CONFIG_PATH", raising=False)
+ for key, value in env.items():
+ monkeypatch.setenv(key, value)
+ return Settings(_env_file=None) # type: ignore[call-arg]
+
+
+def test_explicit_false_survives_an_existing_config_file(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The regression this issue was filed for.
+
+ `mcp_servers.json` is the natural thing to ship alongside `profile.yaml`
+ and `docs/deployment.md` lists it under persistent state, so the file
+ being present is not consent to run MCP.
+ """
+ config = tmp_path / "mcp_servers.json"
+ config.write_text(json.dumps({"mcpServers": {"gw": {"command": "x"}}}))
+
+ settings = _settings(
+ monkeypatch, MCP_ENABLED="false", MCP_SERVERS_CONFIG_PATH=str(config)
+ )
+
+ assert settings.mcp_enabled is False
+
+
+def test_unset_is_inferred_from_the_config_file(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The convenience path is kept for people who never touch the var."""
+ config = tmp_path / "mcp_servers.json"
+ config.write_text(json.dumps({"mcpServers": {"gw": {"command": "x"}}}))
+
+ settings = _settings(monkeypatch, MCP_SERVERS_CONFIG_PATH=str(config))
+
+ assert settings.mcp_enabled is True
+
+
+def test_unset_with_no_config_file_stays_off(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ settings = _settings(
+ monkeypatch, MCP_SERVERS_CONFIG_PATH=str(tmp_path / "absent.json")
+ )
+
+ assert settings.mcp_enabled is False
+
+
+def test_explicit_true_survives_a_missing_config_file(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Explicit wins in both directions — the lifespan reports the miss."""
+ settings = _settings(
+ monkeypatch,
+ MCP_ENABLED="true",
+ MCP_SERVERS_CONFIG_PATH=str(tmp_path / "absent.json"),
+ )
+
+ assert settings.mcp_enabled is True
+
+
+def test_relative_config_path_is_resolved_against_cwd(
+ monkeypatch: pytest.MonkeyPatch
+) -> None:
+ settings = _settings(monkeypatch, MCP_SERVERS_CONFIG_PATH="company/mcp.json")
+
+ assert settings.mcp_servers_config_path.is_absolute()
+ assert settings.mcp_servers_config_path == Path.cwd() / "company/mcp.json"
+
+
+# ---------------------------------------------------------------------------
+# configured_server_names — "nothing to do" is knowable before we spawn
+# ---------------------------------------------------------------------------
+
+
+def test_server_names_are_returned_sorted(tmp_path: Path) -> None:
+ config = tmp_path / "mcp.json"
+ config.write_text(
+ json.dumps({"mcpServers": {"zulu": {}, "alpha": {}}, "filters": {}})
+ )
+
+ assert configured_server_names(config) == ["alpha", "zulu"]
+
+
+ "body",
+ [
+ pytest.param(json.dumps({"mcpServers": {}}), id="empty-mcpservers"),
+ pytest.param(json.dumps({"filters": {}}), id="no-mcpservers-key"),
+ pytest.param(json.dumps({"mcpServers": []}), id="mcpservers-not-an-object"),
+ pytest.param(json.dumps(["gw"]), id="root-not-an-object"),
+ pytest.param("{not json", id="malformed-json"),
+ pytest.param("", id="empty-file"),
+ ],
+)
+def test_configs_with_nothing_to_start_read_as_no_servers(
+ tmp_path: Path, body: str
+) -> None:
+ """The reporter's case is `empty-mcpservers`: extensible-mcp raises
+ ValueError on it and exits, and all that reaches us is an anyio
+ cancel-scope error naming nothing about configuration."""
+ config = tmp_path / "mcp.json"
+ config.write_text(body)
+
+ assert configured_server_names(config) == []
+
+
+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."""
+ config = tmp_path / "mcp.json"
+ config.mkdir()
+
+ assert configured_server_names(config) == []
+
+
+# ---------------------------------------------------------------------------
+# _start_mcp_gateway — a gateway failure must not take the container down
+# ---------------------------------------------------------------------------
+
+
+class _FakeApp:
+ def __init__(self) -> None:
+ self.state = MagicMock()
+
+
+def _stub_gateway(
+ monkeypatch: pytest.MonkeyPatch, start: Any
+) -> tuple[MagicMock, MagicMock]:
+ """Swap MCPGateway for a stub whose `start` does `start`, and capture the
+ active-gateway singleton and email-poller calls."""
+ gateway = MagicMock()
+ gateway.start = AsyncMock(side_effect=start)
+ gateway.close = AsyncMock()
+ set_active = MagicMock()
+
+ monkeypatch.setattr(
+ "openexecutive.orchestrator.mcp_gateway.MCPGateway",
+ MagicMock(return_value=gateway),
+ )
+ monkeypatch.setattr(
+ "openexecutive.orchestrator.mcp_gateway.set_active_gateway", set_active
+ )
+
+ async def _never_ending_poller(_gateway: Any) -> None:
+ await asyncio.Event().wait()
+
+ monkeypatch.setattr(
+ "openexecutive.integrations.email_poller.run_email_poller",
+ _never_ending_poller,
+ )
+ return gateway, set_active
+
+
+def _mcp_settings(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, body: str) -> Settings:
+ config = tmp_path / "mcp_servers.json"
+ config.write_text(body)
+ return _settings(
+ monkeypatch, MCP_ENABLED="true", MCP_SERVERS_CONFIG_PATH=str(config)
+ )
+
+
+def test_gateway_failure_leaves_the_app_bootable(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, oe_logs: list[str]
+) -> None:
+ """The crash loop: this exception used to propagate out of the lifespan and
+ kill the container. It must be logged and swallowed instead."""
+ gateway, set_active = _stub_gateway(
+ monkeypatch,
+ RuntimeError("Attempted to exit cancel scope in a different task"),
+ )
+ 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, "no email poller should ride on a gateway that is down"
+ assert app.state.mcp_gateway is None
+ set_active.assert_not_called()
+ # The half-started subprocess and stdio context have to be reaped.
+ gateway.close.assert_awaited_once()
+ # The log has to carry what the anyio traceback did not: the config path
+ # and the servers it named.
+ logged = "\n".join(oe_logs)
+ assert str(settings.mcp_servers_config_path) in logged
+ assert "google_workspace" in logged
+
+
+def test_gateway_is_not_started_when_no_servers_are_configured(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, oe_logs: list[str]
+) -> None:
+ gateway, set_active = _stub_gateway(monkeypatch, None)
+ settings = _mcp_settings(tmp_path, monkeypatch, json.dumps({"mcpServers": {}}))
+
+ task = asyncio.run(_start_mcp_gateway(_FakeApp(), settings)) # type: ignore[arg-type]
+
+ assert task is None
+ gateway.start.assert_not_awaited()
+ set_active.assert_not_called()
+ assert "no servers" in "\n".join(oe_logs)
+
+
+def test_warning_names_the_config_file_as_the_cause_when_auto_enabled(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, oe_logs: list[str]
+) -> None:
+ """An operator who never set MCP_ENABLED needs to be told that the file is
+ what turned MCP on — that is the whole diagnosis the reporter had to read
+ config.py to reach."""
+ _stub_gateway(monkeypatch, None)
+ config = tmp_path / "mcp_servers.json"
+ config.write_text(json.dumps({"mcpServers": {}}))
+ settings = _settings(monkeypatch, MCP_SERVERS_CONFIG_PATH=str(config))
+ assert settings.mcp_auto_enabled is True
+
+ asyncio.run(_start_mcp_gateway(_FakeApp(), settings)) # type: ignore[arg-type]
+
+ logged = "\n".join(oe_logs)
+ assert "auto-enabled by the presence of the config file" in logged
+ assert "MCP_ENABLED=false" in logged, "tell them how to turn it off"
+
+
+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."""
+ _stub_gateway(monkeypatch, None)
+ settings = _mcp_settings(tmp_path, monkeypatch, json.dumps({"mcpServers": {}}))
+ assert settings.mcp_auto_enabled is False
+
+ asyncio.run(_start_mcp_gateway(_FakeApp(), settings)) # type: ignore[arg-type]
+
+ logged = "\n".join(oe_logs)
+ assert "MCP_ENABLED was set explicitly" in logged
+ assert "auto-enabled" not in logged
+
+
+def test_successful_start_wires_the_gateway_and_the_email_poller(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ gateway, set_active = _stub_gateway(monkeypatch, None)
+ settings = _mcp_settings(
+ tmp_path, monkeypatch, json.dumps({"mcpServers": {"google_workspace": {}}})
+ )
+ app = _FakeApp()
+
+ async def _run() -> asyncio.Task[None] | None:
+ task = await _start_mcp_gateway(app, settings) # type: ignore[arg-type]
+ if task is not None:
+ task.cancel()
+ return task
+
+ task = asyncio.run(_run())
+
+ assert task is not None
+ assert app.state.mcp_gateway is gateway
+ set_active.assert_called_once_with(gateway)
+ gateway.start.assert_awaited_once_with(settings.mcp_servers_config_path)
+
+
+def test_mcp_disabled_starts_nothing(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ gateway, _ = _stub_gateway(monkeypatch, None)
+ config = tmp_path / "mcp_servers.json"
+ config.write_text(json.dumps({"mcpServers": {"google_workspace": {}}}))
+ settings = _settings(
+ monkeypatch, MCP_ENABLED="false", MCP_SERVERS_CONFIG_PATH=str(config)
+ )
+ 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
+ gateway.start.assert_not_awaited()