Skip to main content
Glama
README.md
# GLM Agent Monitor MCP

A local stdio MCP server that displays independently launched GLM agents' logs in dedicated iTerm2 panes on macOS. Claude Code owns launching, orchestration, cancellation and completion detection. This server owns generated log files, fixed log viewers, split layout and managed terminal cleanup.

It exposes exactly five tools. There is no agent launcher, shell tool, arbitrary AppleScript interface, file-content tool, HTTP listener, network client or telemetry.

## Requirements and installation

- macOS with iTerm2 installed and a graphical login session.
- Node.js 22.16 or newer and npm. Unit tests can run on other platforms.
- Claude Code and your existing, independently configured GLM execution mechanism.

## Install directly in Claude Code

Use the prebuilt npm tarball from the versioned GitHub release; no checkout or build is required:

```sh
claude mcp add --transport stdio --scope user glm-agent-monitor -- npx --yes --ignore-scripts https://github.com/jaddoueik1/iterm-mcp/releases/download/v1.0.0/glm-agent-monitor-mcp-1.0.0.tgz
claude mcp get glm-agent-monitor
```

Alternatively merge `.mcp.json.example` into your project's MCP configuration. It uses the same pinned release URL. The tarball contains the compiled server, viewer, fixed AppleScript, Claude skill, documentation and license. `--ignore-scripts` disables dependency install hooks. npm/npx downloads packages before launching the server; the running monitor never downloads updates or initiates network requests. Change the pinned version explicitly when upgrading.

Once `glm-agent-monitor-mcp@1.0.0` is published to npmjs.com, the equivalent short registration is:

```sh
claude mcp add --transport stdio --scope user glm-agent-monitor -- npx --yes --ignore-scripts glm-agent-monitor-mcp@1.0.0
```

`.mcp.npm.json.example` contains that registry-based configuration. GitHub release tarballs work independently of npmjs publishing credentials.

## Build from source

Run in a clone of [jaddoueik1/iterm-mcp](https://github.com/jaddoueik1/iterm-mcp):

```sh
git clone git@github.com:jaddoueik1/iterm-mcp.git
cd iterm-mcp
npm ci --ignore-scripts
npm run build
npm test
```

Only the official `@modelcontextprotocol/sdk` and Zod are direct runtime dependencies. TypeScript and Node types are build dependencies. Versions are pinned in `package-lock.json`. The requested `@modelcontextprotocol/sdk` v1 maintenance package is used; its installed SDK interfaces were checked against the [official v1 documentation](https://github.com/modelcontextprotocol/typescript-sdk/tree/v1.x).

## Register with Claude Code

From this checkout, register the built server with an explicit Node path and a clean launch environment:

```sh
claude mcp add --transport stdio --scope user glm-agent-monitor -- /usr/bin/env -i "HOME=$HOME" PATH=/usr/bin:/bin "$(command -v node)" "$PWD/dist/index.js"
claude mcp get glm-agent-monitor
```

Restart Claude Code or reconnect through `/mcp`. Use the tool names Claude discovers for server `glm-agent-monitor` (typically `mcp__glm-agent-monitor__open-workspace`, etc.). No credentials are needed by the monitor.

For a local-build configuration, use `.mcp.local.json.example`, replace the two absolute executable paths, and merge it with any existing MCP configuration. `${HOME}` is expanded by Claude Code. Do not overwrite an existing configuration. See [Claude Code's local MCP configuration](https://code.claude.com/docs/en/mcp).

Install the reusable skill from a source checkout:

```sh
mkdir -p "$HOME/.claude/skills/glm-agent-monitor"
cp skills/glm-agent-monitor/SKILL.md "$HOME/.claude/skills/glm-agent-monitor/SKILL.md"
```

Alternatively put that `SKILL.md` under `.claude/skills/glm-agent-monitor/` in the consuming project. Invoke `/glm-agent-monitor` or let Claude select it when delegating to GLM. See [Claude Code skills](https://code.claude.com/docs/en/skills).

For an npm-only installation, install the versioned release tarball into a chosen local tools directory and copy the bundled skill from its installed package:

```sh
npm install --prefix "$HOME/.local/share/glm-agent-monitor" --ignore-scripts --omit=dev https://github.com/jaddoueik1/iterm-mcp/releases/download/v1.0.0/glm-agent-monitor-mcp-1.0.0.tgz
mkdir -p "$HOME/.claude/skills/glm-agent-monitor"
cp "$HOME/.local/share/glm-agent-monitor/node_modules/glm-agent-monitor-mcp/skills/glm-agent-monitor/SKILL.md" "$HOME/.claude/skills/glm-agent-monitor/SKILL.md"
```

## macOS Automation permission

On the first `open-workspace`, macOS may ask the hosting terminal/application for permission to control iTerm2. Allow it in **System Settings → Privacy & Security → Automation → iTerm2** for the relevant host. Running a command through a different host can require a separate grant. Automation permission is broad at the OS level; the application restricts its own operations to registered IDs and ownership markers. Accessibility permission and the iTerm2 Python API are not needed.

The server launches iTerm2 by sending its create-window Apple event. It always creates a dedicated window with one tab and a fixed viewer as the initial session command. Existing and restored user windows are never reused or closed. Application restoration or your iTerm2 startup preferences can independently open user windows.

## Architecture

```text
Claude Code ── stdio MCP ── monitor registry ── fixed AppleScript ── dedicated iTerm2 windows
     │                           │                                          │
     │ existing GLM launcher     └── private control files + heartbeat       │ fixed Node viewers
     ▼                                                                      ▼
GLM process ── stdout/stderr ── existing consumer + log mirror ── private agent.log
```

The server generates workspace UUIDs, pane UUIDs and private log paths. AppleScript returns actual native window/session IDs. Before a split or close, scripts resolve the exact session within its recorded window and check its random ownership marker. No operation targets the focused window/session. A single queue serializes native and registry mutations across workspaces; delayed closes wait outside it.

Viewers run a fixed Node helper with a minimal environment. They read generated control files and stream the generated log in 16 KiB chunks, honor output backpressure, and preserve printable text, CR/LF/TAB and ANSI SGR colors/styles. OSC/DCS and non-SGR terminal controls are filtered to prevent terminal actions. The original log bytes remain unchanged. No log content goes through MCP.

Every viewer checks a private heartbeat lease; it stops within about 15 seconds of a server crash, or sooner when its control state is stopped. Output stalls have a 15-second bound. The server handles stdin EOF, SIGINT, SIGTERM and SIGHUP by draining queued operations, cancelling closure delays, stopping viewers and closing verified managed windows. A forced kill can leave exited viewer panes visible, depending on the iTerm2 profile's behavior after a command exits. No registry is adopted after restart.

## Multi-agent workflow

1. Call `open-workspace`, saving its `workspaceId`.
2. For four distinct executions, call `open-agent-pane` with IDs such as `implement`, `tests`, `review`, `docs`. Save each returned log path and pane/session IDs.
3. Launch each agent **exactly once through the existing GLM mechanism**, directing its stdout/stderr to its own generated path. Keep the actual process/run handle separately.
4. If stdout already feeds an orchestration parser, insert a byte-preserving tee before that existing consumer. Preserve stderr handling too. Do not replace the consumer or launch a second process for visualization.
5. Observe real process exit/cancellation, drain the mirror, then call `close-agent-pane` with the actual exit code and final status. Do this in the orchestrator's completion/failure/cancellation cleanup. The monitor itself cannot detect GLM process completion.
6. The last agent closure closes the dedicated workspace. Call `close-workspace` in orchestration cleanup as an idempotent final step.

`examples/mirror-output.mjs` provides a client-side tee that starts no process. With an existing Node child-process orchestrator, the attachment is:

```js
import { createOutputMirrors } from './examples/mirror-output.mjs';

const mirrors = await createOutputMirrors(logFilePath, reportMonitoringWarning);
// Obtain `child` from the EXISTING launch invocation exactly once.
// Replace the existing pipe edges, keeping their existing consumer objects:
child.stdout.pipe(mirrors.stdout).pipe(existingStdoutConsumer);
child.stderr.pipe(mirrors.stderr).pipe(existingStderrConsumer);
// Existing code still owns waiting, output-drain ordering, exit status and cancellation.
// After both output streams drain: await mirrors.close(); then close-agent-pane.
```

This example is a stream attachment pattern, not a generic adapter for every launcher. An SDK that already invokes output callbacks should duplicate bytes inside those callbacks. If monitoring or mirroring fails, preserve the original launch/consumer behavior and continue the task. Never relaunch GLM to repair monitoring. This empty repository had no existing GLM integration to modify; the skill is the lifecycle integration, and its instructions must run in your existing orchestrator.

## Tools and examples

All schemas are strict: unknown keys, commands, filesystem paths, invalid UUIDs, terminal controls and oversized labels are rejected. Workspace IDs and pane IDs are generated UUIDs. Agent IDs match `^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$`. Names are 1–120 characters; task descriptions are 1–500. Display punctuation is data, never code. Tool results contain a text item with JSON metadata; failures have `isError: true`.

### `open-workspace`

Input: optional `workspaceName`, optional `reuseWorkspaceId` (a known live workspace). Each ordinary call creates a fresh workspace, even when names match. Explicit reuse never renames it.

```json
{"workspaceName":"Feature implementation"}
```

Output: `workspaceId`, actual `windowId`, and `status: "created" | "reused"`.

### `open-agent-pane`

Required: `workspaceId`, `agentId`, `agentName`. Optional: `taskDescription`, `splitDirection` (`auto` default, `horizontal`, `vertical`), `parentAgentId`.

```json
{"workspaceId":"<returned UUID>","agentId":"tests","agentName":"Test agent","taskDescription":"Check edge cases","splitDirection":"auto"}
```

Output: generated `paneId`, actual `sessionId`, absolute `logFilePath`, applied `splitDirection`, `status: "created"`. The first agent in a window reuses its initial waiting pane and reports `splitDirection: "none"`. Agent IDs cannot be reused during a workspace's lifetime, including after a failed registration or completed execution. A duplicate never truncates/reuses an existing log. Use a fresh execution ID.

### `close-agent-pane`

Required: `workspaceId`, `agentId`, `status` (`completed`, `failed`, `cancelled`). Optional: signed integer `exitCode`, integer `delayMs` (default 0; maximum 30000).

```json
{"workspaceId":"<returned UUID>","agentId":"tests","status":"completed","exitCode":0,"delayMs":1500}
```

Output: `status: "closed" | "already_closed"`. Shows a final status during the delay, stops only the viewer, and closes only the exact owned session. The GLM process must already have ended according to the orchestrator. Repeated concurrent requests share one close operation. A missing pane is reconciled without a fallback target. Completion also releases a protected log after explicit workspace closure.

### `list-agent-panes`

Input: `{}`. Output: `workspaces`, each containing `workspaceId`, `workspaceName`, original `windowId`, `createdAt`, `status`, all `windows` (actual IDs, timestamps and statuses), and `agents` (IDs, names, pane/session/window IDs, timestamps, split directions, statuses and generated log paths). Ownership markers, log contents, task descriptions and environment variables are omitted.

Workspace status is `active` or `close_failed`; window status is `active` or `missing`; agent status is `active`, `closing`, `missing`, `ownership_lost`, or `close_failed`. Completed agents leave the active registry. Missing agents remain metadata-only until the orchestrator reports their real lifecycle completion, protecting their log files.

### `close-workspace`

```json
{"workspaceId":"<returned UUID>"}
```

Output: `status: "closed" | "already_closed"`. Stops associated viewers and closes verified dedicated windows. It refuses to close a window if a user added an unregistered tab/session or changed an ownership marker. No GLM process is stopped; active log leases remain protected until explicit completion is reported.

## Automatic split layout

Horizontal means stacked above/below; vertical means side by side, as specified by the [official iTerm2 AppleScript interface](https://iterm2.com/documentation-scripting.html) and the installed `iTerm2.sdef`.

| Agents | Layout |
| --- | --- |
| 1 | Reuse the initial pane |
| 2 | Split agent 1 vertically, placing agent 2 on the right |
| 3 | Split agent 1 horizontally, placing agent 3 below it |
| 4 | Split agent 2 horizontally, placing agent 4 below it (2×2) |
| More | Split the largest suitable leaf, selecting its longer normalized dimension; stable tree order breaks ties |

The default maximum is four panes per window. Additional agents create another dedicated window within the same workspace. Increase the cap to allow more splits in a window. Actual character dimensions enforce minimums before a split; a too-small window spills into another dedicated window if capacity permits. With an explicit parent, a too-small/full parent window fails instead of silently splitting elsewhere. User resizing can change visible proportions; the server retains its split tree and checks actual dimensions, but does not rearrange user-resized panes.

## Storage and retention

```text
~/.glm-agent-monitor/
  logs/<workspace-uuid>/<agent-id>.log
  state/<server-instance-uuid>/lease.json
  state/<server-instance-uuid>/panes/<pane-uuid>.json
```

Managed directories use `0700`; files use `0600`. Existing unsafe permissions are rejected, never silently loosened or repaired. All managed ancestry must be real directories; symbolic links and hard-linked/non-regular log files are rejected. A custom data root's parent must already exist and be a canonical absolute path (`/private/tmp/...`, not the macOS `/tmp` symlink, for example).

Inactive logs expire seven days after their last modification. Under disk pressure, oldest inactive logs can be removed earlier. Cleanup runs on admission and periodically. Active logs are never truncated/deleted, including when panes are manually closed. Private leases protect logs across concurrent server instances. If only protected logs occupy the configured disk limit, new admissions fail.

The byte limit is an **admission and inactive-cleanup limit**, not a hard quota on external GLM writers. An external writer can exceed it; the monitor cannot bound that writer without changing agent behavior. Configure filesystem quotas or writer limits separately if a hard ceiling is required. Limits on workspaces/windows/panes apply per server process.

On monitor shutdown/crash or workspace closure while agents may still run, their leases remain conservative protection. After a restart, the monitor cannot know whether an external writer has stopped and does not automatically reclaim orphaned protected logs. Confirm every referenced GLM writer is stopped before manually removing that old instance's lease; subsequent cleanup then applies retention. Metadata directories are small but are also left for this inspection. No cleanup tool accepts arbitrary file paths.

## Configuration

Set only these optional environment variables in the MCP launch configuration. If using `/usr/bin/env -i`, add them as `KEY=value` arguments **before** the Node path. Values are integers except `DATA_DIR`; invalid values stop startup.

| Variable (prefix `GLM_MONITOR_`) | Default | Allowed |
| --- | --- | --- |
| `DATA_DIR` | `~/.glm-agent-monitor` | Canonical absolute local path; parent exists |
| `RETENTION_DAYS` | 7 | 1–3650 |
| `MAX_DISK_BYTES` | 1073741824 (1 GiB) | 1024–Number.MAX_SAFE_INTEGER |
| `MAX_WORKSPACES` | 8 | 1–64 |
| `MAX_PANES_PER_WINDOW` | 4 | 1–32 |
| `MAX_WINDOWS_PER_WORKSPACE` | 4 | 1–16 |
| `MAX_TOTAL_AGENTS` | 4096 | 1–100000 registrations per server lifetime |
| `MIN_COLUMNS` | 30 | 10–200 per resulting pane |
| `MIN_ROWS` | 6 | 3–100 per resulting pane |
| `APPLESCRIPT_TIMEOUT_MS` | 10000 | 100–60000 |
| `MAINTENANCE_INTERVAL_MS` | 10000 | 1000–300000 |

The viewer's poll interval is 100 ms, heartbeat interval 2 s, heartbeat expiry 15 s and output-stall bound 15 s. The request queue admits at most 256 pending operations and the stdio input buffer is capped at 1 MiB. Child environments contain only local HOME/PATH/LANG, plus TERM for viewers. API keys, tokens, NODE_OPTIONS, startup hooks, and unrelated environment variables are not forwarded.

## Tests and audits

```sh
npm test
npm run test:package
npm run audit:licenses
npm audit --omit=dev
npm run test:macos
```

The ordinary suite uses mocked iTerm2 plus real private temporary files, real SDK stdio round trips, a network-denial preload, lifecycle/concurrency tests, ANSI streaming tests and an exactly-once fake-agent output test. It does not contact GLM or run native iTerm2 operations. Invoking `test:macos` explicitly opts into native operations on newly created UUID-owned test workspaces. It verifies live output and actual 2×2 dimensions. Running the native test file directly without `GLM_MONITOR_MACOS_TESTS=1`, or on another platform, reports a skip, not a native pass. Dependency installation and `npm audit` contact npm; the running server does not.

See the [verification record](https://github.com/jaddoueik1/iterm-mcp/blob/main/docs/verification.md) for the checks run on this project.

## Releases and npm publishing

CI runs the ordinary tests and an actual tarball installation test on Linux/macOS with Node 22 and 24. Native iTerm2 tests stay opt-in on a graphical Mac. All GitHub Actions are pinned to verified commit hashes and use MIT-licensed official actions.

After committing a stable version in `package.json` and the lockfile, push its matching tag:

```sh
npm version patch
git push origin main --follow-tags
```

The `Release npm tarball` workflow checks tag/version agreement and main-branch ancestry, runs tests, packs the compiled distribution and creates a GitHub Release with its `.tgz` asset. Published tarballs require no TypeScript/build tools or install scripts. The local `dist/` stays available but is excluded from Git; the release package includes it explicitly. Never move/reuse a released tag or replace a released tarball; increment the version.

Publishing to npmjs.com requires npm account authorization separately from GitHub access. For the first publication, sign into your npm account and publish this package after its checks:

```sh
npm login
npm publish --access public
```

Then configure the package's npm **Trusted Publisher** as GitHub owner `jaddoueik1`, repository `iterm-mcp`, workflow `publish-npm.yml`, allowing direct `npm publish`. In GitHub repository **Settings → Secrets and variables → Actions → Variables**, set `NPM_PUBLISH_ENABLED=true`. Subsequent version-tag pushes publish automatically with OIDC and provenance. As an alternative for bootstrapping, configure a granular npm publishing token in the GitHub Actions secret `NPM_TOKEN`; never put it in source or MCP configuration. See [npm trusted publishing](https://docs.npmjs.com/trusted-publishers/).

You can manually run `Publish to npm` from Actions after selecting the exact version tag. Selecting `main` is rejected. Until npm credentials/trust are configured, the npm publishing job is skipped on tag pushes; GitHub Release tarballs are still created and usable by npx. The running monitor has no update or publishing capability.

## Troubleshooting and security limits

- **No tools / server exits:** run `npm run build`, check the absolute Node/entrypoint paths with `claude mcp get glm-agent-monitor`, and check `/mcp`. The server's stdout is reserved for MCP; diagnostics use stderr.
- **Automation denied or native timeout:** grant the hosting application permission to control iTerm2. A modal close confirmation can block AppleScript; choose an appropriate iTerm2 profile setting for monitored command exits. Inspect only dedicated monitoring windows after a timeout. An Apple event can finish after its caller times out; the helper is stopped, but an unreturned window/session ID is never guessed or adopted.
- **Pane missing:** Claude must keep observing the actual GLM process and report completion. The server does not reopen a pane by relaunching GLM.
- **Workspace refuses closure:** remove any manually added unrelated sessions yourself or restore the intended ownership context. The server will not force-close them. Retry `close-workspace` after resolving the conflict.
- **Disk admission blocked:** complete outstanding agent lifecycle cleanup or inspect orphaned leases after confirming writers stopped. Never delete an active writer's log to make space.
- **Custom root rejected:** remove symlinks from the configured ancestry and use private owner-only directories. The server rejects world/group-accessible managed files and directories.
- **Output appears buffered:** GLM and its runtime control their own buffering when output is redirected. The monitor cannot force another process to flush. Keep the existing consumer/mirroring strategy and agent settings.

The OS user, root, installed Node runtime, repository build and iTerm2 installation/profile are trusted. Same-user malicious processes can modify application code, markers and files; filesystem checks reduce accidental and cross-user exposure but cannot sandbox a hostile owner racing path checks. iTerm2's own profile triggers, logging, integrations or network features are outside this server's control. Use a trusted, local profile without automatic output actions. See [SECURITY.md](SECURITY.md) for the full threat model.

TDQS

A3.7/5.0

Scored across 5 tools

Disambiguation4/5

Each tool maps to a distinct object+action pair (open/close pane, open/close workspace, list panes), and descriptions explicitly clarify boundaries such as 'does not terminate the agent' and 'does not launch agents'. Minor overlap remains between open-agent-pane and open-workspace since a first pane appears to implicitly establish workspace context, but the descriptions largely resolve this.

Naming Consistency5/5

All five tools follow a strict kebab-case verb_noun pattern (open-agent-pane, close-agent-pane, open-workspace, close-workspace, list-agent-panes). The open/close/list symmetry across the two resources makes the set highly predictable.

Tool Count5/5

Five tools is a tight, well-scoped surface covering create/teardown for both panes and workspaces plus enumeration. Each tool clearly earns its place with no redundancy.

Completeness3/5

The open/close lifecycle for panes and workspaces plus listing is covered, but a monitor server has no tool to read agent log contents, query agent status, or observe completion state — the client must infer these externally. This is a notable gap for the stated monitoring purpose, though the descriptions suggest the design intentionally avoids log exposure.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues