t3code icon indicating copy to clipboard operation
t3code copied to clipboard

feat(server): expose terminal control to agents over MCP

Open frizynn opened this issue 4 months ago • 3 comments

What

Adds a terminal toolkit to the server's MCP server, mirroring the existing preview toolkit, so an agent running inside T3 Code can drive terminals: terminal_open, terminal_write, terminal_read, terminal_list, terminal_wait, terminal_close.

It also exposes three point-in-time reads on TerminalManager (readAllTerminalMetadata, readTerminalMetadata, readTerminalSnapshot) that are thin wrappers over helpers the service already computed privately.

Why

The MCP server currently exposes browser automation only, so an agent cannot open a terminal or run anything in one. Everything else was already in place: the server owns persistent PTYs, and subscribeTerminalMetadata already publishes the roster, which the web client already reconciles into the drawer layout. A terminal created through these tools shows up in connected clients with no client-side change.

Notes for review

The first commit added the toolkit but reached terminal state by using subscribeMetadata/attachStream as queries — subscribe, capture the snapshot from inside the listener, unsubscribe immediately. The second commit removes that: the manager reads replace it, which also drops two redundant roster scans per call and a fallback that reported hasRunningSubprocess: false whenever a post-open lookup came back empty.

Worth knowing: readTerminalSnapshot never opens, restarts or resizes the session, which attachStream can. That difference is why the read exists rather than reusing attach.

Thread scoping is a security property here, not a convenience: the thread id comes from the MCP invocation scope and is never accepted as a tool parameter, so an agent cannot name its way into another thread's terminals. There is a test for it.

Reads are bounded (200 trailing lines, 32k character ceiling) so scrollback cannot blow up the agent's context, and terminal_wait always returns within its timeout.

Testing

  • apps/server: tsgo --noEmit clean
  • vp test run src/mcp → 53 pass (14 new)
  • vp test run src/terminal → 56 pass
  • vp test run src/project → 26 pass
  • vp lint / vp fmt --check clean

On your contribution policy

CONTRIBUTING.md says you are not taking contributions right now, so no expectations — close it if it does not fit your direction. Opening it because the change is additive, confined to apps/server, and the manager reads may be useful on their own.


[!NOTE] Medium Risk Agents can run arbitrary commands in server-side PTYs scoped to their thread, which is intentional but operationally sensitive; thread isolation is enforced in handlers and tested.

Overview Adds a terminal MCP toolkit alongside the existing preview tools so agents can drive the same shared PTY sessions users see in the T3 Code drawer.

Six tools cover the full lifecycle: open (allocate or reattach), write (submit commands with optional raw keystrokes), read (bounded scrollback with ANSI stripping), list, wait (idle detection via subprocess metadata), and close. Handlers always scope work to the thread from the MCP credential—threadId is never a tool parameter—so agents cannot target another thread’s terminals.

TerminalManager gains openNewTerminal (id allocation under the thread lock), plus point-in-time readAllTerminalMetadata, readTerminalMetadata, and readTerminalSnapshot so handlers query state without subscribe-and-unsubscribe hacks.

Codex developer instructions now steer agents toward terminal_* for interactive or user-visible work while keeping routine shell use on the private tool.

Reviewed by Cursor Bugbot for commit ccfd9d7faa9896260b45f3672b1d4f9e80096cfc. Bugbot is set up for automated code reviews on this repo. Configure here.

[!NOTE]

Expose terminal control to agents as MCP tools via a new terminal toolkit

  • Adds six MCP tools (terminal_open, terminal_write, terminal_read, terminal_list, terminal_wait, terminal_close) implemented in handlers.ts and tools.ts, and registers them on the MCP HTTP server alongside the existing preview toolkit.
  • Extends TerminalManager with openNewTerminal (race-safe id allocation under thread lock) and point-in-time read APIs (readAllTerminalMetadata, readTerminalMetadata, readTerminalSnapshot).
  • Adds ANSI/control-sequence stripping and line/character bounding utilities so terminal_read returns clean, size-bounded output.
  • Appends terminal tool usage guidance to both Plan and Default mode developer instructions in CodexDeveloperInstructions.

Macroscope summarized ccfd9d7.

frizynn avatar Jul 29 '26 21:07 frizynn

[!IMPORTANT]

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 812a1469-0692-4c5c-bc18-2693e3106780

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • [ ] 🔍 Trigger review

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

coderabbitai[bot] avatar Jul 29 '26 21:07 coderabbitai[bot]

Approvability

Verdict: Needs human review

1 blocking correctness issue found. This PR introduces a substantial new feature (terminal control for agents via MCP) with 6 new tools and supporting infrastructure. New capabilities of this scope require human review, and there is also an unresolved review comment about a potential race condition in terminal_write.

You can customize Macroscope's approvability policy. Learn more.

macroscopeapp[bot] avatar Jul 29 '26 21:07 macroscopeapp[bot]

Both findings were real. Fixed in ccfd9d7f.

Open id allocation race. terminal_open read the roster, picked the lowest free id, then called TerminalManager.open, which reattaches to an existing session with that id — so two concurrent opens both picked the same id and the second silently reattached, with both calls reporting success for the same terminal. Added openNewTerminal, which allocates and opens inside the same withThreadLock section, and terminal_open now uses it whenever the caller did not name a terminal.

Write succeeds on exited shell. Confirmed in Manager.write: if (session.status === "exited") return; is a deliberate no-op, so the tool was reporting submitted: true for input that reached no shell. The handler now reads the session first and surfaces TerminalNotRunningError, which is what the manager already raises for every other non-running state. Left Manager.write alone since the silent no-op looks intentional for the UI path.

One note on testing, in case it matters to a reviewer: the concurrency regression test had to go in Manager.test.ts against the real manager. The equivalent test written against the toolkit's in-memory stub passed against the buggy code too, because the stub resolves synchronously and never interleaves. The toolkit test asserts the weaker property it can actually observe — that an unnamed open delegates allocation to the manager rather than pre-computing an id.

Also pushed since the original PR: a matching section in CodexDeveloperInstructions.ts. Registering the tools was not enough on its own — the agent ignored them and reached for desktop automation to open a graphical terminal, because the injected instructions describe the preview_* tools and say nothing about terminals.

frizynn avatar Jul 29 '26 22:07 frizynn

[!NOTE] 🤖 GPT-5.6 Sol responding on behalf of Theo

Closing this PR after an automated pass over open pull requests. Adds an unsolicited product feature or cross-system architecture change that exceeds the contribution policy.

t3dotgg avatar Aug 23 '26 11:08 t3dotgg