# MCP client over stdio

`Bootgly\CLI\MCP\Client` is the **stdio** transport of the
**[MCP client](/manual/API/RPC/MCP_Client/overview/)**: it launches an MCP server as a child
process and speaks newline-delimited JSON-RPC with it — one message per line on the child's stdin,
the answers read from its stdout. It is the other side of
**[MCP over stdio](/manual/CLI/MCP/overview/)**, the transport a Bootgly server uses when an MCP
client launches it.

## Launch a server and call a tool

Many MCP servers ship as a command. Give the transport the command as an argv list, the client
your application's name and version, and call:

```php
use Bootgly\API\RPC\MCP_Client;
use Bootgly\CLI\MCP\Client;

$Client = new MCP_Client(
   new Client(
      ['npx', '-y', 'some-mcp-server'],
      environment: ['ENGINE_API_KEY' => $key]
   ),
   name: 'App',
   version: '1.0.0'
);

$result = $Client->call('search', ['query' => 'bootgly']);
$Client->close();
```

The child is started on the first message, not by the constructor. The transport **blocks the
caller** while the server answers: use it in **[commands](/manual/CLI/Commands/overview/)** and
jobs, never in a request handler. What `call()` returns, and how the client agrees on a protocol
era, is the same on every transport: see the **[MCP client](/manual/API/RPC/MCP_Client/overview/)**.

## The command and its environment

- **The command** is an argv list of strings, run without a shell, in `directory` (the parent's
  when null). The first (the program) must not be empty. No argument, no `directory` and no
  `environment` name or value may hold a NUL byte, and the `environment` maps string names to
  string values. The constructor refuses anything else (`InvalidArgumentException`, naming no
  value). If PHP still refuses the start, the message fails as `Transport` with PHP's reason
  alone: the environment never reaches an exception trace.
- **The environment** is an allowlist of the parent's (`Client::ENVIRONMENT`: `PATH`, `HOME`,
  `USER`, `LOGNAME`, `SHELL`, `TERM`, `LANG`, `TMPDIR`) plus the `environment` you give —
  credentials go there. `inherit: true` passes the whole parent environment instead. The
  variables you give win over the parent's.
- **The descriptors** the parent holds (its sockets, its files) never reach the child: each one
  it would inherit is set to `/dev/null` there. They are read from `/proc/self/fd` on Linux and
  from `/dev/fd` elsewhere. Starting the child takes one more descriptor for each one mapped, so
  the soft open-files limit is raised by exactly that for the moment (within the hard limit) and
  restored right after (the child keeps the raised limit). When that leaves no room for the
  mapping (the soft limit already equals the hard one, as `ulimit -n` sets it, the hard limit caps
  the raise, or ext-posix is missing — in any language the system speaks), or when the descriptors
  cannot be listed (an `open_basedir` that leaves out `/proc` and `/dev`), they are closed in the
  child instead: a shell (`/bin/sh`, else `/bin/bash --posix`) closes every descriptor above 2 it
  finds open and `exec`s your command, which keeps the process id. A program named without a `/`
  is found on the parent's `PATH` as a direct start finds it: relative entries are read from
  `directory`. On that path the server's environment gains `PWD` and `SHLVL` and loses
  `SHELLOPTS`, `BASHOPTS`, the `BASH_FUNC_*` functions and any `BOOTGLY_L_*` variable (the
  launcher's own names), and a program that cannot be run fails
  the message as the server exiting (the shell's reason goes to the `Sink`) — so does a shell
  that cannot list the descriptors either (no `/proc/self/fd`, no `/dev/fd`): it runs nothing
  rather than let them through. When even the three
  pipes find no free descriptors, the start fails (`Transport`, naming the limit to raise). A host
  whose only shell cannot close descriptors above 9 (`dash` without `bash`) cannot take that path:
  there the start fails too, saying why.

The `environment` never reaches a dump: `var_dump()`, `print_r()` and Bootgly's `Dumper` show it
redacted.

## stderr and what is skipped

A server writes its diagnostics to stderr. Give the transport a `Sink` closure to keep them; without
one they are read and dropped, so a chatty server never fills its pipe and stalls. What a server
writes as it exits (its last words, a fatal trace) reaches the `Sink` too. A `Reporter`
closure is told of the lines the transport skips:

```php
use Bootgly\API\RPC\MCP_Client\Failure;
use Bootgly\CLI\MCP\Client;

$Transport = new Client(
   ['some-mcp-server', '--stdio'],
   Sink: static function (string $chunk) use ($Log): void {
      $Log->write($chunk);
   },
   Reporter: static function (Failure $Failure) use ($Log): void {
      $Log->write($Failure->getMessage());
   }
);
```

Every line the child writes to stdout is one of these:

- **The awaited answer** — the response with the request's id: returned to the client.
- **A refusal that names no request** — `id: null` with Parse error (`-32700`) or Invalid Request
  (`-32600`). A server answers this for a line it could not read; the Bootgly server answers it
  for a line past its bound. It is the awaited request's refusal, and the call fails at once with
  a `Rejection`. While a request given up on — past its timeout, or failed on an answer line past
  `line` — has seen neither its own answer nor a later request's, the refusal may belong to that
  request instead: it is dropped, and the awaited request waits for its own answer.
- **A notification** — skipped.
- **A server request** — in the session era a `ping` is answered `{}` and any other request
  Method not found (sampling, elicitation and roots included: the client declares no
  capabilities); in the stateless era a server request breaks the protocol: skipped and reported.
- **An answer to an earlier request** — one that arrives late, after a timeout: dropped.
- **A line that is not JSON** — skipped and reported (`Protocol`).

What `Sink` or `Reporter` throws is dropped: the conversation goes on.

## The era of a launched server

The first message probes the era with `server/discover`, like on HTTP — but the probe waits at most
`MCP_Client::PROBE` seconds (`5`), and an error, silence or the process exiting all mean the legacy
era: the client sends `initialize` next (to a new process when the first one exited). A server that
answers unknown methods at once costs no wait.

The verdict is remembered per process by the command, the directory, the environment and
`inherit` — kept as a keyed digest, so the digest of a credential in the environment cannot be
checked against guesses. A client built for each job does not probe the same server every time.

## Timeouts and the line bound

- **`timeout`** (30 seconds) is how long one request waits for its answer, from the moment it is
  sent, including the start of a child it needs. A span past the monotonic clock's range (`INF`,
  `PHP_INT_MAX`) waits without a deadline, as on HTTP. A timeout that is not a positive number
  (`NAN`) is refused when the transport is built. Past the timeout the call fails (`Timeout`) —
  the tool **may have run** — and the client tells the server with `notifications/cancelled`,
  best effort and within `MCP_Client::CANCEL` seconds. The process keeps running; its late answer
  is dropped.
- **`line`** (4 MiB, the Bootgly server's own bound) is the longest line read, in bytes, the
  newline excluded. An answer line past it fails the request (`Protocol`); the rest of that line
  is skipped and the process keeps running.

## The child's life

- **An exit** fails the message in flight (`Transport`); the next message starts a new process.
  A server that exited while idle is started again for the next message (in the legacy era after
  a new `initialize`). A server that closes its stdin fails the message (`Transport`) the same way.
- **The wait** on the pipes is `stream_select`, so they must be numbered below `FD_SETSIZE` (1024
  by default): a process already holding that many descriptors gets a `Transport` failure naming
  it at once. A signal that cuts the wait short is waited through.
- **`close()`** (and destruction) closes stdin, waits `Client::GRACE` seconds, then sends
  `SIGTERM`, waits again, then `SIGKILL`. It is safe to call twice; the next message starts a new
  child. `$Transport->pid` is the running child's process id, `0` when none runs.

## Limits

- **POSIX only:** the constructor throws `RuntimeException` on Windows (`stream_select` cannot
  wait on process pipes there).
- **It blocks the caller:** one request at a time, in commands and jobs.
- **Grandchildren.** `close()` stops the direct child; a wrapper that starts another process
  (`npx`, `uvx`, a shell script) may leave it running.

## Reference

```php
public function __construct (
   array $command,
   null|string $directory = null,
   array $environment = [],
   bool $inherit = false,
   int|float $timeout = 30,
   int $line = 4_194_304,
   null|Closure $Sink = null,
   null|Closure $Reporter = null
)
```

Creates the transport for one server command. `$command` is the argv list (strings, no shell);
`$directory` the child's working directory (null: the parent's); `$environment` the variables
over the allowlist; `$inherit` passes the parent's whole environment instead of the allowlist;
`$timeout` the seconds one request waits; `$line` the longest line read, in bytes; `$Sink`
(`fn (string $chunk): void`) receives the child's stderr; `$Reporter`
(`fn (Failure $Failure): void`) is told of what the transport skips. Throws `RuntimeException` on
Windows, and `InvalidArgumentException` for: an empty command or program; a command that is not a
list or holds a non-string; an argument, `$directory` or `$environment` name or value holding a
NUL byte; an `$environment` name or value that is not a string; a `$timeout` that is not a
positive number (`NAN`); or a `$line` below `1`. A `$timeout` past the clock's range (`INF`) waits
without a deadline.

```php
public function send (Exchange $Exchange): Reply
```

Writes one message to the child — starting it first when none runs — and, for a request, reads
until the answer with its id arrives, or a refusal that names no request (`id: null`, Parse error
or Invalid Request) and can only be its own. Called by the client, not by your code. Throws
`Failure` of kind `Transport` (the child exited, closed its stdin or cannot start — the last with
PHP's reason only), `Timeout` (past the deadline) or `Protocol` (an answer line past `$line`).

```php
public function prepare (): void
```

Releases a child that exited while idle, so the next message starts another (and, in the legacy
era, the client opens a new session first).

```php
public function close (): void
```

Stops the child: closes its stdin, waits, `SIGTERM`, waits, `SIGKILL`. Safe to call twice.

```php
public private(set) array $command;
```

The argv list.

```php
public private(set) null|string $directory;
```

The child's working directory; null: the parent's.

```php
public private(set) bool $inherit;
```

Whether the child gets the parent's whole environment instead of the allowlist.

```php
public private(set) int|float $timeout;
```

The seconds one request waits for its answer; `INF` (any span past the monotonic clock's range)
means no deadline.

```php
public private(set) int $line;
```

The longest line read from the child, in bytes (the newline excluded).

```php
public private(set) int $pid;
```

The running child's process id; `0` when none runs.

```php
Client::ENVIRONMENT
```

The parent's variables the child gets by default: `PATH`, `HOME`, `USER`, `LOGNAME`, `SHELL`,
`TERM`, `LANG`, `TMPDIR`.

```php
Client::GRACE
```

The seconds (`1`) the child gets to exit after its stdin closes, then again after `SIGTERM`.
