How the OpenWork Connect-State System Manages MCP Server Connections Throughout the Workspace Lifecycle

The connect-state system persists host-level MCP configuration in connect-state.json, resolves workspace-specific connections via resolveConnectWorkspace, probes cloud health through resolveCloudHealth, and aggregates runtime diagnostics into a unified ConnectSnapshot that tracks availability across the entire workspace lifecycle.

The connect-state subsystem serves as the central orchestration layer for Model Context Protocol (MCP) server management in the OpenWork ecosystem. Located in apps/server/src/connect-state.ts within the different-ai/openwork repository, this system maintains the openwork-cloud connection status for both host-wide and per-workspace scopes. By decoupling persisted configuration from runtime workspace resolution, it enables reliable connection state management from application startup through active development sessions.

Core Architecture of the Connect-State System

Host-Level Persistence Layer

The foundation of the connect-state system rests on the CONNECT_STATE_FILE constant, which defines the path to connect-state.json. This JSON file stores whether Connect is enabled via connectEnabled and optional host-scoped MCP configuration. The persistConnectState and writeConnectState functions handle atomic updates to this file, including timestamp metadata for change tracking.

Safety boundaries prevent resource exhaustion: CONNECT_STATE_MAX_BYTES (16 KB) limits file sizes to avoid loading huge or malicious payloads. When reading, the readConnectState and inspectConnectState functions return diagnostic statuses (available, missing, invalid, unreadable) rather than throwing exceptions, allowing graceful degradation when files are corrupted or permission-denied.

Workspace Resolution Engine

Given a workspace ID or exact OpenCode directory, the resolveConnectWorkspace function locates matching WorkspaceInfo or reports ambiguity. This resolution is critical when snapshots must bind to specific workspaces rather than global state. The function integrates with the workspace registry to validate directory paths and disambiguate duplicate names.

Cloud Health Probing

For active workspace connections, resolveCloudHealth initiates remote diagnostics by calling readOpenworkCloudMcpHealth (exported from cloud-mcp-health.ts). This probes the remote MCP endpoint for the resolved workspace and returns health metrics including usable status. The result merges into the final snapshot via getConnectSnapshot, setting cloudMcpPresent based on both persisted configuration and live health checks.

Lifecycle Management Phases

Application Startup and State Inspection

During server initialization, inspectConnectState attempts to read connect-state.json. If the file does not exist, the system defaults to a disabled state without error. This passive inspection provides immediate availability status while deferring expensive network operations until explicitly requested.

The getConnectSnapshot function aggregates multiple data sources: persisted host state, workspace resolution results, and cloud health status. This composite ConnectSnapshot enables UI components to render connection badges, enablement toggles, and diagnostic warnings based on a single data fetch.

Runtime Workspace Detection

When host-level MCP configuration is absent, the system falls back to inspectConnectRuntime. This function scans the runtime_opencode_configs database table for openwork-cloud entries across active workspaces. To prevent performance degradation, the scan respects CONNECT_SNAPSHOT_MAX_RUNTIME_ROWS (default 100), ensuring the operation completes quickly even with thousands of workspaces.

This bounded scan sets cloudMcpPresent to true if any workspace contains a local MCP configuration, avoiding unnecessary network calls while still detecting server-scoped connections. The runtimeConfigMaxBytes parameter provides additional protection against oversized configuration rows.

Legacy System Integration

The connect-state system handles edge cases through shouldGateLegacyGoogleWorkspace and googleWorkspaceStatusConnectExtra. These functions add contextual guidance when the legacy Google Workspace extension is disabled but Connect is enabled, ensuring users receive actionable connection instructions rather than silent failures.

Error Handling and Safety Boundaries

The subsystem implements defense-in-depth strategies for production reliability. File corruption triggers an invalid status rather than crashes, while I/O errors like ENOENT map to missing. Callers may provide an AbortSignal to any async operation; aborts propagate immediately through the promise chain, preventing wasted work during rapid state changes or client disconnections.

