# MCP client over HTTP

`Bootgly\WPI\Nodes\MCP_Client_CLI` is the **Streamable HTTP** transport of the
**[MCP client](/manual/API/RPC/MCP_Client/overview/)**: it carries the client's messages to an MCP
server behind a URL. Every message is one `POST` to the endpoint and every answer is read whole —
`application/json`, or a buffered `text/event-stream` scanned for the response to the request.

The transport builds and owns its **[HTTP client](/manual/WPI/HTTP/HTTP_Client_CLI/overview/)**:
HTTP/1.1, **no redirect followed, no request retried**. From your application it takes only the
endpoint, a token hook, the timeouts, the answer bound, TLS options, a dial seam and — inside a
request handler — the deferral's `Response`.

## Call a tool from a command

From a command or a job, build the transport with the server's URL, the client 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();
```

Here the transport runs on an event loop of its own and **blocks the caller** while the server
answers, for as long as you keep it. `close()` ends a legacy session with its `DELETE` (best
effort: a `405` or a failure is ignored) and closes the connections. 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/)**.

## Call a tool from a request handler

A command can block while the server answers; a request handler cannot — the worker serves other
connections. Inside a handler, call from **[`defer()`](/manual/WPI/HTTP/HTTP_Server_CLI/Response/overview/)**
and pass the deferral's `Response` to the transport: the call parks the deferred Fiber on the
worker's reactor and resumes it when the answer arrives.

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

yield $Router->route('/preview', function (Request $Request, Response $Response) {
   return $Response->defer(function (Response $Response) {
      $Client = new MCP_Client(
         new MCP_Client_CLI('https://engine.example.com/mcp', timeout: 10, Response: $Response),
         name: 'App',
         version: '1.0.0'
      );

      try {
         $result = $Client->call('render', ['scene' => 42]);
         $Response->JSON->send($result['structuredContent'] ?? []);
      }
      catch (Rejection | Failure) {
         $Response(code: 502)->JSON->send(['error' => 'The engine is unavailable.']);
      }
   });
});
```

With `Response`, the transport mounts an HTTP response resource of its own on the deferral's
`Response` — the **[embedded mode](/manual/WPI/HTTP/HTTP_Client_CLI/overview/#embedded-mode)** of the HTTP
client, with redirects and retries off.

Build **one client per deferral**. A client is owned by the deferral that first used it: a call
from another deferred context while it is in use raises `LogicException`, and a transport built
inside a deferral without its `Response` raises `LogicException` too — its own event loop would
block the worker.

Each era costs round trips on a fresh client: a stateless server takes the probe and the call
(two requests); a session server takes the probe, `initialize`, `notifications/initialized` and
the call (four), plus the `DELETE` on `close()`. The era is remembered per worker by the server's
URL (scheme, host, port, path and query), so the next client skips the probe.

## The token hook

A server behind OAuth wants `Authorization: Bearer <token>` on every request. Give the transport a
`Token` closure; it is asked **once per HTTP request** — the probe, `initialize`, every
notification and call, the `DELETE` — and its answer is never cached, never put in a URL, never
sent after a redirect (none is followed). Return `null` to send none.

```php
$Transport = new MCP_Client_CLI(
   'https://engine.example.com/mcp',
   Token: static fn (): null|string => $Tokens->fetch('engine')
);
```

Bootgly 1.4 ships no OAuth flow: the closure is where your application's OAuth plugs in (its
token store, its refresh). When the server refuses the token (`401` or `403`), the call raises a
`Failure` of kind `Authentication` carrying the `WWW-Authenticate` challenge — refresh and call
again:

```php
use Bootgly\API\RPC\MCP_Client\Failure;
use Bootgly\API\RPC\MCP_Client\Failure\Kinds;

try {
   $result = $Client->call('render', ['scene' => 42]);
}
catch (Failure $Failure) {
   if ($Failure->kind !== Kinds::Authentication) {
      throw $Failure;
   }
   $Tokens->refresh('engine', challenge: $Failure->challenge);
   $result = $Client->call('render', ['scene' => 42]);
}
```

If your token provider discovers the authorization server through RFC 9728 (the challenge's
`resource_metadata`, then `/.well-known/oauth-protected-resource` plus the MCP URL's path, then
the root document), it **must** check the `resource` of the document that answers: equal to the
MCP URL — for the root document, the origin (`https://host[:port]`) is accepted too — compared
exactly apart from a trailing slash (no case folding, no default-port normalization), and refuse
the document otherwise. A document that answers and is refused **fails the discovery**: the
provider does not fall through to the next URL, since a document that names another resource must
not be used (RFC 9728 §3.3). Only a URL that yields no JSON object — a failed fetch, a status
other than `200`, a body that is not an object — moves on to the next one. This client ships no
OAuth flow, so the check is your provider's.

The token and the URL's userinfo never reach a dump: `var_dump()`, `print_r()` and Bootgly's
`Dumper` show the transport's `Token` as redacted (and a `passphrase` in `secure`), `$Transport->URL`
drops the userinfo — which is never sent either — and a `Failure` carries no request bytes.

## TLS and the destination

An `https` URL is dialed with TLS and the secure defaults: the certificate is verified against the
URL's host. Pass `secure` to add stream context options — a private CA, a client certificate:

```php
$Transport = new MCP_Client_CLI(
   'https://engine.internal.example.com/mcp',
   secure: ['cafile' => '/etc/ssl/certs/internal-ca.pem']
);
```

The options are those of the HTTP client's **[SSL/TLS](/manual/WPI/TCP/TCP_Client_CLI/overview/#ssltls)**.

The transport **vets no destination**: it dials whatever its URL names. When the URL comes from
users, vet the addresses in a `Resolution` closure — the HTTP client's dial seam, with the
signature described in **[Dialing a name](/manual/WPI/TCP/TCP_Client_CLI/overview/#dialing-a-name)**
— and refuse private, loopback and link-local ones:

```php
use Closure;

use Bootgly\WPI\Nodes\DNS_Client_CLI;
use Bootgly\WPI\Nodes\MCP_Client_CLI;

$DNS = new DNS_Client_CLI();

$Transport = new MCP_Client_CLI(
   $URL,
   Resolution: static fn (string $host, null|Closure $Wait, null|int $deadline, object $Reactor): array
      => array_values(array_filter(
         $DNS->resolve($host, $Wait, $deadline, $Reactor),
         static fn (string $address): bool => filter_var(
            $address,
            FILTER_VALIDATE_IP,
            FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
         ) !== false
      ))
);
```

Without `Resolution`, the HTTP client's own resolver dials every address the name answers. A URL
whose host is an IP literal never reaches the closure: check that host yourself before you build
the transport.

## Timeouts and the answer bound

- **`connectTimeout`** (30 seconds) bounds the name's lookup, the connection and the TLS handshake.
- **`timeout`** (30 seconds) bounds the answer once connected. A call past it fails `Timeout` —
  the tool **may have run**. In the session era the client then tells the server, best effort and
  within `MCP_Client::CANCEL` seconds, with `notifications/cancelled` (that budget is split in
  half between the dial and the answer); in the stateless era the closed answer already is the
  cancellation.
- **`bytes`** (4 MiB) is the largest answer, head included: past it the call fails (`Transport`).
  An answer is buffered and decoded whole, so this bounds the memory a server can make you spend
  — the **[MCP client](/manual/API/RPC/MCP_Client/overview/#limits)** gives the arithmetic.

## What the transport refuses

The rules below are the HTTP side of the protocol: they hold whatever the era.

- **No redirect, no retry.** A `3xx` fails the call (`Protocol`). A `5xx`, a `408` or a `429`
  fails it (`Transport`, whatever its body says; a JSON-RPC error in that body is kept as the
  failure's previous exception, a `Rejection`): trying again may help, after a pause of your own
  on a `429` (its `Retry-After` is not surfaced). A `401`/`403` fails it (`Authentication`).
- **Only the MCP answer.** A `200` whose media type is neither `application/json` nor
  `text/event-stream`, or an event stream without the response to the request, fails the call
  (`Protocol`).
- **Sent again only when the server did not run it.** A lost legacy session (`404`, after a new
  `initialize`), a header mismatch (`-32020`, after the tools are listed again) and a stateless
  revision the server no longer speaks (`-32022`, or a `400` without a modern error, after a new
  probe) — each once. A server that answers `400` to a call it ran would see it twice: such a
  server breaks the protocol.
- **The probe's answer.** `server/discover` settles the stateless era when it is answered `200`
  with a discovery, or `400` with a modern refusal (`-32020`, `-32021`, or `-32022` with the
  revisions the server speaks). A redirect, a `5xx`, a `408` or `429`, a `406`, `413` or `415`, a
  `401`/`403` or no answer at all (a failed connection, a timeout) fails the call and remembers
  nothing — the next client asks again. Any other answer means the legacy era.

## Limits

- **Answers are buffered.** An event-stream answer is read whole and scanned for the response;
  progress notifications and server requests on it are skipped, and a stream the server keeps
  open after the answer fails at the timeout.
- **No listening.** No `GET` listening stream: notifications outside an answer are never received.
- **No server requests.** Sampling, elicitation or roots requests on a stream are skipped.

## Reference

```php
public function __construct (
   string $URL,
   null|Closure $Token = null,
   int|float $timeout = 30,
   int|float $connectTimeout = 30,
   int $bytes = 4_194_304,
   null|array $secure = null,
   null|Closure $Resolution = null,
   null|Response $Response = null
)
```

Creates the transport for one endpoint. `$URL` must be an absolute `http(s)` URL; `$Token`
(`fn (): null|string`) is asked once per request; `$timeout` is the seconds the answer may take
once connected and `$connectTimeout` the lookup, connection and TLS handshake; `$bytes` the largest
answer, head included — past it the call fails (`Transport`); `$secure` the TLS stream context
options (null: the secure defaults on `https`); `$Resolution` the dial's name resolution, with the
signature of `HTTP_Client_CLI->Resolution`; `$Response` the deferral's `Response`, inside
`defer()`. Throws `InvalidArgumentException` for a URL that is not an absolute `http(s)` URL, a
non-positive timeout or a non-positive `$bytes`, and `LogicException` when built inside a deferral
without its `Response`.

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

`POST`s one message and reads its answer whole — called by the client, not by your code. Throws
`Failure` of kind `Transport` (no answer), `Timeout` (past the deadline) or `Protocol` (a `200`
without the answer, an unexpected media type), and `LogicException` from another deferred context
than the owner's.

```php
public function end (string $session, string $revision): void
```

Sends the `DELETE` of a legacy session the client refused before using it, naming `$revision`
(empty: none) — best effort: a `405` or a failure is ignored.

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

Ends the legacy session with its `DELETE` (best effort) and closes the connections.

```php
public private(set) string $URL;
```

The endpoint without its userinfo (which is never sent).

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

The seconds the answer may take once connected.

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

The seconds the lookup, the connection and the TLS handshake may take.

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

The largest answer, in bytes, head included.
