Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 15 additions & 11 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,26 +55,28 @@ Keep this accurate — it's the navigation aid. One row per non-test file (`test
| `src/main.rs` | entry: CLI parse, Sentry + tracing init, config load, serve with a 10s graceful drain (`DRAIN_DEADLINE`); dispatches `set-auth` (writes creds, then revokes every session) and the admin subcommands. Tests in `src/main_tests.rs` |
| `src/cli.rs` | clap command definitions (`serve`/`set-auth`/`jobs`/`job kill`/`sessions [--revoke]`) |
| `src/app.rs` | builds the axum router: `/mcp` (rmcp `StreamableHttpService` behind `auth::require_auth`) + the OAuth routes, both behind the `Host` allowlist guard; `/healthz` outside it; the shutdown token that ends every SSE stream. In-process router tests in `src/app_tests.rs` |
| `src/admin.rs` | local admin subcommands (`jobs`/`job kill`/`sessions [--revoke]`): open the existing DB (`Db::open_existing` — no create, no migration) through `jobs::JobRepo` / `oauth` — never builds a `JobStore` (that would start a reaper + reconcile and fail the live server's running rows); `job kill` only renders `jobs::kill_persisted`'s `KillOutcome`. Never prints token values |
| `src/agent.rs` | `Agent`: the OAuth client behind a request or a job — `client_id` + `ClientName` (the DCR `client_name`, untrusted: control/invisible chars stripped, whitespace collapsed, ≤32 chars), shown as `label()` = `<name>#<4-hex of SHA-256(client_id)>`; `Debug` shows only the label. Tests in `src/agent/tests.rs` |
| `src/admin.rs` | local admin subcommands (`jobs` with a `BY` owner column/`job kill`/`sessions [--revoke]`, which also lists each logged-in agent's last activity): open the existing DB (`Db::open_existing` — no create, no migration) through `jobs::JobRepo` / `oauth` — never builds a `JobStore` (that would start a reaper + reconcile and fail the live server's running rows); `job kill` only renders `jobs::kill_persisted`'s `KillOutcome`. Never prints token values |
| `src/config.rs` | env + TOML file config; fails fast on missing/empty creds or a non-loopback bind without `MCP_SSH_ALLOWED_HOSTS`; clamps `inline_timeout` ≤60s; `Password` with redacted `Debug`; TOML parse errors scrubbed of the file's text. `db_path()` resolves the DB path alone for the cred-free admin commands |
| `src/config/set_auth.rs` | `set-auth`'s config write: atomic replace, 0600 from the first byte, owner adopted from the config dir |
| `src/db.rs` | SQLite connection (`rusqlite`, `bundled`): open/create (file 0600, WAL), `open_existing` for the admin CLI, one serialized connection driven via `spawn_blocking`, typed `DbError`. DB at `/var/lib/mcp-ssh/mcp-ssh.db`. Queries live in the repositories (`src/jobs/store.rs`, `src/oauth/store.rs`) |
| `src/db/migrations.rs` | the schema (`jobs` incl. `interactive`, hashed `access_tokens`/`refresh_tokens`/`refresh_tombstones`, `clients`) as ordered forward-only steps versioned by `PRAGMA user_version`, each in its own `BEGIN IMMEDIATE` transaction. Append only |
| `src/auth.rs` | bearer-only guard for `/mcp` (`require_auth`; store outage → 503, not 401; a streaming response keeps re-checking its token — see `src/auth/revalidate.rs`) and `check_login`, the constant-time credential check the consent form uses. No HTTP Basic |
| `src/db/migrations.rs` | the schema (`jobs` incl. `interactive` and the owner's `client_id`/`client_name`, `clients` incl. `client_name`/`last_used_unix`, hashed `access_tokens`/`refresh_tokens`/`refresh_tombstones`, `clients`) as ordered forward-only steps versioned by `PRAGMA user_version`, each in its own `BEGIN IMMEDIATE` transaction. Append only |
| `src/auth.rs` | bearer-only guard for `/mcp` (`require_auth`; puts the bearer's `Agent` in the request extensions for the tools; store outage → 503, not 401; a streaming response keeps re-checking its token — see `src/auth/revalidate.rs`) and `check_login`, the constant-time credential check the consent form uses. No HTTP Basic |
| `src/auth/revalidate.rs` | re-checks an open `/mcp` stream's token on an interval (`STREAM_REVALIDATE`, 30s) and ends the body once it is revoked or expired; holds the token hash, never the bearer; a store outage keeps the stream |
| `src/oauth/mod.rs` | minimal OAuth 2.1 server wiring: `AuthState` (creds, store, public URL, the stream re-check interval), the public routes (discovery, `/authorize` GET+POST, `/token`, `/register`) with a 64 KiB body limit |
| `src/oauth/metadata.rs` | RFC 8414 / RFC 9728 discovery documents; `base_url` from `MCP_SSH_PUBLIC_URL` else the allow-listed `Host` |
| `src/oauth/flow.rs` | `/authorize`: GET validates (registered `client_id` + exact `redirect_uri`, else `invalid_request`; PKCE S256) and renders the consent page — never a code; POST takes the single-use CSRF nonce + credentials and only then redirects with a code. Flat delay on a failed login; redirect-URI rule |
| `src/oauth/flow/token.rs` | `/token`: `authorization_code` (code + PKCE verifier) and `refresh_token` grants; `no-store`; store outage → 503 |
| `src/oauth/flow/register.rs` | `/register`: Dynamic Client Registration (RFC 7591), bounded URIs per client |
| `src/oauth/flow/register.rs` | `/register`: Dynamic Client Registration (RFC 7591), bounded URIs per client, optional `client_name` cleaned by `ClientName::parse` before it is stored |
| `src/oauth/consent.rs` | the consent page HTML: static template, escaped values, `no-store`, CSP `frame-ancestors 'none'`, `X-Frame-Options: DENY` |
| `src/oauth/pending.rs` | `Pending<T>`: bounded, TTL'd, single-use in-memory map for consent requests and auth codes (10 min) |
| `src/oauth/secret.rs` | random 256-bit tokens, SHA-256 `hash_token` (how tokens are stored and looked up), PKCE S256 + verifier rules |
| `src/oauth/store.rs` | `Store`: the OAuth repository facade — lifetimes (access 24h, refresh 30d, family 90d, client grace 7d, ≤1000 clients), codes/consents, issue + validate; typed `GrantError`/`StoreUnavailable`/`RegisterError`. Only token hashes reach the DB |
| `src/oauth/store/pair.rs` | token pairs: mint + insert within a login family; refresh rotation with reuse detection (a replayed refresh token revokes its whole family via tombstones) |
| `src/oauth/store/clients.rs` | registered clients: persist `client_id`→redirect URIs (no secrets), cap, exact-match check for `/authorize` |
| `src/oauth/store/clients.rs` | registered clients: persist `client_id`→redirect URIs + cleaned name (no secrets), cap, exact-match check for `/authorize` |
| `src/oauth/store/presence.rs` | who is on the host: `authenticate` (bearer hash → `Agent`, noting last use at most once a minute per client), `active_agents` (used a bearer within `PRESENCE_WINDOW`, 15 min), `logged_in_agents` (for `mcp-ssh sessions`). Never reads a token |
| `src/oauth/store/sweep.rs` | `revoke_all` (`sessions --revoke`, `set-auth`) and the reaper's `sweep_expired_access`/`sweep_expired_refresh`/`sweep_stale_clients` — counts only, never a token value |
| `src/jobs/mod.rs` | job engine facade: `JobStore` wiring (`new` spawns the reaper), public types (`JobState`, `RunResult`, `JobSummary`, `JobList`, `JobError`), `list` (paged, ≤200) and `kill` |
| `src/jobs/mod.rs` | job engine facade: `JobStore` wiring (`new` spawns the reaper), public types (`JobState`, `JobMeta` — title + owning `Agent`, `RunResult`, `JobSummary`, `JobList`, `JobError`), `list` (paged, ≤200), `owner` and `kill` |
| `src/jobs/run.rs` | launching: reserve id + 0600 log (`create_new`), spawn in its own process group (`sh -c` or `bash -ic`), hand to the supervisor, wait out the inline window |
| `src/jobs/supervise.rs` | the supervisor task: owns a job from spawn to its recorded final state (survives request cancellation), enforces the 256 MiB live log cap (`LOG_CAP`; `SIGKILL` past it) — on leftovers too, until the group is gone — maps exit/signal to `JobState` |
| `src/jobs/poll.rs` | poll: status + one newest-first page from the live log, else the tail saved in the row |
Expand All @@ -87,15 +89,16 @@ Keep this accurate — it's the navigation aid. One row per non-test file (`test
| `src/jobs/reaper/compact.rs` | log compaction: trim finished jobs' logs to their last 5000 lines (<3h since finish) / 500 after, ≤4 MiB, idempotent marker |
| `src/jobs/shell.rs` | `Shell`: how a user command is launched — bare `sh -c` (default) vs. interactive `bash -ic` (sources `~/.bashrc` for aliases/version managers) |
| `src/jobs/status.rs` | `JobStatus`: the bare `jobs.status` word (`running`/`exited`/`failed`); the one place the on-disk strings are spelled |
| `src/jobs/store.rs` | `JobRepo`: the `jobs` repository the engine, reaper and admin CLI call (insert, finish with the saved tail — 500 lines, ≤256 KiB — find, paged summaries, listing). No `cmd` text reaches a query or a log line |
| `src/jobs/store.rs` | `JobRepo`: the `jobs` repository the engine, reaper and admin CLI call (insert with the owner, finish with the saved tail — 500 lines, ≤256 KiB — find, owner, paged summaries, listing). No `cmd` text reaches a query or a log line |
| `src/jobs/store/row.rs` | row⇄domain mapping: typed rows, `JobState` onto `(status, code, error)` and back |
| `src/jobs/store/fail.rs` | recording `failed` for a job this writer may not own (kill, reconcile) — only while the row still reads `running`, or replacing a bare `killed by signal N` the engine recorded; plus re-recording a finished job `failed` when the supervisor killed its leftovers over the log cap |
| `src/jobs/store/reap.rs` | the reaper's and reconcile's queries: untracked `running` rows, compaction/eviction candidates, deleting aged-out rows |
| `src/tools/mod.rs` | MCP tool surface (`#[tool_router]`/`#[tool]` from rmcp): 3 tools (`bash`/`job`/`file`) dispatching on `action`, their descriptions, one tracing span per dispatch. Thin adapters over jobs + files |
| `src/tools/mod.rs` | MCP tool surface (`#[tool_router]`/`#[tool]` from rmcp): 3 tools (`bash`/`job`/`file`) dispatching on `action`, their descriptions, one tracing span per dispatch (with the caller's `agent` label). Thin adapters over jobs + files |
| `src/tools/caller.rs` | the calling `Agent` (from the HTTP parts rmcp hands each tool), its span label, and `foreign_owner` — whose job `id` is, when not the caller's |
| `src/tools/args.rs` | arg structs for the 3 tools (`BashArgs`/`JobArgs`/`FileArgs`, all `deny_unknown_fields`; `JobAction`/`FileAction`) + `lenient_action` (non-string/missing `action` → `list`, unknown string → error) — schema shape only |
| `src/tools/render.rs` | agent-facing wording for `file`: `render_file`/`render_file_error` turn `FileOutcome`/`FileError` into sentences, markers and next-step hints |
| `src/tools/reject.rs` | the operator's log line for a `tools/call` refused before dispatch (args `Parameters<T>` rejects, or an unknown tool): tool + fixed reason word + `request_id` — never a key, value or serde message |
| `src/tools/job_render.rs` | agent-facing wording for `bash`/`job`: run/poll replies + the newest-first paging footer, list page + cursor, each `KillOutcome`, `JobError` |
| `src/tools/job_render.rs` | agent-facing wording for `bash`/`job`: run/poll replies + the newest-first paging footer, list page (presence line, `by` per job) + cursor, each `KillOutcome`, the `[started by another agent: …]` note, `JobError` |
| `src/tools/files.rs` | file operations' shared types (`FileOutcome`, typed `FileError` — a failed shell op keeps its `ShError`) + `list`/`grep` (shelled-out `ls`/`find -maxdepth 20`/`grep`). Returns facts, never a sentence |
| `src/tools/files/read.rs` | `read`: regular files only, forward by line, ≤1000 lines / 64 KiB a page, 8 KiB line clamp, 30s deadline |
| `src/tools/files/write.rs` | `write` (atomic temp sibling + rename, keeps mode, writes through a symlink) and `append` |
Expand Down Expand Up @@ -137,7 +140,7 @@ Current tools (three, constant):
| Tool | Params | Does |
|---|---|---|
| `bash` | `cmd`, `cwd?`, `timeout?`, `bg?`, `interactive?`, `title?` | run a command; inline if fast, else a job id (`bg` backgrounds at once; `timeout` ≤600; `interactive` sources `~/.bashrc` via `bash -ic` for aliases/version managers, default fast `sh -c`; `title` labels the job id as `<title>-HH-MM-SS`) |
| `job` | `action?`, `id?`, `cursor?`, `limit?` | jobs by `action`: `poll` (newest-first page, byte cursor), `list` (default; newest first, ≤200 per page, offset cursor), `kill` (typed outcome) |
| `job` | `action?`, `id?`, `cursor?`, `limit?` | jobs by `action`: `poll` (newest-first page, byte cursor), `list` (default; presence line of agents active in 15 min, then newest first with `by` = `you`/agent label, ≤200 per page, offset cursor), `kill` (typed outcome). Another agent's job is pollable/killable; the reply names its owner |
| `file` | `action`, `path?`, `content?`, `pattern?`, `recursive?`, `src?`, `dest?`, `cursor?`, `limit?` | file ops by `action`: `read` (by line, ≤1000/64 KiB a page)/`write` (atomic)/`append`/`delete` (non-empty dir needs `recursive=true`; symlinks never followed)/`list`/`grep`/`move` (never overwrites) |

## Conventions
Expand All @@ -150,7 +153,7 @@ Non-negotiable: SOLID, SRP, tested code. The bar: idiomatic, boring, readable Ru
- Borrow by default (`&str` over `String`, `&[T]` over `Vec<T>`). `.clone()` only when ownership must move — non-obvious clone gets a one-line `// why`. `Arc<T>` for shared read-only; lock only when you mutate shared state, keep the critical section tiny.
- Functions do one thing. Need "and" to describe it → split it. Concrete first; introduce a trait when the **second** impl arrives.
- Async end-to-end. No `std::sync::Mutex` on the request path — use `tokio::sync`. Never hold a `std::sync` guard across `.await`. No `block_on`; offload blocking I/O with `spawn_blocking`.
- `tracing`, not `println`. Every tool dispatch is a span with `request_id` and `tool` name. A call refused before dispatch logs one `rejected` WARN (tool + reason word) instead.
- `tracing`, not `println`. Every tool dispatch is a span with `request_id`, `tool` name and the caller's `agent` label (never a `client_id`). A call refused before dispatch logs one `rejected` WARN (tool + reason word) instead.
- Derive, don't hand-roll (`Debug`, `Clone`, serde). Every public type derives `Debug`. Keep `pub` surface minimal.
- Comment the non-obvious *why*, never the *what*. Rename until the code doesn't need the *what*.

Expand Down Expand Up @@ -224,6 +227,7 @@ Non-negotiable: SOLID, SRP, tested code. The bar: idiomatic, boring, readable Ru
## Context (not in code)

- One host, one service user. Targets the box it runs on; not a fan-out / multi-host tool.
- Many agents may share the host at once (one OAuth client each). They see each other (presence, job owners) but are not isolated from each other: awareness, not multi-tenancy.
- TLS, multi-host routing, and rate limiting live in the reverse proxy, not here.
- NOT building: an SSH client, a fleet orchestrator, a job scheduler, a secrets vault.

Expand Down
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ You're in your car. From your phone, you point Claude at `https://your-vps/mcp`

Want to go further? Run `bash("claude -p 'fix the failing test and push'")` — **one agent supervising another agent** on your VPS. mcp-ssh is just the shell; what you run through it is up to you.

**Several agents, one host.** Any number of MCP clients can connect at once, each with its own login; their commands and jobs run side by side, never queued behind each other. They can see each other: `job(action="list")` opens with who is active (`2 agents active (last 15 min): you (Claude Code#4f2a), cursor#9b1c`) and marks each job `by` you or the agent that started it. Jobs are shared, not isolated — one service user — so an agent can poll or kill another's job, and the reply says whose it is.

## ⚡ Quickstart

**One-liner (Debian/Ubuntu)** — downloads the latest release, asks for a username + password, installs the service, and starts it:
Expand Down Expand Up @@ -106,9 +108,9 @@ mcp-ssh set-auth admin # prompts for the password
mcp-ssh serve # run the server (this is the default)
mcp-ssh set-auth <user> # configure the username/password (logs every client out)

mcp-ssh jobs # list running jobs (--all includes finished ones)
mcp-ssh jobs # list running jobs and which agent started each (--all includes finished ones)
mcp-ssh job kill <id> # SIGTERM then SIGKILL a job's process group
mcp-ssh sessions # summarise OAuth logins (token counts + next expiry)
mcp-ssh sessions # summarise OAuth logins (token counts, next expiry, each agent's last activity)
mcp-ssh sessions --revoke # end every login: all clients must log in again
```

Expand Down
4 changes: 2 additions & 2 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,8 @@ A single SQLite database at `/var/lib/mcp-ssh/mcp-ssh.db` (sibling of the job-lo
**In SQLite — durable, survives restarts:**

- **OAuth tokens** — `access_tokens` and `refresh_tokens`, stored only as SHA-256 hashes (a copy of the DB yields no usable bearer), each bound to its client and login family. Logins survive a service restart — which matters because the agent can self-update and restart itself. Access tokens last 24h; refresh tokens 30 days, rotated on use, within a 90-day family cap; a replayed (already-rotated) refresh token ends its whole family.
- **Registered clients** — `clients` (`client_id` → redirect URIs, no secrets), capped at 1000; a client at least 7 days old that holds no live token is swept.
- **Job metadata** — id, title, status (`running`/`exited`/`failed`), exit code or error, start/finish time, process group + boot id, and a saved **output tail** (last 500 lines, ≤256 KiB). This is what makes `job(action="list")` show history across restarts.
- **Registered clients** — `clients` (`client_id` → redirect URIs, the cleaned `client_name` it registered, when it last used a bearer; no secrets), capped at 1000; a client at least 7 days old that holds no live token is swept. The last-use time is rewritten at most once a minute per client, so a busy agent's requests stay reads; it is what `job(action="list")`'s presence line and `mcp-ssh sessions` read.
- **Job metadata** — id, title, status (`running`/`exited`/`failed`), exit code or error, start/finish time, process group + boot id, the OAuth client that started it (id + name, so the owner still reads right after the client is swept), and a saved **output tail** (last 500 lines, ≤256 KiB). This is what makes `job(action="list")` show history across restarts.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minor · docs docs/architecture.md:64 still says job(action="list") "exposes only the id and state", but ListedJob (src/tools/job_render.rs:46) now adds by, and every list reply opens with a presence line. Update line 64 (and the job row in README.md:74) to mention by and the presence line, while keeping the claim that command text is never exposed.


**On the filesystem — the high-frequency path:**

Expand Down
11 changes: 11 additions & 0 deletions docs/changelog/unreleased.md
Original file line number Diff line number Diff line change
@@ -1 +1,12 @@
# Unreleased

### Added

- **Agents sharing a host can see each other.** `job(action="list")` opens with the agents (OAuth clients) that used the host in the last 15 minutes, the caller marked `you` — e.g. `2 agents active (last 15 min): you (Claude Code#4f2a), cursor#9b1c` — and each job gains `by`: `you`, the agent that started it, or `unknown` for older jobs. Polling or killing another agent's job still works (one service user), and the reply opens with `[started by another agent: …]`.
- `mcp-ssh jobs` shows a `BY` column; `mcp-ssh sessions` lists each logged-in agent with when it was last active.
- An end-to-end test proves two separately logged-in agents run commands and background jobs side by side without waiting on each other.

### Changed

- **Schema version 7.** `jobs` gains `client_id`/`client_name`; `clients` gains `client_name`/`last_used_unix`. An older binary, including its admin CLI, refuses a migrated database. A `client_name` from client registration is cleaned before it is stored or shown: control and invisible characters dropped, whitespace collapsed, at most 32 characters.
- `job(action="list")` is no longer bare JSON: the presence line comes first.
Loading
Loading