Database scanning protections include hard row limits and byte constraints. These boundaries ensure that getConnectSnapshot maintains sub-second latency regardless of workspace count or configuration size.

Code Implementation Examples

Reading the current Connect state (host-wide)

import { readConnectState } from "@/apps/server/src/connect-state";

const state = await readConnectState(serverConfig);
console.log(state.connectEnabled);   // true / false
console.log(state.cloudMcp);         // host-level MCP config or null

Enabling Connect for the host

import { writeConnectState } from "@/apps/server/src/connect-state";

await writeConnectState(serverConfig, { connectEnabled: true });

Getting a snapshot for a specific workspace

import { getConnectSnapshot } from "@/apps/server/src/connect-state";

const snapshot = await getConnectSnapshot(serverConfig, {
  workspaceId: "my-workspace",
  // or: directory: "/path/to/opencode/project"
});
console.log(snapshot.cloudMcpPresent);          // true if MCP config found
console.log(snapshot.cloudHealth?.usable);      // true if remote health OK

Inspecting the snapshot without network calls (passive diagnostics)

import { inspectConnectSnapshot } from "@/apps/server/src/connect-state";

const inspection = await inspectConnectSnapshot(serverConfig);
console.log(inspection.status);                 // e.g. "available"
console.log(inspection.snapshot.cloudMcpPresent);

Key Source Files

File Role
apps/server/src/connect-state.ts Core implementation of persisted state, workspace resolution, cloud health probing, and snapshot construction.
apps/server/src/connect-state.test.ts Validates per-workspace cloud health scoping and unknown directory handling.
apps/server/src/connect-state.inspect.test.ts Tests inspection logic, file-size limits, abort handling, and runtime-row bounding.

Summary

  • Host-level persistence uses connect-state.json managed by persistConnectState and writeConnectState, bounded by 16 KB size limits.
  • Workspace resolution occurs via resolveConnectWorkspace, supporting both ID and directory path lookups.
  • Cloud health validation happens through resolveCloudHealth calling readOpenworkCloudMcpHealth, merging results into ConnectSnapshot.
  • Runtime detection via inspectConnectRuntime scans the runtime_opencode_configs table with a hard limit of 100 rows (CONNECT_SNAPSHOT_MAX_RUNTIME_ROWS).
  • Safety mechanisms include AbortSignal propagation, corruption detection (invalid vs. unreadable statuses), and file size enforcement.
  • Unified aggregation through getConnectSnapshot provides the UI with cloudMcpPresent and cloudHealth flags for consistent connection state rendering.

Frequently Asked Questions

How does the connect-state system handle corrupted or missing configuration files?

The readConnectState function in apps/server/src/connect-state.ts treats missing files (ENOENT) as a missing status and JSON parsing errors as invalid. Files exceeding CONNECT_STATE_MAX_BYTES (16 KB) are rejected, preventing memory exhaustion from malicious or accidental large file uploads.

What prevents performance degradation when scanning for workspace MCP configurations?

The system implements hard limits through CONNECT_SNAPSHOT_MAX_RUNTIME_ROWS (default 100) and runtimeConfigMaxBytes when scanning the runtime_opencode_configs table via inspectConnectRuntime. This bounded scan prevents database exhaustion while still detecting openwork-cloud entries across active workspaces.

How does the system differentiate between host-level and workspace-specific MCP connections?

Host-level configuration resides in connect-state.json managed by persistConnectState, while workspace-specific resolution occurs through resolveConnectWorkspace which queries the runtime_opencode_configs table. The getConnectSnapshot function merges both scopes, setting cloudMcpPresent based on either persisted host config or runtime detection.

When does connect-state perform network calls versus local file or database checks?

Network calls to probe cloud health only occur when resolveCloudHealth explicitly calls readOpenworkCloudMcpHealth during snapshot generation for a resolved workspace. Local detection via inspectConnectRuntime scans the runtime database table without network overhead, providing a fast fallback when host-level configuration is absent.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →