Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

feat(mcp): add two-way local agent receive

Rahman796ec2f256b9
diff --git a/CLAUDE.md b/CLAUDE.md
index 0e291cc5..0fc29a4b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -349,7 +349,7 @@ the real runtime and working analogue before changing a tool or skill contract.
- **Tool names are a cross-repo contract.** `rahmanef63/connectors-gateway` registered
mso as a connector on 2026-08-17 and historically pinned a subset of the MCP names as
literal `x-upstream` strings.
- <!-- mcp-toolset: server=1.6.0 version=2026.09.03.1 tools=70 read=34 write=24 exec=12 -->
+ <!-- mcp-toolset: server=1.6.0 version=2026.09.03.2 tools=70 read=34 write=24 exec=12 -->
MSO currently exposes **71 transport tools**: **70 model/operator tools** (34 read, 24 write,
12 exec) plus the app-only `workflow_status` bridge; `GET /mcp` plus `_meta.toolset` expose
the current version/hash/name manifest.
diff --git a/README.md b/README.md
index ac075904..f2874d8b 100644
--- a/README.md
+++ b/README.md
@@ -76,7 +76,7 @@ For a real deployment, put MSO behind **Tailscale, a VPN, or a TLS reverse proxy
- **Use BYOK AI** — Alfa and the terminal MSO Agent use credentials stored on your server, not committed to the repo. Bare `mso` opens the interactive setup/operations agent. `mso models` manages AI provider/API/OAuth connections; `mso model` only selects the active model from providers that are already connected.
- **Automate deployment providers without handing tokens to the model** — Dokploy and Cloudflare are built-in feature apps; `mso provider` also supports Hostinger DNS. Secrets stay in owner-only MSO state while bounded provider tools perform live checks and approved deployment/DNS operations. See [docs/INFRASTRUCTURE-PROVIDERS.md](./docs/INFRASTRUCTURE-PROVIDERS.md).
- **Drive the box from ChatGPT, Codex, Claude Code, Cursor, Gemini CLI or VS Code** — Settings → MCP now provides client-specific numbered setup, copy-ready remote configs, live MCP/OAuth discovery checks, tunnel/domain guidance, and the same OAuth 2.1 + PKCE `read → write → exec` permission ladder enforced server-side. See the [ChatGPT Plugin / custom MCP app guide](./docs/CHATGPT-PLUGIN.md) and [MCP reference](./docs/MCP.md).
-- **Message live local sessions by a short name** — every durable same-principal MSO session gets a unique familiar handle such as `@milo`, `@luna`, or `@nara`, independent from its longer auto-generated session title. `/rename <name>` changes that handle, while `/title <text>` changes the session description. `@milo …` resolves only agents with a current lease **and** a live receiver subscription, then creates an explicitly correlated request; replies relay deterministically into the originating conversation while notify-only events remain passive. Presence lease (`idle`/`busy`/`offline`) and receiver subscription (`consumerConnected`) are reported separately so an idle-but-unsubscribed target is diagnosable. See [Local Agents](./docs/LOCAL-AGENTS.md).
+- **Message live local sessions by a short name** — every durable same-principal MSO session gets a unique familiar handle such as `@milo`, `@luna`, or `@nara`, independent from its longer auto-generated session title. `/rename <name>` changes that handle, while `/title <text>` changes the session description. `@milo …` resolves only agents with a current lease **and** a live receiver subscription, then creates an explicitly correlated request; replies relay deterministically into the originating conversation while notify-only events remain passive. Presence lease (`idle`/`busy`/`offline`) and receiver subscription (`consumerConnected`) are reported separately so an idle-but-unsubscribed target is diagnosable. For ChatGPT/MCP sessions, `local_agent_inbox(wait_ms=...)` temporarily turns the foreground MCP call into that live receiver for up to 20 seconds, enabling direct two-way session messaging without a worker, DB, webhook, or broker. See [Local Agents](./docs/LOCAL-AGENTS.md).
- **Spawn focused same-session subagents** — `/spawn` and `agent_subagent_run` create bounded foreground workers with isolated context, explicit delegated scope, turn/timeout caps, no recursive spawn, and final-result-only return. They are not Local Agent peers and do not run autonomously after the parent call returns. See [Subagents](./docs/SUBAGENTS.md).
- **Delegate between remote agents with standard A2A v1** — register public HTTPS peers, attach private API-key/Bearer/OAuth access-token profiles, stream remote tasks over SSE, or expose MSO's authenticated inbound Agent Card when a public HTTPS origin is configured. Inbound credentials are owner-minted `read | write | exec` capabilities and run in a memory-isolated task context. See [A2A](./docs/A2A.md).
- **Keep agents efficient independently of the model provider** — the MCP-first [Cognitive Runtime](./docs/COGNITIVE-RUNTIME.md) isolates conversations from OAuth identity, budgets model context/tool output, uses the RASMIC catalog-first router to select a tiny per-turn capability pack without weakening scopes, compacts durable sessions with sanitized 30-day backup archives, learns only verified workflow recipes, promotes repeated procedures only through the eval-gated Tool Forge, and batches/filter/aggregates independent reads through `read_pipeline` before raw data reaches the model. `bun run bench:cognitive` and `bun run bench:pipeline` guard routing, correctness and context savings.
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index b222ce03..2f9ccad1 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -160,7 +160,7 @@ park a visible Approve/Deny card. The complete semantic contract is
**MCP** is for external clients such as ChatGPT, Claude.ai and Cursor. Its catalog lives in
`lib/mcp/`; access is controlled by the OAuth token scope rather than Alfa approval cards.
-<!-- mcp-toolset: server=1.6.0 version=2026.09.03.1 tools=70 read=34 write=24 exec=12 -->
+<!-- mcp-toolset: server=1.6.0 version=2026.09.03.2 tools=70 read=34 write=24 exec=12 -->
At the current toolset it exposes **71 transport tools**: **70 model/operator tools** (34 read, 24 write, 12 exec) plus the app-only `workflow_status` progress bridge. Project-specific
function names remain data behind `project_capabilities` / `project_function_call`, so one
project cannot dynamically rewrite the global MCP tool prefix. `GET /mcp` remains the live count/hash authority.
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 3550d7d6..c606ce1d 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Added**
+- `mcp` add two-way local agent receive
- `mcp` add read-only result pipeline
- add RASMIC orchestration memory automation
- `agent` section terminal and recover API errors
diff --git a/docs/CHATGPT-PLUGIN.md b/docs/CHATGPT-PLUGIN.md
index cb30ea68..948602fa 100644
--- a/docs/CHATGPT-PLUGIN.md
+++ b/docs/CHATGPT-PLUGIN.md
@@ -12,15 +12,15 @@
> <https://help.openai.com/en/articles/12584461-developer-mode-and-mcp-apps-in-chatgpt-beta>
> and <https://help.openai.com/en/articles/20001256-plugins-in-chatgpt-and-codex>.
-<!-- mcp-toolset: server=1.6.0 version=2026.09.03.1 tools=70 read=34 write=24 exec=12 -->
+<!-- mcp-toolset: server=1.6.0 version=2026.09.03.2 tools=70 read=34 write=24 exec=12 -->
-MSO currently exposes MCP server **1.6.0**, toolset **2026.09.03.1**: **71 transport tools** total; **70 model/operator tools**
+MSO currently exposes MCP server **1.6.0**, toolset **2026.09.03.2**: **71 transport tools** total; **70 model/operator tools**
(34 read, 24 write, 12 exec) plus app-only `workflow_status` for the progress widget. Use `GET /mcp` or Settings → MCP as the live authority if
this document and a deployed instance ever disagree.
### Local-agent and subagent tools
-The current catalog exposes `local_agents_list`, `local_agent_message_send`, `local_agent_reply`, `local_agent_request_wait`, `local_agent_inbox`, and `local_agent_request` for same-principal session collaboration, plus `agent_subagent_run` for one bounded foreground isolated worker. `local_agents_list` separates lease status from receiver subscription; `local_agent_request_wait` gives a bounded no-resend mailbox outcome; `local_agent_request` is an exec-gated fresh worker from a durable session context and never claims to wake/control the original ChatGPT/terminal process. The local tools do not turn an MCP connection into a remote A2A peer, and the subagent tool does not create another durable session or background process. A client should use `local_agent_reply` for an exact inbox request instead of reconstructing correlation from text.
+The current catalog exposes `local_agents_list`, `local_agent_message_send`, `local_agent_reply`, `local_agent_request_wait`, `local_agent_inbox`, and `local_agent_request` for same-principal session collaboration, plus `agent_subagent_run` for one bounded foreground isolated worker. `local_agents_list` separates lease status from receiver subscription. `local_agent_inbox` accepts optional `wait_ms` (0-20000): zero preserves the old immediate read, while a positive value holds only that foreground MCP call and returns early when a peer message arrives. During that wait the session is a real Local Agent receiver (`consumerConnected=true`), so another ChatGPT conversation on the same MCP client can deliver directly without spawning a worker. `local_agent_request_wait` remains the bounded no-resend wait for one exact outbound request; `local_agent_request` remains an exec-gated fresh worker from a durable session context and never claims to wake/control the original ChatGPT/terminal process. The local tools do not turn an MCP connection into a remote A2A peer, and the subagent tool does not create another durable session or background process. A client should use `local_agent_reply` for an exact inbox request instead of reconstructing correlation from text.
## 1. What this connection does
@@ -282,6 +282,8 @@ hash: <live schema hash>
count: 70 model/operator tools (+ 1 app-only bridge)
```
+Toolset `2026.09.03.2` changes the `local_agent_inbox` input schema by adding optional `wait_ms`. ChatGPT keeps a frozen action snapshot, so refresh/re-scan the MSO app actions before expecting the model to see this parameter. Existing omitted/`wait_ms=0` calls remain backward compatible.
+
Use this sequence after an MSO MCP change:
```mermaid
diff --git a/docs/CONNECTORS-GATEWAY-INTEGRATION.md b/docs/CONNECTORS-GATEWAY-INTEGRATION.md
index a8b5f459..d1135f44 100644
--- a/docs/CONNECTORS-GATEWAY-INTEGRATION.md
+++ b/docs/CONNECTORS-GATEWAY-INTEGRATION.md
@@ -4,9 +4,9 @@
> can evolve independently, so do not claim its mapping count is current without checking
> that repository at the time of the change.
-<!-- mcp-toolset: server=1.6.0 version=2026.09.03.1 tools=70 read=34 write=24 exec=12 -->
+<!-- mcp-toolset: server=1.6.0 version=2026.09.03.2 tools=70 read=34 write=24 exec=12 -->
-MSO currently exposes MCP server **1.6.0**, toolset **2026.09.03.1**: **71 transport tools** total; **70 model/operator tools**
+MSO currently exposes MCP server **1.6.0**, toolset **2026.09.03.2**: **71 transport tools** total; **70 model/operator tools**
(34 read, 24 write, 12 exec) plus app-only `workflow_status`. `GET /mcp` exposes the live names, version/hash and scoped
manifest and is the machine-readable parity source.
@@ -16,6 +16,8 @@ Toolset `2026.09.02.7` tracks `local_agents_list`, `local_agent_message_send`, `
Toolset `2026.09.02.8` introduced RASMIC's `project_memory_search`, `project_memory_upsert`, and `project_script_run`; toolset `2026.09.02.9` keeps those three names stable while extending `project_memory_search` with `search | related | timeline` views and the catalog-first runtime. A gateway may expose these literal names, but must preserve their MSO scopes and must not reinterpret repo-local `.agent` records as gateway-owned/global memory.
+Toolset `2026.09.03.2` keeps Local Agent names/scopes stable and extends only `local_agent_inbox` with optional `wait_ms` (0-20000). A positive wait is a bounded foreground receive operation on the existing MCP request; it is not a webhook, background subscriber, remote agent spawn, or new transport.
+
## Why this contract matters
Connector/gateway manifests commonly bind an action to an MSO tool with a literal upstream
diff --git a/docs/LOCAL-AGENTS.md b/docs/LOCAL-AGENTS.md
index b29d2c12..f7476982 100644
--- a/docs/LOCAL-AGENTS.md
+++ b/docs/LOCAL-AGENTS.md
@@ -102,7 +102,7 @@ Local Agents uses a small private lease store rather than rewriting the potentia
Interactive CLI sessions maintain a lightweight lease heartbeat and one SSE receive stream. There is no message polling loop. **Presence and consumption are separate signals:** `idle` means the lease is current; it does not by itself prove that an SSE receiver is subscribed. Directory rows therefore also expose `consumerConnected` and `consumerCount`. `/new` and `/resume` release the old receiver and bind the same terminal to the new durable session automatically. `/restart` keeps the exact durable session alive across process replacement and the replacement process renews its lease.
-MCP conversation sessions have no persistent terminal socket, so MSO refreshes their lease around bound MCP tool calls. Messages remain durable when that client is not currently connected and can be read with `local_agent_inbox` on a later call.
+MCP conversation sessions have no persistent terminal socket, so MSO refreshes their lease around bound MCP tool calls. Toolset `2026.09.02.10` adds a KISS foreground receive path: `local_agent_inbox(wait_ms=...)` may keep one MCP call open for 0–20 seconds. A positive wait registers the same in-process Local Agent subscriber used by terminal delivery, keeps that session receivable/idle for the duration of the call, and returns early when another same-principal session sends a message. The implementation performs a second durable-mailbox read after subscribing so a message cannot be lost in the read→subscribe race. The subscriber is always removed on message, timeout, or error. When no MCP call is active, messages remain durable and are read on a later call; MSO still does not claim it can wake an idle ChatGPT conversation.
Only `ready`, `idle`, and `busy` sessions appear in the normal lease-active target list. `@mention` is stricter: it resolves only those rows that also have `consumerConnected=true`. An explicit lower-level send to a known `offline`/`ended` target can still retain a durable queued message; the sender receives `target_offline` instead of a false delivered status.
@@ -158,7 +158,7 @@ Local messaging has explicit tools so it cannot be confused with public A2A peer
| `local_agent_message_send` | write | Backward-compatible explicit send. Default `intent=notify`; can create a durable request and may explicitly queue to known offline targets. |
| `local_agent_reply` | write | Reply to one exact request message ID; target, correlation ID, and relay policy are inherited. |
| `local_agent_request_wait` | read | Bounded 0–30s foreground wait/status for one exact sent request; returns replied/offline/no-consumer/timeout without resend. |
-| `local_agent_inbox` | read | Read this exact durable session's mailbox with explicit intent/correlation metadata. |
+| `local_agent_inbox` | read | Read this exact durable session's mailbox with explicit intent/correlation metadata; optional `wait_ms=0..20000` makes the current foreground MCP call a bounded live receiver and returns early on peer delivery. |
| `local_agent_request` | exec | Run a fresh bounded worker from another same-owner durable session context and return the result even when its terminal receiver is offline; never claims to wake/control that original process. |
Remote A2A tools retain their existing names (`a2a_agent_*`, `a2a_message_send`, `a2a_handoff`, etc.) and behavior.
diff --git a/docs/MCP.md b/docs/MCP.md
index c458736d..b4353d45 100644
--- a/docs/MCP.md
+++ b/docs/MCP.md
@@ -126,9 +126,9 @@ The catalog has a stable server version plus a schema-derived toolset signature.
Settings → MCP shows the current version/hash/count and stores a browser-local acknowledgement when the operator marks ChatGPT refreshed. A later signature change becomes an explicit stale-snapshot warning. This does not mutate ChatGPT remotely; it makes the required refresh visible instead of relying on memory.
-<!-- mcp-toolset: server=1.6.0 version=2026.09.03.1 tools=70 read=34 write=24 exec=12 -->
+<!-- mcp-toolset: server=1.6.0 version=2026.09.03.2 tools=70 read=34 write=24 exec=12 -->
-Current transport catalog: **71 tools**, server `1.6.0` / toolset `2026.09.03.1`.
+Current transport catalog: **71 tools**, server `1.6.0` / toolset `2026.09.03.2`.
The model/operator catalog is **69 tools** (33 read, 24 write, 12 exec); `workflow_status` is the
one app-only MCP Apps bridge used by the progress widget and is documented separately.
`agent_memory_search` is the typed-memory retrieval surface. It resolves semantic/episodic/procedural claims at an optional point in time, returns confidence/provenance and competing effective claims, and can expose superseded/retracted history when explicitly requested. `agent_memory_remember` remains the write surface and now accepts typed metadata; raw ChatGPT conversation ids are never stored as provenance.
@@ -143,7 +143,7 @@ RASMIC adds three stable generic MCP tools without coupling MSO to another repos
### Local Agent collaboration
-Local same-owner session collaboration is intentionally separate from public A2A. `local_agents_list` reports each durable session's short public `name`, lease status, and live receiver observability (`consumerConnected` / `consumerCount`). `local_agent_message_send` + `local_agent_reply` provide durable correlated mailbox semantics; `local_agent_request_wait` gives a bounded foreground request outcome without polling/resending; `local_agent_request` is an explicit exec-gated fresh worker from another durable session context and never claims to wake/control its original terminal/ChatGPT process. Human `@name` mentions resolve active public names only.
+Local same-owner session collaboration is intentionally separate from public A2A. `local_agents_list` reports each durable session's short public `name`, lease status, and live receiver observability (`consumerConnected` / `consumerCount`). `local_agent_message_send` + `local_agent_reply` provide durable correlated mailbox semantics. `local_agent_inbox(wait_ms=...)` can hold one foreground MCP call for at most 20 seconds and returns early when a peer message arrives; the implementation registers the same in-process receiver used by terminal Local Agents, closes the read/subscribe race with a second durable-mailbox read, and unsubscribes on return/timeout. The default `wait_ms=0` preserves immediate reads. `local_agent_request_wait` remains the bounded wait for one exact correlated outbound request, while `local_agent_request` remains an explicit exec-gated fresh worker from another durable session context and never claims to wake/control its original terminal/ChatGPT process. Human `@name` mentions resolve active public names only.
### Agent-to-Agent (A2A) peers
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 2079a065..f1b7cfa9 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -2,6 +2,14 @@
Running log of what shipped each phase. Newest at top.
+## 2026-09-03 — MCP Local Agent foreground two-way receive
+
+- **KISS two-way MCP path:** `local_agent_inbox` now accepts optional `wait_ms=0..20000`. A positive wait keeps only the current foreground MCP request open, registers the existing in-process Local Agent subscriber, and returns early when another same-principal session delivers a message. No DB, webhook, broker, WebSocket, daemon, or background worker was added.
+- **Race-safe durability:** the durable file mailbox remains authoritative. The receiver reads once, subscribes, reads again to close the read→subscribe race, then waits for either an event or timeout; the listener is always removed on return/error/timeout. Omitted/zero `wait_ms` preserves the previous immediate inbox behavior.
+- **Receivable MCP presence:** the MCP dispatcher keeps `local_agent_inbox` sessions `idle` rather than marking the receive call `busy`, allowing `local_agent_message_send` / `local_agent_reply` to publish directly to that foreground receiver. Other tool calls retain normal `busy → idle` presence.
+- **Real A↔B integration coverage:** a new MCP-dispatch integration test opens Chat-B-style inbox wait, sends a correlated request from Chat A, then opens Chat-A-style inbox wait and replies from Chat B. Both deliveries return `delivered`, both waits wake before timeout, and neither path invokes `local_agent_request` or any spawned durable-session worker.
+- **Toolset:** upstream P3 already added `read_pipeline`; this schema-only Local Agent update therefore advances the catalog to `2026.09.03.2` while keeping **71 transport tools = 70 model/operator tools (34 read / 24 write / 12 exec) + app-only `workflow_status`**. ChatGPT must refresh/re-scan its frozen action snapshot before the model can see the new optional parameter.
+
## 2026-09-03 — Cognitive Runtime P3 read-only orchestration
- **Self-update invariant fixed:** RASMIC `.agent/` evidence/memory is runtime-local state and is now ignored by the MSO repo. This prevents successful workflow memory writes from making the canonical checkout dirty and causing `mso update` to refuse its own upgrade.
diff --git a/docs/TESTING-HANDOFF.md b/docs/TESTING-HANDOFF.md
index ce5986b7..13c738c4 100644
--- a/docs/TESTING-HANDOFF.md
+++ b/docs/TESTING-HANDOFF.md
@@ -4,13 +4,14 @@ Update this file at the end of every manual or automated test session. Keep it f
## Current status
-The current deployed baseline is **MSO CLI 1.12.0** with toolset `2026.09.03.1`; use `mso --version` plus `/api/health` for the exact Git build because documentation-only release commits also advance that identity. The v1.10/v1.11 findings and the v1.12 sectioned-terminal/recoverable-error work below are resolved and retained as historical test evidence. Do not re-open a resolved finding from prose alone: reproduce it against the current build first. There is no known 1.12 release blocker in this handoff.
+The current deployed baseline is **MSO CLI 1.12.0** with toolset `2026.09.03.2`; use `mso --version` plus `/api/health` for the exact Git build because documentation-only release commits also advance that identity. The v1.10/v1.11 findings and the v1.12 sectioned-terminal/recoverable-error work below are resolved and retained as historical test evidence. Do not re-open a resolved finding from prose alone: reproduce it against the current build first. There is no known 1.12 release blocker in this handoff.
Current verified behavior:
- every durable session has a unique short public `name` (`milo`, `luna`, `nara`, …) independent from its longer `title`; `/rename` changes the handle and `/title` changes the description;
- human `@name` mention routing resolves active agents only; internal `agent-a` aliases remain compatibility data for explicit APIs;
- composer drafts wrap dynamically to terminal width/height, repaint on resize, and ↑/↓ navigate visual rows before history;
- `local_agents_list` exposes lease status separately from `consumerConnected` / `consumerCount`;
+- `local_agent_inbox(wait_ms=0..20000)` can make one foreground MCP request a real Local Agent receiver; it returns early on peer delivery, closes the read→subscribe race against the durable mailbox, and never starts a background listener;
- `local_agent_request_wait` provides bounded foreground outcomes without resend/background polling;
- `local_agent_request` has MCP-dispatch coverage and remains a fresh bounded worker, never a claim to wake/control another terminal/ChatGPT process;
- standalone Local Agent MCP tests isolate the A2A worker import boundary instead of failing on Vitest's unresolved `server-only`;
@@ -24,7 +25,7 @@ Current verified behavior:
```text
You are taking over MSO testing work in /home/rahman/projects/mso.
-Read docs/TESTING-HANDOFF.md first. Current verified baseline: CLI 1.12.0, toolset 2026.09.03.1; resolve the exact live Git build from `mso --version`/`/api/health`. Preserve existing work and do not re-open resolved v1.10-v1.12 findings unless you can reproduce them against the current build.
+Read docs/TESTING-HANDOFF.md first. Current verified baseline: CLI 1.12.0, toolset 2026.09.03.2; resolve the exact live Git build from `mso --version`/`/api/health`. Preserve existing work and do not re-open resolved v1.10-v1.12 findings unless you can reproduce them against the current build.
For a new issue: record the exact reproduction, distinguish durable state from live receiver/process state, avoid duplicate write/exec retries when outcome is uncertain, add the smallest focused regression, run typecheck plus the relevant contract tests, then update this handoff with factual results.
```
@@ -61,6 +62,28 @@ Validation minimum: focused unit tests for success, offline target, absent subsc
## Session log
+### 2026-09-03 — ChatGPT-session Local Agent foreground two-way MVP
+
+**Goal**
+- Make two separate ChatGPT conversations connected to the same MSO MCP communicate directly in both directions while each destination is actively holding a bounded MCP receive call.
+- Reuse the existing file mailbox + in-process Local Agent subscriber; no DB, webhook, broker, WebSocket, daemon, or worker spawn.
+
+**Changed**
+- Added optional `wait_ms=0..20000` to read-scope `local_agent_inbox`; default zero preserves immediate reads.
+- Added race-safe foreground receive: read mailbox → subscribe → read again → wait for event/timeout → final read, always unsubscribe.
+- MCP dispatcher keeps `local_agent_inbox` presence receivable/`idle` while the call is open instead of marking it `busy`; normal tool calls are unchanged.
+- Advanced toolset schema identity to `2026.09.03.2`; upstream P3's new `read_pipeline` remains intact, so the catalog stays at 70 model/operator tools + app-only `workflow_status`.
+
+**Verified before full release gate**
+- Targeted typecheck + ESLint: PASS.
+- Targeted Local Agent/MCP bundle: **5 test files / 50 tests passed**.
+- New end-to-end MCP-dispatch test proves A→B request delivery and B→A correlated reply delivery while each destination is in `local_agent_inbox(wait_ms)`, with sender status `delivered` and receiver subscriber cleanup after return.
+- `node scripts/check-docs.mjs`: PASS after merging the concurrent P3 read-pipeline toolset.
+- Full release gate PASS with exit 0: `bun run verify` followed by `bash scripts/verify-build.sh`; lint remains **0 errors / 8 existing max-lines warnings**, dependency audit is clean, and the out-of-tree production build completes successfully.
+
+**Client test requirement**
+- ChatGPT uses a frozen MCP action snapshot. Refresh/re-scan MSO actions after deployment so `local_agent_inbox.wait_ms` is visible to the model; then use two new ChatGPT conversations for the live A↔B test.
+
### 2026-09-03 — repository docs + unused Agent surface audit
**Goal**
diff --git a/lib/agent/local-agent-messaging.ts b/lib/agent/local-agent-messaging.ts
index 88434970..ccbf4972 100644
--- a/lib/agent/local-agent-messaging.ts
+++ b/lib/agent/local-agent-messaging.ts
@@ -4,10 +4,11 @@ import { getAgentSession } from "./session-store";
import { principalHash } from "./session-files";
import { listLocalAgents, resolveLocalAgent } from "./local-agent-directory";
import { enqueueLocalAgentMessage, findLocalAgentReply, getLocalAgentInboxMessage, getLocalAgentSentMessage, listLocalAgentInbox, updateLocalAgentMessageState } from "./local-agent-mailbox";
-import { publishLocalAgentMessage } from "./local-agent-events";
+import { publishLocalAgentMessage, subscribeLocalAgentMessages } from "./local-agent-events";
import type { LocalAgentDeliveryStatus, LocalAgentMessageIntent, LocalAgentMessageKind, LocalAgentMessageView, LocalAgentTarget } from "./local-agent-types";
export const MAX_LOCAL_AGENT_MESSAGE_BYTES = 16 * 1024;
+export const MAX_LOCAL_AGENT_INBOX_WAIT_MS = 20_000;
function safePayload(value: string): string {
const raw = String(value || "").trim();
@@ -140,6 +141,39 @@ export async function flushLocalAgentQueue(principal: string, targetSessionId: s
}
+export async function waitForLocalAgentInbox(input: {
+ principal: string;
+ sessionId: string;
+ includeRead?: boolean;
+ limit?: number;
+ waitMs?: number;
+}): Promise<LocalAgentMessageView[]> {
+ const limit = Math.max(1, Math.min(200, Math.trunc(input.limit ?? 100)));
+ const waitMs = Number.isFinite(input.waitMs)
+ ? Math.max(0, Math.min(MAX_LOCAL_AGENT_INBOX_WAIT_MS, Math.trunc(input.waitMs ?? 0)))
+ : 0;
+ const read = () => listLocalAgentInbox(input.principal, input.sessionId, { includeRead: input.includeRead === true, limit });
+ const initial = await read();
+ if (initial.length || waitMs === 0) return initial;
+
+ let wake = () => {};
+ const signalled = new Promise<void>((resolve) => { wake = resolve; });
+ const unsubscribe = subscribeLocalAgentMessages(input.sessionId, () => wake());
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ // Close the read→subscribe race: a sender may persist mail after the first
+ // read but before this receiver registers. The mailbox remains authoritative.
+ const afterSubscribe = await read();
+ if (afterSubscribe.length) return afterSubscribe;
+ const timedOut = new Promise<void>((resolve) => { timer = setTimeout(resolve, waitMs); });
+ await Promise.race([signalled, timedOut]);
+ return read();
+ } finally {
+ if (timer) clearTimeout(timer);
+ unsubscribe();
+ }
+}
+
export async function waitForLocalAgentReply(input: {
principal: string;
senderSessionId: string;
diff --git a/lib/mcp/dispatch-tools.ts b/lib/mcp/dispatch-tools.ts
index 73d10bc5..86989bd4 100644
--- a/lib/mcp/dispatch-tools.ts
+++ b/lib/mcp/dispatch-tools.ts
@@ -72,7 +72,12 @@ export async function dispatchToolCall(req: RpcRequest, scope: Scope, actor?: st
if (!workflowProbe) void recordMcpActivity({ id: activityId, actor, tool: name, state: "started", scope, ...initialFlow, target });
try {
if (mcpPresence)
- await touchLocalAgentPresence(mcpPresence.principal, mcpPresence.sessionId, "busy", mcpPresence.instanceId).catch(() => undefined);
+ await touchLocalAgentPresence(
+ mcpPresence.principal,
+ mcpPresence.sessionId,
+ name === "local_agent_inbox" ? "idle" : "busy",
+ mcpPresence.instanceId,
+ ).catch(() => undefined);
const titleHint = sessionDetail(name, args, target);
if (titleHint && context?.principal && context.sessionId && !["agent_session_current", "workflow_status", "agent_subagent_run"].includes(name)) {
await maybeAutoTitleAgentSession(context.principal, context.sessionId, titleHint).catch(() => undefined);
diff --git a/lib/mcp/local-agent-two-way.test.ts b/lib/mcp/local-agent-two-way.test.ts
new file mode 100644
index 00000000..c45a4545
--- /dev/null
+++ b/lib/mcp/local-agent-two-way.test.ts
@@ -0,0 +1,91 @@
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import { mkdtempSync, rmSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+vi.mock("server-only", () => ({}));
+
+const root = mkdtempSync(path.join(os.tmpdir(), "mso-mcp-local-two-way-"));
+process.env.OS_AGENT_SESSIONS_DIR = path.join(root, "sessions");
+process.env.OS_LOCAL_AGENT_PRESENCE_STORE = path.join(root, "presence.json");
+process.env.OS_LOCAL_AGENT_MESSAGE_STORE = path.join(root, "messages.json");
+process.env.OS_LOCAL_AGENT_LEASE_MS = "15000";
+process.env.NEXT_PUBLIC_OS_DEMO = "0";
+
+const store = await import("@/lib/agent/session-store");
+const events = await import("@/lib/agent/local-agent-events");
+const { dispatch } = await import("./dispatch");
+
+const principal = "mcp-client:two-way-test";
+let a: Awaited<ReturnType<typeof store.createAgentSession>>;
+let b: Awaited<ReturnType<typeof store.createAgentSession>>;
+
+const call = (name: string, args: Record<string, unknown> = {}) =>
+ ({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } });
+
+function textResult<T>(response: Awaited<ReturnType<typeof dispatch>>): T {
+ const result = response.result as { content: Array<{ text: string }> };
+ return JSON.parse(result.content[0].text) as T;
+}
+
+async function waitForSubscriber(sessionId: string): Promise<void> {
+ for (let i = 0; i < 50; i += 1) {
+ if (events.localAgentSubscriberCount(sessionId) > 0) return;
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ }
+ throw new Error(`receiver ${sessionId} never subscribed`);
+}
+
+beforeAll(async () => {
+ a = await store.createAgentSession(principal, "mcp", { title: "Chat A", titleSource: "manual" });
+ b = await store.createAgentSession(principal, "mcp", { title: "Chat B", titleSource: "manual" });
+});
+
+afterAll(() => rmSync(root, { recursive: true, force: true }));
+
+describe("two-way Local Agent MCP receive", () => {
+ it("keeps each foreground inbox receivable and wakes both ChatGPT-style sessions without spawning a worker", async () => {
+ const contextA = { principal, sessionId: a.id };
+ const contextB = { principal, sessionId: b.id };
+
+ const receiveB = dispatch(call("local_agent_inbox", { wait_ms: 1000 }), "read", "mcp:b", contextB);
+ await waitForSubscriber(b.id);
+
+ const sent = await dispatch(call("local_agent_message_send", {
+ target: b.name,
+ message: "PING_FROM_A",
+ intent: "request",
+ }), "write", "mcp:a", contextA);
+ expect(textResult<{ status: string }>(sent).status).toBe("delivered");
+
+ const inboxB = textResult<Array<{ id: string; text: string; intent: string }>>(await receiveB);
+ expect(inboxB).toHaveLength(1);
+ expect(inboxB[0]).toMatchObject({ text: "PING_FROM_A", intent: "request" });
+ expect(events.localAgentSubscriberCount(b.id)).toBe(0);
+
+ const receiveA = dispatch(call("local_agent_inbox", { wait_ms: 1000 }), "read", "mcp:a", contextA);
+ await waitForSubscriber(a.id);
+
+ const replied = await dispatch(call("local_agent_reply", {
+ reply_to_message_id: inboxB[0].id,
+ message: "PONG_FROM_B",
+ }), "write", "mcp:b", contextB);
+ expect(textResult<{ status: string }>(replied).status).toBe("delivered");
+
+ const inboxA = textResult<Array<{ text: string; intent: string; replyToMessageId?: string }>>(await receiveA);
+ expect(inboxA).toHaveLength(1);
+ expect(inboxA[0]).toMatchObject({
+ text: "PONG_FROM_B",
+ intent: "reply",
+ replyToMessageId: inboxB[0].id,
+ });
+ expect(events.localAgentSubscriberCount(a.id)).toBe(0);
+ });
+
+ it("preserves immediate reads when wait_ms is omitted", async () => {
+ const startedAt = Date.now();
+ const response = await dispatch(call("local_agent_inbox"), "read", "mcp:a", { principal, sessionId: a.id });
+ expect(Date.now() - startedAt).toBeLessThan(500);
+ expect(Array.isArray(textResult<unknown[]>(response))).toBe(true);
+ });
+});
diff --git a/lib/mcp/tools-local-agents.test.ts b/lib/mcp/tools-local-agents.test.ts
index 4e3e2f0d..2c17a509 100644
--- a/lib/mcp/tools-local-agents.test.ts
+++ b/lib/mcp/tools-local-agents.test.ts
@@ -25,5 +25,9 @@ describe("native local session agent MCP tools", () => {
expect(local.get("local_agent_reply")?.description).toMatch(/correlation/i);
expect(local.get("local_agent_request_wait")?.description).toMatch(/bounded foreground/i);
expect(local.get("local_agent_request")?.description).toMatch(/fresh bounded worker/i);
+ expect(local.get("local_agent_inbox")?.description).toMatch(/bounded interval/i);
+ const inboxSchema = JSON.stringify(local.get("local_agent_inbox")?.inputSchema ?? {});
+ expect(inboxSchema).toContain('"wait_ms"');
+ expect(inboxSchema).toContain('"maximum":20000');
});
});
diff --git a/lib/mcp/tools-local-agents.ts b/lib/mcp/tools-local-agents.ts
index 769aa4e1..348b660b 100644
--- a/lib/mcp/tools-local-agents.ts
+++ b/lib/mcp/tools-local-agents.ts
@@ -1,6 +1,6 @@
import { listLocalAgents } from "@/lib/agent/local-agent-directory";
import { listLocalAgentInbox, updateLocalAgentMessageState } from "@/lib/agent/local-agent-mailbox";
-import { replyLocalAgentMessage, sendLocalAgentMessage, waitForLocalAgentReply } from "@/lib/agent/local-agent-messaging";
+import { replyLocalAgentMessage, sendLocalAgentMessage, waitForLocalAgentInbox, waitForLocalAgentReply } from "@/lib/agent/local-agent-messaging";
import { handoffOwnerLocalSession } from "@/lib/a2a/local-session";
import { type McpRunContext, type McpTool, S, str } from "./tool-kit";
@@ -110,7 +110,7 @@ export const LOCAL_AGENT_TOOLS: McpTool[] = [
},
{
name: "local_agent_inbox",
- description: "Read durable local-agent messages for this exact session. Each item carries explicit intent/correlation metadata. If intent=request, answer it with local_agent_reply(reply_to_message_id=<item.id>, ...); do not invent correlation by parsing text. By default only unread items are returned.",
+ description: "Read durable local-agent messages for this exact session. With wait_ms > 0, keep this foreground MCP call open for a bounded interval and return as soon as a peer message arrives; this uses the existing in-process receiver plus the durable mailbox, never a background loop. Each item carries explicit intent/correlation metadata. If intent=request, answer it with local_agent_reply(reply_to_message_id=<item.id>, ...); do not invent correlation by parsing text. By default only unread items are returned.",
scope: "read",
annotations: { readOnlyHint: true, idempotentHint: true },
limit: { key: "local-agent.read", max: 120, windowMs: 60_000 },
@@ -118,10 +118,17 @@ export const LOCAL_AGENT_TOOLS: McpTool[] = [
include_read: { type: "boolean" },
limit: { type: "number", description: "1-200, default 100." },
acknowledge: { type: "boolean", description: "When true, mark returned messages read after retrieval." },
+ wait_ms: { type: "number", minimum: 0, maximum: 20000, description: "Optional foreground receive wait in milliseconds. Default 0 preserves immediate inbox reads; max 20000. Returns early when a peer message arrives." },
}),
run: async (a, context) => {
const current = sessionContext(context);
- const messages = await listLocalAgentInbox(current.principal, current.sessionId, { includeRead: a.include_read === true, limit: Number(a.limit) || 100 });
+ const messages = await waitForLocalAgentInbox({
+ principal: current.principal,
+ sessionId: current.sessionId,
+ includeRead: a.include_read === true,
+ limit: Number(a.limit) || 100,
+ waitMs: a.wait_ms === undefined ? 0 : Number(a.wait_ms),
+ });
if (a.acknowledge === true && messages.length)
await updateLocalAgentMessageState(current.principal, current.sessionId, messages.map((row) => row.id), "read");
return messages;
diff --git a/lib/mcp/toolset.ts b/lib/mcp/toolset.ts
index 66e07d09..0e681066 100644
--- a/lib/mcp/toolset.ts
+++ b/lib/mcp/toolset.ts
@@ -3,8 +3,8 @@ import type { Scope } from "./scope";
import type { McpTool } from "./tool-kit";
export const MCP_SERVER_VERSION = "1.6.0";
-export const MCP_TOOLSET_VERSION = "2026.09.03.1";
-export const MCP_TOOLSET_CHANGED_AT = "2026-09-02T20:10:00Z";
+export const MCP_TOOLSET_VERSION = "2026.09.03.2";
+export const MCP_TOOLSET_CHANGED_AT = "2026-09-02T20:39:00Z";
export type McpToolsetInfo = {
serverVersion: string;