# MCP client

`Bootgly\API\RPC\MCP_Client` lists and calls the tools of **another** MCP server — a rendering
engine, a search service, a local tool an AI vendor ships as a command. It speaks both protocol
eras on its own: the stateless revision `2026-07-28` when the server offers it, and the session
revisions (`initialize` first) otherwise. The wire is a transport you hand it:

- **Streamable HTTP** — `Bootgly\WPI\Nodes\MCP_Client_CLI`, for a server behind a URL. See
  **[MCP client over HTTP](/manual/WPI/HTTP/HTTP_Client_CLI/MCP/overview/)**.
- **stdio** — `Bootgly\CLI\MCP\Client`, for a server you launch as a child process. See
  **[MCP client over stdio](/manual/CLI/MCP/Client/overview/)**.

The client is minimal on purpose: tools only (list and call), answers read whole, a token hook
instead of an OAuth flow. **[What it leaves out](#limits)** is listed at the end.

## Call a tool

Build a transport, the client over it with your application's name and version, and call:

```php
use Bootgly\API\RPC\MCP_Client;
use Bootgly\WPI\Nodes\MCP_Client_CLI;

$Client = new MCP_Client(
   new MCP_Client_CLI('https://engine.example.com/mcp'),
   name: 'App',
   version: '1.0.0'
);

$tools = $Client->walk();                       // every tool, page after page
$result = $Client->call('render', ['scene' => 42]);

$Client->close();
```

`call()` returns the tool's result decoded: `content`, `structuredContent`, `isError`… —
**[reading results](#reading-results)** shows what to take from it. `walk()` returns every tool
the server lists (each one an array with `name`, `inputSchema`, …); `list()` returns one page when
you want to page yourself. The code is the same over stdio — only the transport changes — and
inside a request handler the HTTP transport takes the deferral's `Response`
(**[from a request handler](/manual/WPI/HTTP/HTTP_Client_CLI/MCP/overview/#call-a-tool-from-a-request-handler)**).

One client per transport: a second `MCP_Client` on a transport already in use throws
`LogicException` — keep the client (and its transport) for as long as you need the server.
Neither is ever copied: `clone` of a client or a transport throws `LogicException` too.

## Protocol eras

The first request decides the era. The client sends `server/discover`: a server that answers it
is called without a session, every request carrying its revision, capabilities and client
information in `_meta`; any other answer falls back to `initialize` and a session (the
`Mcp-Session-Id` header on HTTP, the running process on stdio), which `close()` ends — on HTTP
with a `DELETE`, which an `initialize` answer the client refuses (a revision it does not speak, no
tools) also gets, for the session that answer opened. Either way the code above does not change — `$Client->revision` and
`$Client->stateless` tell you which one was agreed.

The verdict is remembered per worker by the transport's peer — the server's URL on HTTP, the
command and its environment on stdio — so a client built for each job does not probe every time.
A failed probe (a `5xx`, a `408` or `429`, a timeout) remembers nothing: the next client asks again. A server
remembered as legacy that now refuses `initialize` (it moved to the stateless era) is probed
again, once; so is a stateless server that answers a call with `-32022` (a revision it no longer
speaks), and the call is sent again. What each transport reads as the probe's answer, and the
other answers that send a call again, are on its page.

## Reading results

A tool's result arrives as the server sent it, decoded into arrays:

```php
$result = $Client->call('render', ['scene' => 42]);

if (($result['isError'] ?? false) === true) {
   // the tool ran and failed: its content explains why
}

$data = $result['structuredContent'] ?? null;     // the tool's typed output, when it has one
foreach ($result['content'] ?? [] as $block) {
   match ($block['type']) {
      'text' => print($block['text']),
      'resource_link' => print($block['uri']),
      default => null
   };
}
```

- **`isError: true`** is a tool failure, reported as a result — never an exception.
- **`structuredContent`** is returned as decoded, not validated against the tool's
  `outputSchema`: check what you rely on.
- **`{}` and `[]`** decode alike (an empty array). On the way out the client keeps objects:
  empty `arguments`, capabilities and `_meta` go as `{}`; for a nested empty object pass
  `new stdClass`.

When a stateless server answers `input_required`, the client resends the call with the server's
`requestState`, unchanged, up to `MCP_Client::RESENDS` times. The server's `inputRequests` are not
served: an answer that carries them fails (`Protocol`), and so does one without a `requestState`.

## Errors

Two exceptions, one rule: **a server's JSON-RPC error is a `Rejection`, anything else is a
`Failure`.**

- **`MCP_Client\Rejection`** — the server answered an error: `getCode()`, `getMessage()` and
  `$data`.
- **`MCP_Client\Failure`** — no MCP answer: branch on `$kind` (`MCP_Client\Failure\Kinds`):
  - `Transport` — no answer: the connection failed or dropped, a `5xx`, a `408` or a `429`, the
    stdio server exited. Trying again may help.
  - `Timeout` — the deadline passed. The tool **may have run**: retrying blindly may run it twice.
  - `Protocol` — an answer that is not the MCP answer: a redirect, an unexpected status or media
    type, a malformed message, too many `input_required` rounds, a walk past its bounds.
  - `Authentication` — `401`/`403`: `$status` and `$challenge` are set.
  - `Version` — client and server share no protocol revision.

A `Rejection` is deliberately **not** a `JSON\Fault`. Inside a tool of your own Bootgly MCP server,
an uncaught `Rejection` becomes your server's Internal error (`-32603`): a remote server's code and
data never leak out as your answer. Forward one on purpose:

```php
use Bootgly\API\RPC\JSON;

catch (Rejection $Rejection) {
   throw new JSON\Fault(JSON::INTERNAL_ERROR, 'The engine refused the job.');
}
```

## Limits

What the client does not do, so you can plan around it:

- **Answers are buffered.** Every answer is read whole before it is decoded; on HTTP an
  event-stream answer is scanned for the response.
- **Answers are bounded.** An HTTP answer past the transport's `bytes` (4 MiB) fails
  (`Transport`); a stdio line past the transport's `line` (4 MiB) fails (`Protocol`); a message
  with more than `Transport::CONTAINERS` (131,072) arrays and objects fails (`Protocol`) before it
  is decoded. Decoded, an object costs some 420 bytes and a short string about twelve times its
  size, so the worst answer under both bounds takes about 25 times its size in memory — some
  95 MiB at the default 4 MiB: leave that much room in `memory_limit`, or lower the transport's
  bound.
- **A timeout is not a "no".** After a `Timeout` the tool may have run; a call with side effects
  needs an idempotency key of yours before you retry it.
- **No listening.** No `GET` listening stream, no `subscriptions/listen`: notifications outside
  an answer are never received.
- **No sampling, elicitation or roots.** The client declares no capabilities; a server request
  for them is answered Method not found (stdio) or skipped (HTTP).
- **No OAuth flow.** The HTTP transport's
  **[token hook](/manual/WPI/HTTP/HTTP_Client_CLI/MCP/overview/#the-token-hook)** is the
  integration point.
- **No destination vetting.** The HTTP transport dials whatever its URL names: vet the addresses
  in its **[`Resolution`](/manual/WPI/HTTP/HTTP_Client_CLI/MCP/overview/#tls-and-the-destination)**
  closure when the URL comes from users.
- **POSIX only and grandchildren** for stdio: see its
  **[limits](/manual/CLI/MCP/Client/overview/#limits)**.

## Reference

### MCP_Client

```php
new MCP_Client (Transport $Transport, string $name, string $version, null|Closure $Reporter = null)
```

The client over a transport. `name` and `version` are sent as `clientInfo`. `Reporter`
(`fn (Failure $Failure): void`) is told of what the client leaves out — a tool whose
`x-mcp-header` annotation is invalid, a server request skipped. Throws `LogicException` when
the transport already serves another client.

```php
$Client->list (null|string $cursor = null): array
```

One page of `tools/list`: the result as sent (`tools`, and `nextCursor` when more pages follow).
Pass the previous `nextCursor` for the next page; an empty string is a cursor, not the end.

```php
$Client->walk (): array
```

Every tool, `list()` page after page until one has no `nextCursor`. Fails with `Protocol` past
`MCP_Client::TOOLS` tools or `MCP_Client::BYTES` bytes of answers.

```php
$Client->call (string $name, array $arguments = []): array
```

Calls a tool and returns its result decoded. `arguments` must be an object (an associative
array, or empty); a list raises `InvalidArgumentException`.

```php
$Client->close (): void
```

Ends the conversation: the legacy session's `DELETE` (HTTP) or the server process (stdio). The
client keeps its era; a later call opens a new session.

```php
$Client->revision   // null|string
```

The protocol revision agreed with the server; null before the first request.

```php
$Client->stateless   // bool
```

Whether the server is spoken to in the stateless era.

```php
MCP_Client::PROBE · CANCEL · RESENDS · TOOLS · BYTES
```

Seconds the stdio probe waits (`5`), seconds a cancellation may take (`1`), the most
`input_required` resends (`3`), the most tools (`10_000`) and answer bytes (64 MiB) a walk reads.

### MCP_Client\Rejection

```php
$Rejection->getCode () · getMessage () · $Rejection->data
```

The server's JSON-RPC error: its code, message and decoded `data` (null when none).

### MCP_Client\Failure

```php
$Failure->kind   // MCP_Client\Failure\Kinds
```

`Transport`, `Timeout`, `Protocol`, `Authentication` or `Version`. Each case is backed by its
lowercase name (`Kinds::Transport->value` is `'transport'`), so a kind you store or log reads back
with `Kinds::from()`.

```php
$Failure->status   // int
```

The HTTP status, `0` when none arrived or on stdio.

```php
$Failure->challenge   // null|string
```

The `WWW-Authenticate` challenge of an `Authentication` failure.

### MCP_Client\Transport

```php
abstract class Transport
```

The wire the client speaks over: `send (Exchange $Exchange): Reply` and `close (): void`, plus
`$peer` (the key of the era cache; empty: never cached), `$HTTP` and `$generation`. The shipped
transports are the supported ones —
**[`MCP_Client_CLI`](/manual/WPI/HTTP/HTTP_Client_CLI/MCP/overview/#reference)** and
**[`CLI\MCP\Client`](/manual/CLI/MCP/Client/overview/#reference)**; later members arrive with
default bodies, never as new abstract methods within 1.x.

```php
$Transport->prepare (): void
```

Called before the client composes each message: a transport whose peer ended while idle releases
it here and changes its `generation` (the stdio transport does). Nothing by default.

```php
$Transport->end (string $session, string $revision): void
```

Called when the client refuses an `initialize` answer that opened a legacy session — a revision it
does not speak, or no tools: the HTTP transport sends that session's `DELETE` naming `$revision`,
best effort. An id that is not a valid `Mcp-Session-Id` is never passed. Nothing by default.

```php
Transport::decode (string $JSON): mixed
```

Decodes one message of the peer (objects as arrays) — the one way the client and the shipped
transports read what a server wrote. Throws `JsonException` for invalid JSON and `Failure`
(`Protocol`) past `Transport::CONTAINERS` arrays and objects, counted outside the strings.
