All 48 libraries

SugarMCPClient

MCP client core — JSON-RPC codec, stdio transport, server narrowing

component-package mcp json-rpc

SugarMCPClient code coverage

A Model Context Protocol client core the whole ecosystem can share: JSON-RPC 2.0 envelopes, a newline-framed stdio transport with a bounded child lifecycle, the initialize/tools handshake, and deny-before-allow server narrowing — tool rosters follow servers. Here "client" means the tool-CALLING side: this library spawns and drives an MCP server child process; it does not host one. It was extracted from candy-code's MCP stack, so every surface that talks to an MCP server over stdio shares the same framing and the same handshake-and-deadline rules. First-party: MCP is a specification, not a Go port.

Install

composer require sugarcraft/sugar-mcp-client

Requires PHP 8.3 or newer. The only runtime dependency beyond PHP is sugarcraft/sugar-core, which supplies the output sanitizer used below.

Suggested: ext-posix. It drives the liveness probes for server children, lock owners and forked successors. Without it, the lock-owner probe falls back to Linux /proc, which can still certify a dead pid as absent; only a host with neither posix nor procfs leaves that probe failing open as alive. A forked successor's server-liveness check has no such fallback: without ext-posix it assumes the server is up, so a dead server surfaces through the pipes (a write failure or EOF) rather than through the probe.

Quickstart

use SugarCraft\Core\Util\Sanitize;
use SugarCraft\McpClient\StdioMcpServer;

$server = new StdioMcpServer(
    name: 'everything',
    command: 'npx',
    args: ['-y', '@modelcontextprotocol/server-everything'],
);

$server->start();              // initialize → notifications/initialized → tools/list, one 60 s clock
foreach ($server->listTools() as $tool) {
    echo $tool->name, ' — ', Sanitize::untrusted($tool->description), PHP_EOL;  // server-authored prose
}

$result = $server->callTool('echo', ['message' => 'hi']);
// normally ['content' => [['type' => 'text', 'text' => '…']]], or ['error' => …]
// naming the CAUSE: a failed call never throws and never answers bare.

$server->stop();               // closes the pipes, then TERM → KILL → reap; __destruct calls stop() if you forget

The example spawns npx -y @modelcontextprotocol/server-everything, so it needs Node.js on PATH. Any stdio MCP server takes the same three arguments: a name, a command and an argv list. For a trial with nothing to install, run php examples/echo.php (see Examples).

Concepts

The library is the client half of MCP. It launches a server as a child process, speaks newline-delimited JSON-RPC 2.0 over the child's stdin and stdout, and runs the handshake: initialize, then notifications/initialized, then tools/list. The handshake runs under a single monotonic deadline, so a slow start cannot stretch it leg by leg.

Failures are answers, not exceptions. callTool(), listResources() and the other convenience methods return either the result payload or ['error' => 'why']. A handshake that cannot complete is different: start() stops the child and throws, with any captured stderr attached.

Launching a configured stdio entry runs third-party code as the invoking user, and the child inherits the full parent environment unless you narrow it. Read the trust boundary before you configure a server.

Tasks

Use it for

  • Speaking MCP from any PHP process: spawn a stdio server child, handshake, list and call tools, with the framing and timeout rules already in place.
  • Agent tool surfaces: narrow which servers each agent may see with globs and deny-before-allow. Tool rosters follow servers, which is the same semantics candy-code builds on.
  • Bounded subprocess I/O: the transport is a reference for newline-framed JSON-RPC over pipes, with deadlock-free pumping and bounded child teardown (TERM → KILL → reap on stop() and on destruct). A process SIGKILLed mid-use leaves its child to the embedding process manager.

Narrow which servers an agent sees

McpRouter takes the servers keyed by config name and a deny list. A deny pattern always wins over an allow entry. An empty allow list means allow all, minus the denied servers.

use SugarCraft\McpClient\McpRouter;

$router  = new McpRouter(['filesystem' => $fs, 'git' => $git], ['git']);  // deny 'git'
$servers = $router->resolveAllowedServers(['filesystem', 'git']); // only 'filesystem' survives
$tools   = $router->resolveAllowedTools(['filesystem']);          // tools of the surviving servers

Bound one tool call

A call has no deadline unless you pass one. A bounded call answers with an error when the deadline passes, and the connection stays usable.

$result = $server->callTool(
    name: 'slow-report',
    arguments: ['days' => 30],
    timeoutSeconds: 30.0,        // zero and negative values are refused at the door
);
// on timeout: ['error' => 'Tool call timed out after 30s and was cancelled; …']

Read a failure

$result = $server->callTool('echo', ['message' => 'hi']);

if (isset($result['error'])) {
    fwrite(STDERR, Sanitize::untrusted((string) $result['error']) . PHP_EOL);
    exit(1);
}
foreach ($result['content'] ?? [] as $block) {
    echo Sanitize::untrusted((string) ($block['text'] ?? '')), PHP_EOL;
}

Keep the child's environment small

The child inherits the full parent environment by default. envRemove: drops named variables from that inheritance, and curatedEnv: replaces the environment outright. spawnPlanner: gives full control over the argv and the env that actually spawn.

$server = new StdioMcpServer(
    name: 'narrow',
    command: 'npx',
    args: ['-y', '@modelcontextprotocol/server-everything'],
    envRemove: ['AWS_SECRET_ACCESS_KEY', 'SSH_AUTH_SOCK'],
);

// Or replace the environment wholesale. curatedEnv: cannot be combined with env:,
// envRemove: or spawnPlanner:, and the constructor throws if you try.
$server = new StdioMcpServer(
    name: 'curated',
    command: 'npx',
    args: ['-y', '@modelcontextprotocol/server-everything'],
    curatedEnv: ['PATH' => '/usr/local/bin:/usr/bin:/bin'],
);

Configuration

The options are the named arguments of StdioMcpServer's constructor. Only name, command and the argument list are routinely needed.

StdioMcpServer constructor options
OptionTypeDefaultEffect
namestringrequiredThe config name. Routers key servers by it, and diagnostics name it.
command, argsstring, arrayrequired, []The executable and its argv. The spawn is an argv array, never a shell string.
envarray[]Entries added to or overriding the inherited environment. It never removes an inherited name.
envRemovelist<string>[]Names stripped from the inherited environment before env is applied. Must be distinct and non-empty.
curatedEnv?arraynullThe exact environment the child receives. [] means an empty environment. Exclusive with env, envRemove and spawnPlanner.
spawnPlanner?\ClosurenullReceives the name, the argv and the authored env, and returns [argv, env] that actually spawn. Throwing from it refuses the launch.
cwd?stringnullAbsolute working directory for the child. null inherits the parent's directory.
startTimeoutSeconds?float60.0The one handshake deadline. null, zero or negative values fall back to 60 seconds.
clientInfoarraypackage name and versionThe clientInfo sent in initialize. Exclusive with clientName and clientVersion.
clientName, clientVersion?stringpackage valuesSet one arm of the client identity. An empty string throws.
capabilitiesarray[]Client capabilities advertised in initialize.
onServerMessage?\ClosurenullHandler for requests the server sends while a call is in flight. Unhandled methods are refused.
lockDir?stringthe system temp directoryWhere the ExchangeLock file lives. The directory must exist.

Architecture

The wire layers sit under StdioMcpServer. JsonLines\Reader turns raw pipe chunks into complete lines and caps how large one line may grow. McpMessage and the Protocol classes build and read the envelopes. ExchangeLock serializes exchanges when forked processes share one connection.

McpMessageJSON-RPC 2.0 envelope: parse() / request() / notification() / success() / error(); a resultSet sentinel keeps explicit "result": null representable; toJson() is the wire and fails closed on unencodable payloads, toArray() is inspection.
McpTool / McpServerOne tool definition value object with a well-typedness gate that refuses malformed server output — control bytes in names are rejected at parse; descriptions are free-form prose that passes through verbatim, so display them through sugar-core Sanitize::untrusted — plus the McpServer interface: lifecycle, tool surface, and the shared raw legs request()/notify().
StdioMcpServerargv-array proc_open child, newline-delimited (NDJSON) framing, 64 KiB rolling stderr tail absorbed on every wait set, one monotonic (hrtime) deadline across the whole handshake, protocol-version negotiation, and a per-second handshake beat via start(onWait:).
ExchangeLockSerializes whole request/response exchanges when forked processes share one stdio connection; records a W/R phase so the next holder resynchronizes after a killed one; the file is created at mode 0600, verified before any payload, and a filesystem that refuses the mode fails the open loudly.
Protocol codecThe candy-code.v1 JSON-RPC 2.0 codec: JsonRpc decodes one client message into a Request and builds the four wire shapes; RpcError carries an ErrorCode, a kind and data. Undecodable text is answered with an RpcError, never null.
McpRouterDeny-before-allow SERVER narrowing over any set of McpServer instances — tool rosters arrive whole, so rosters follow servers; fnmatch globs; empty allowlist means allow-all; malformed entries fail loud.
Server requests & trustA server's own requests (ping, roots/list, elicitation/create) are answered inline while a call is in flight — default ping acknowledged, anything else refused "Method not found" — with the handler's wall clock excluded from the call's budget. Running a configured stdio entry executes third-party code as the invoking user with the FULL parent environment: see the README's Trust boundary.

API

API surface
ClassMethodDescription
McpMessageparse(string $json): ?selfDecode a wire frame; null when it cannot be read as a JSON-RPC 2.0 message; an id that is neither string, int nor null is DROPPED and the message still parses (parsePreservingId() refuses such frames instead)
McpMessagerequest(string $id, string $method, ?array $params) / notification(string $method, ?array $params): selfOutbound request and notification envelopes
McpMessagesuccess(string $id, mixed $result) / error(string $id, int $code, string $message, mixed $data = null): selfOutbound response envelopes; result is mixed by design; an explicit "data": null is indistinguishable from an absent one on round-trip
McpMessagetoJson(): string / isRequest() / isResponse() / isNotification() / isError(): boolWire serialization + role predicates; toJson() throws InvalidArgumentException for an envelope JSON cannot carry (INF/NAN, invalid UTF-8) instead of emitting a blank frame
McpMessageparsePreservingId(string $json): ?self / withWireId(string|int|null $id): selfThe wire-typed id pair: parsePreservingId() REFUSES (null) frames whose id is neither string, int nor null — where parse() would drop such an id and answer a valid-looking message — and records the id's original JSON type; withWireId() stamps that type onto an outbound reply so a response to a server's int id travels back an int (the client's own request ids are plain strings — the transport stringifies at send)
McpMessageerrorCode(): ?int / errorMessage(): ?stringHonest error reads: a malformed code (a server's "code":"abc") or non-string message answers null — "not reported" — never a casted 0 that a downstream caller could misread as a real code, and never the string 'Array'
StdioMcpServerstart(?\Closure $onWait = null): void / stop(): void / isUp(): boolHandshake under one deadline, beating $onWait about once a second while it waits; the constructor's startTimeoutSeconds: is a silent-fallback knob — null, zero or negative lands on the 60 s default (a 0 that means 60), so a bad setting can never disable the bound. clientInfo: is checked at construction: a non-empty string 'name' and a string 'version', or an InvalidArgumentException (an explicit [] is a bug, not a reset); the untouched shipped default resolves to the real installed package version when Composer knows it, and an explicitly supplied identity is never rewritten. Piecewise authorship: clientName:/clientVersion: supply one arm and the omitted arm rides the same runtime resolution, so renaming never requires carrying a version literal; a split knob combined with a supplied clientInfo: — or an empty-string arm — throws at construction. Every leg must succeed — a spawn refusal naming the command, an initialize or tools/list error or missing reply, a protocol version this client will not speak, or an undelivered notifications/initialized reaps the child and throws RuntimeException. Close-pipes-first teardown with TERM→KILL→reap via sugar-core BoundedShutdown
StdioMcpServerlistResources(): array / readResource(string $uri): array / listPrompts(): array / getPrompt(string $name, array $arguments = []): arraythe resources/prompts convenience quartet over request() — same array-or-error shape as callTool(): result payload on success, a failure named in ['error' => …], never a throw, never null; an empty $arguments map is repaired to a JSON object before the wire, a non-empty positional list is refused at the client door
StdioMcpServerwriteFramed(string $json, ?float $deadline = null): boolThe single raw-frame escape hatch below request()/notify(), for an embedder already driving a started transport that must emit exactly one raw frame: a payload embedding a CR or LF is refused at the boundary (either would forge a second wire frame for stdio readers that split on both), and the deadline follows the same monotonic-instant law; deliberately no exchange lock and no dead-holder salvage prefix — those are protocol-conversation machinery, callers speaking the protocol use request()
StdioMcpServerlistTools(): list<McpTool> / callTool(string $name, array $arguments, ?\Closure $onWait = null, ?float $timeoutSeconds = null, ?\Closure $onServerMessage = null): arraytools/list result; tools/call with scalar-result wrapping at the boundary, no deadline unless timeoutSeconds: is passed, and a liveness probe on idle polls (a dead server ends an unbounded call, or a bounded call carrying an onWait: beat, within about a second, even when a forked helper holds its pipes (for a forked child that liveness check needs ext-posix; see Install); a bounded call with no beat can instead sleep one long slice to its own timeoutSeconds, which is then its bound). Failure payloads always name the CAUSE — the server's JSON-RPC code and message, the dead child, the refused frame — and carry the stderr tail; the three trailing opt-ins exist on this concrete class (the McpServer contract is callTool(name:, arguments:), whose parameter names this implementation keeps so named arguments bind either way)
StdioMcpServerrequest(string $method, ?array $params = null, ?float $deadline = null, ?\Closure $onServerMessage = null): ?McpMessage / notify(string $method, ?array $params = null, ?float $deadline = null): boolEscapeway to any other protocol method (resources, prompts) without subclasses; $deadline is an ABSOLUTE monotonic instant (StdioMcpServer::monotonicNow() + seconds), not a duration — a wall-clock magnitude throws instead of silently never firing; notify() reports whether the whole line went out
StdioMcpServerstderrTail(): string / static monotonicNow(): floatThe bounded stderr capture, control bytes swept and surviving stop() for post-mortems — the bytes are UNTRUSTED server output, render them through SugarCraft\Core\Util\Sanitize::untrusted(); monotonicNow() is the clock request()/notify() deadlines are instants on
StdioMcpServerpumpStderr(): voidNon-blocking stderr drain for callers that idle between exchanges and want diagnostics warm — deliberately caller-pumped: two readers on one destructive pipe would steal each other's bytes
StdioMcpServermalformedToolDefinitions(): list<string> / malformedToolDefinitionsReport(): stringThe definitions the well-typedness gate SKIPPED during the current start(), by label, plus a one-line announcement for wherever the start outcome is surfaced — the registered roster is already safe; the report is the half the user must not guess. Reset by every start(), kept by stop()
StdioMcpServerserverInfo(): ?array / serverCapabilities(): ?array / initializeResultDefects(): list<string>The kept InitializeResult: the server's advertised identity and capability map, handed out verbatim (server-authored text — sanitize before display) and surviving stop() for post-mortems; the store is tolerant, so initializeResultDefects() names any spec-required member the server omitted instead of leaving the gap unannounced
McpServerinterface: start(): void / stop(): void / listTools(): array / callTool(string $name, array $arguments): array / request(string $method, ?array $params = null, ?float $deadline = null): ?McpMessage / notify(string $method, ?array $params = null, ?float $deadline = null): boolThe transport contract; failed calls answer as error payloads, not throws; raw legs answer the server's own error REPLY as an error-bearing message (read it) and a dead exchange as null (or false). Concrete transports may add trailing opt-ins the interface cannot express — on StdioMcpServer, onWait:/timeoutSeconds:/onServerMessage: behind callTool's shared pair and an exchange-scoped answerer behind request()'s — and the positional order of those trailing parameters is concrete-class API, pinned by name
ArgumentShapeconform(array $arguments, array $inputSchema): arrayRestores the {}-vs-[] JSON distinction a decoded PHP array lost, guided by the tool's advertised inputSchema (nested properties, items, anyOf/oneOf/allOf, local $refs); NO-SCHEMA-NO-GUESS: an untyped position keeps its shape
RequestIdSequencenext(): int|string / claim(): bool / isOwner(): boolJSON-RPC ids unique across pcntl_fork(): plain counters in the owner, <pid>-<nonce>-<n> elsewhere; a foreign claim against a live owner is refused, and a succession from a dead one resumes far ahead so stale replies can never alias new calls
RequestIdSequenceownerPid(): int / currentPid(): intThe two pids the fork rules are written against: who opened the sequence, and who is asking now (currentPid answers through the pid provider — the default is getmypid, the seam is the suite's)
McpToolfromArray(array $definition, string $serverName): self / tryFromArray(array $definition, string $serverName): ?selfParse a tool definition; tryFromArray gates well-typedness before construction — a name carrying control bytes is refused, where fromArray() would construct it — and is the door the wire path uses. The $annotations object (readOnlyHint, destructiveHint, idempotentHint, openWorldHint, title) is parsed and carried verbatim but consulted by nothing here — a hint is an unverified server claim about itself, and enforcing it is the consumer's policy to write
McpRouterresolveAllowedTools(array $allowList = []): list<McpTool> / resolveAllowedServers(array $allowList = []): arrayDeny-first narrowing; the server map is keyed by the config server name as authored (PHP normalizes digit-looking names to int keys); empty allowlist = allow-all
McpRouterstatic serverDenied(string $server, array $denyPatterns): bool / static serverAllowed(string $name, array $allowList): boolThe two glob dialects, deliberately asymmetric: the deny side fnmatches EVERY pattern (under-matching a denial fails open), the allow side globs only *-entries and otherwise compares exactly (over-matching an allowance fails open); malformed allow entries throw
ExchangeLockstatic new(string $label, ?string $dir = null): self / static sweepStale(?string $dir = null): intCross-process flock for one stdio connection shared across pcntl_fork(); new() sweeps lock files whose owner died, then creates this owner's file at mode 0600 — verified before any payload, refusing loudly where the filesystem will not carry the mode. create() remains as a deprecated alias of new(), scheduled for removal at the 2.0.0 major
ExchangeLockacquire(?float $deadline, \Closure $serverAlive): bool / load(): array / store(string $phase, string $buffer): bool / markPhase(string $phase): boolPhase byte + carried read buffer under the lock; store()/markPhase() return false when the write did not land, and an empty file loads as dirty
ExchangeLockrelease(): void / close(): void / destroy(): voidThe three teardown grades, each pid-guarded: release() lifts THIS process' flock only; close() also drops the handle — an inherited handle is dropped, never unlocked, because LOCK_UN on a shared description would release the parent's lock; destroy() closes and, in the owner only, removes the file
McpCallstatic request(string|int $id, string $method, array|\stdClass $params = [], int $extraFlags = 0): stringBuilds one outgoing JSON-RPC request line with the empty-params shim in one place: an empty array leaves as {}, and a caller-supplied \stdClass passes through untouched, so a relay can forward a client's own bytes. Throws JsonException when the envelope cannot be encoded.
PendingCallsregister(string $id, \Closure $settle, bool $preserving = false): void / has(string $id): bool / isPreserving(string $id): bool / count(): intA promise-neutral table of in-flight requests keyed by id. register() throws LogicException when the id is already pending; the $settle callback is fn(?\Throwable, mixed): void, so a ReactPHP consumer wraps a Deferred and a synchronous one stores the outcome. isPreserving() echoes the flag given at registration.
PendingCallssettle(string $id, mixed $result): bool / fail(string $id, \Throwable $failure): bool / failAll(\Throwable|string $failure): intEach settle path removes the entry before invoking its callback, so a re-entrant callback sees a consistent table and nothing settles twice. settle() and fail() return false for an unknown id. failAll() is transport death: it fails every pending call (a string becomes a RuntimeException) and returns how many it failed.
ProcessLivenessstatic ownerAlive(int $pid): bool / const ERRNO_ESRCHThe shared signal-0 liveness probe. Only a kernel certainty of "no such process" (ESRCH) reports dead; EPERM is a live process owned by someone else, and any other answer counts as alive. Without ext-posix, Linux /proc can still certify absence.
JsonRpcstatic decode(string $text): Request|array / result(string|int|null $id, mixed $result): string / error(string|int|null $id, RpcError $error): string / notification(string $method, array $params): array / encode(array $message): string / encodeValue(mixed $value, int $depth = self::MAX_DEPTH_VALUE): stringThe candy-code.v1 envelope codec. Decoding never throws past decode(): text that is not a request comes back as the RpcError the caller answers with; depth is capped at MAX_DEPTH. encodeValue() encodes a bare value with no envelope under the same wire flags (invalid UTF-8 substituted), within the MAX_DEPTH_VALUE (511-level) budget
Request__construct(string|int|null $id, bool $hasId, string $method, array $params) / isNotification(): boolOne decoded client message: a request (hasId true, answered) or a notification (no id, never answered)
RpcErrorstatic of(ErrorCode $code, string $message, ?string $kind = null, array $data = []): self / static invalidParams(string $message, string $kind = 'invalid_params'): self / static notFound(string $message, string $kind = 'not_found'): self / toArray(): arrayA method's refusal, extending RuntimeException and implementing Refusal; toArray() is the JSON-RPC error object the codec sends
RefusalrefusalKind(): string / refusalData(): arrayThe refusal contract a bundle branches on, read the same on the wire and in-process: the wire's data.kind and the data object, retry hint included. A bundle checks this interface rather than a concrete error class, because RpcError and the plugin host's RefusedCall both implement it, so a refusal keeps its retryAfterMs whichever copy raised it
ErrorCodekind(): string / isRetryable(): boolThe candy-code.v1 error codes (int-backed enum) with the stable kind string and whether a caller may retry

Only methods declared in sugar-mcp-client/src, or inherited from a parent declared there, are listed. A type that extends a class outside that tree, such as \RuntimeException, does not show the methods of that class.

SugarCraft\McpClient

ArgumentShape final class

Restores the JSON object/array distinction a tools/call argument map lost on its way into PHP, guided by the tool's own inputSchema.

MethodSummary
static conform(array $arguments, array $inputSchema): arrayThe tool-call argument map with every empty object position (per the schema) turned into \stdClass. The top level itself stays an array — an empty one is returned as [], and each transport keeps its own === [] ? new \stdClass() for the arguments member (the top-level object law), so a caller typed array (e.g. ClaudeCodeMcpClient) can take the result.

ExchangeLock final class

Cross-process mutual exclusion for one stdio connection, plus the state that must outlive whichever process held it last.

MethodSummary
static new(string $label, ?string $dir = null): selfCreate the lock file for a connection the CURRENT process owns, after sweeping the files dead owners left in the same directory.
static create(string $label, ?string $dir = null): selfFormer name of new(), kept as a public-API compatibility shim until any embedder still calling it moves over; the repo's factory rule names the default root ::new(). (The originally-named downstream caller has ALREADY migrated — the sole caller inside this repo is the alias-resolution test, and this note carries no survivor's name so it cannot go stale again.)
static sweepStale(?string $dir = null): intRemove the lock files in $dir whose owner process no longer exists.
acquire(?float $deadline, \Closure $serverAlive): boolWait for the exclusive lock. Polls LOCK_NB rather than blocking so the wait honours $deadline (hrtime seconds, null = no deadline, matching the no-deadline tool-call policy) and gives up the moment the server is gone.
load(): arrayThe phase and buffer the previous holder left.
store(string $phase, string $buffer): boolRewrite the whole state: phase byte plus buffer. This is a FULL truncate-and-write of everything the exchange carries, on every exchange, under the lock: the cost tracks the read buffer's size (bounded by the transport frame cap), a deliberate price for state an external kill can only ever leave whole-or-empty. An append-delta design would need a cross-process offset ledger to stay recoverable — it re-earns nothing the phase byte could not already say.
markPhase(string $phase): boolOverwrite the phase byte alone, leaving the stored buffer as it is.
release(): void
close(): voidClose THIS process' handle; the file and every other process' handle stay.
destroy(): voidClose, and — in the owner only — remove the file.

JsonLines final class

The writer half of the JSON-Lines pair (Reader is the reader): the ONE place the line-protocol encode flag set lives.

MethodSummary
static encode(mixed $value, int $extraFlags = 0): stringOne line of JSON, no trailing newline (the transport appends it).
static reader(?int $maxLineBytes = null): Reader

McpCall final class

Builds the wire line for an outgoing JSON-RPC request, with the empty-params shim in ONE place.

MethodSummary
static request(string|int $id, string $method, array|\stdClass $params = [], int $extraFlags = 0): string

McpMessage final class

A single JSON-RPC 2.0 envelope — request, notification, success response or error response — as one immutable value object.

MethodSummary
static parse(string $json): ?selfParse one wire line into an envelope, or null when the payload is not a JSON-RPC 2.0 object we can act on.
static parsePreservingId(string $json): ?selfTHE ID-PRESERVING VARIANT: parse(), except that the id is also kept exactly as it arrived — an integer stays an integer — in $wireId, and toJson() writes it back that way.
withWireId(string|int|null $id): selfA copy whose wire id is $id exactly as given — how the id-preserving variant BUILDS a message: McpMessage::success((string) $id, $r)->withWireId($id) answers an integer-id request with the integer, and McpMessage::error('', $code, $m)->withWireId(null) is the "id": null error JSON-RPC requires for a request whose id could not be read. On a notification, which carries no id, it changes nothing on the wire.
static request(string $id, string $method, ?array $params = null): selfBuild an outgoing request envelope (method + id + params).
static notification(string $method, ?array $params = null): selfBuild an outgoing notification envelope (method, no id, no answer).
static success(string $id, mixed $result): selfBuild a success response. Accepts any value — MCP results are mixed and null is a legal payload, which is what resultSet records.
static error(string $id, int $code, string $message, mixed $data = null): selfBuild a JSON-RPC error envelope. An explicit wire "data": null does NOT survive a build→encode→parse round-trip: the member is omitted for a null $data, and a parsed envelope keeps only what the wire carried. Code 0 is legal and preserved — callers who mean "no data" and callers who mean "null data" both arrive at the omission; JSON-RPC treats the two alike.
toJson(): stringWire serialization — one line, no trailing newline, keys only when set.
toArray(): arrayInspection view: every key present, including the booleans and the wire-id pair.
isRequest(): boolOutgoing-shaped request: has a method, has an id, is not a notification.
isResponse(): boolA response carries no method — only result and/or error.
isNotification(): bool
isError(): bool
errorCode(): ?intThe JSON-RPC error code, or NULL when absent or malformed.
errorMessage(): ?stringThe JSON-RPC error message, or NULL when absent or malformed.

McpRouter final class

SERVER narrowing over a keyed map of MCP servers (tool rosters follow servers): deny patterns first, then an explicit allow-list.

MethodSummary
__construct(private readonly array $servers, array $denyPatterns = [])
resolveAllowedTools(array $allowList = []): arrayEvery tool from every allowed server, after the deny patterns and the server allow-list have had their say. Tool rosters arrive whole: the filter's unit is the SERVER.
resolveAllowedServers(array $allowList = []): arrayThe servers that survive deny patterns and the allow-list, keyed by name.
static serverDenied(string $server, array $denyPatterns): boolWhether ONE server name matches a deny-pattern config.
static serverAllowed(string $name, array $allowList): boolTHE LAW, EXPOSED. Whether ONE server name passes an allow-list.

McpServer interface

The contract every MCP server transport must honour: start, expose its tool table, answer tool calls, stop — plus the two raw RPC legs (request()/notify()) every transport speaks, so code typed against this interface can reach protocol traffic beyond the tool surface without growing a second type per transport family.

MethodSummary
start(): voidBring the server up and complete the MCP handshake (initialize → notifications/initialized → tools/list), caching the tool table.
stop(): voidTear the server down. Must be safe to call when never started and to call twice; implementations must leave no child process behind.
listTools(): arrayThe tool table captured at start(), each entry tagged with this server's name.
callTool(string $name, array $arguments): arrayInvoke a tool and return the MCP result payload as an array.
request(string $method, ?array $params = null, ?float $deadline = null): ?McpMessageOne raw request/response round trip — the leg callTool() rides, exposed for protocol traffic beyond the tool surface (resources, prompts, completion) without this contract growing speculative convenience methods.
notify(string $method, ?array $params = null, ?float $deadline = null): boolOne-way leg: send a notification, await nothing (JSON-RPC promises no reply). Same absolute-monotonic $deadline law as self::request().

McpTool final class

One tool definition advertised by an MCP server: name, description, JSON-Schema input contract, and the owning server.

MethodSummary
__construct(public readonly string $name, public readonly string $description, public readonly array $inputSchema, public readonly string $serverName, public readonly array $annotations = [])
static fromArray(array $definition, string $serverName): selfBuild from a wire tool definition. Absent or explicitly-null fields collapse to their defaults ('', []) — the ?? reads match the well-typedness gate below, which uses isset() semantics.
static tryFromArray(array $definition, string $serverName): ?selfParse-then-trust factory: null unless every wire field carries its declared type, so a malformed definition degrades to "skipped" instead of an exception at the construction subscript.

PendingCalls final class

The in-flight request table of a JSON-RPC client: register a settle callback under an id, settle it when the reply arrives, fail the whole table when the transport dies.

MethodSummary
register(string $id, \Closure $settle, bool $preserving = false): void
has(string $id): bool
isPreserving(string $id): bool
count(): int
settle(string $id, mixed $result): boolDeliver a successful result; false when $id is not pending.
fail(string $id, \Throwable $failure): boolDeliver a failure for one id; false when $id is not pending.
failAll(\Throwable|string $failure): intTransport death: fail every pending call with $failure (a string becomes a \RuntimeException) and empty the table first, so callbacks that register a retry land in a fresh table. Returns how many failed.

ProcessLiveness final class

The single home of the signal-0 liveness contract this library leans on in three places: who may claim an id sequence, whether a lock's owner still exists, and whether a forked observer still has a server to talk to. One kernel contract deserves one probe — the pre-extraction tree carried three hand-rolled variants whose fail-open shapes drifted apart, so a fix to one (say, a stricter EPERM reading) silently failed to reach the others.

MethodSummary
static ownerAlive(int $pid): boolRefuse-only-on-certainty polarity: true unless the kernel can prove the pid is absent.

RequestIdSequence final class

JSON-RPC request ids that stay unique across pcntl_fork().

MethodSummary
__construct(?\Closure $pidProvider = null, int $firstOwnerId = 0, ?\Closure $ownerAlive = null)
claim(): boolMake the CURRENT process the owner — called when a connection is opened, because the process that opened it is the one whose ids should look ordinary. The owner counter is not reset: an id is never reused within one object's lifetime, even across a stop()/start() cycle.
ownerPid(): int
isOwner(): boolIs the current process the one that opened the connection?
currentPid(): intThe current pid, as the provider reports it.
next(): int|stringThe next id: an int for the owner, a <pid>-<nonce>-<n> string for any other process. Transports that put ids on the wire as strings cast the int; a transport that historically sent integers keeps doing so for the owner. A matcher must therefore compare ids as strings.

StdioMcpServer final class

An MCP server reached over a child process' stdin/stdout, speaking newline-delimited JSON-RPC 2.0.

MethodSummary
__construct(public readonly string $name, private readonly string $command, private readonly array $args = [], private readonly array $env = [], ?float $startTimeoutSeconds = null, private readonly ?\Closure $spawnPlanner = null, array $clientInfo = self::DEFAULT_CLIENT_INFO, private readonly ?string $cwd = null, array $capabilities = [], ?\Closure $onServerMessage = null, private readonly ?string $lockDir = null, private readonly array $envRemove = [], private readonly ?array $curatedEnv = null, ?string $clientName = null, ?string $clientVersion = null)
__destruct()Orphan-proofing: a server the embedder forgot to stop dies with this object. stop() is idempotent, so an already-stopped instance is a no-op.
start(?\Closure $onWait = null): voidBegin the session: spawn, then run initialize → notifications/initialized → tools/list under one deadline.
stop(): voidTear the connection down: pipes first (a well-behaved server exits on stdin EOF before ever seeing a signal), then the TERM → poll → KILL → reap ladder, then the lock and the per-call state. Idempotent, and fork-aware — a non-owner clone closes only its own copies and leaves the connection to the process that started it.
stderrTail(): stringThe captured stderr tail, control characters swept. Survives stop() on purpose: a server that died is the one whose logs you want. The TEXT is server-authored and remains UNTRUSTED — render it through a sanitiser before terminal-facing display.
pumpStderr(): voidDrain pending stderr without blocking, for callers that idle between exchanges and want diagnostics warm. This is a CALLER-PUMPED seam on purpose: mounting it on an event loop would put two readers on one pipe, and pipe reads are destructive — whichever reader wins eats bytes the other was meant to see (the shared-pipe readership ruling: two readers on one pipe steal each other's bytes).
isUp(): boolIs the child process still alive?
listTools(): array
malformedToolDefinitions(): arrayLabels of the tools/list definitions refused by the well-typedness gate during the current start — the ones parseTools() skipped instead of registering. Post-mortem evidence: reset by every start(), kept by stop(). The view is capped at self::MALFORMED_LEDGER_CEILING entries; the full count rides the report.
malformedToolDefinitionsReport(): stringOne-line announcement for the skipped definitions, '' when the last tools/list walk registered everything the server advertised. Report it wherever the server's start outcome is surfaced — the roster is already SAFE (only valid definitions were registered); this is the half of the story the user must not have to guess. The count is the honest total; the named rows are the first few of a ledger capped at self::MALFORMED_LEDGER_CEILING, and a cut-off list says so with [+N more] — truncation announced, never silent.
serverInfo(): ?arrayThe server's advertised serverInfo (name, version, optional title) exactly as it answered the handshake — UNTRUSTED server-authored text: route it through Sanitize::untrusted before it reaches a terminal. Null before the first successful start(), after a start that never reached the judgement, or when the server omitted the member (see self::initializeResultDefects()). Survives stop(): "which server was this?" stays answerable post-mortem.
serverCapabilities(): ?arrayThe server's advertised capability map — the gate an embedder reads before trying resources/*, prompts/*, elicitation, or trusting a listChanged notification: null/absent means the server never claimed the feature. Same survival and untrusted-text laws as self::serverInfo().
initializeResultDefects(): arraySpec-required InitializeResult members the server failed to send (serverInfo, capabilities). The store is deliberately tolerant — a server that negotiated and listed tools boots, and these names tell the embedder WHY the accessors come back empty instead of leaving the omission unannounced. Empty list means the handshake was whole.
callTool(string $name, array $arguments, ?\Closure $onWait = null, ?float $timeoutSeconds = null, ?\Closure $onServerMessage = null): arrayInvoke a tool. No deadline by default (the no-blanket-timeout law): see the class docblock.
listResources(): arrayresources/list — the server's advertised resources. Same array-or-error shape as self::callTool(): the result payload on success, ['error' => ...] on any failure; never a throw, never null. The unbounded-wait law applies (this is protocol chatter without a defensible blanket budget — bound it via self::request() if you need a deadline).
readResource(string $uri): arrayresources/read — fetch one resource by URI.
listPrompts(): arrayprompts/list — the server's advertised prompt templates.
getPrompt(string $name, array $arguments = []): arrayprompts/get — render one prompt template. $arguments follows the tool-arguments law: an object map, a non-empty positional list is refused at the client door, and [] is repaired to an empty JSON object before the wire sees it.
request(string $method, ?array $params = null, ?float $deadline = null, ?\Closure $onServerMessage = null): ?McpMessageOne request/response round trip. Public so protocol traffic beyond tools (resources/list, prompts/get, completion) is one call away for embedders without this library growing that surface speculatively — the product implements none of it either.
notify(string $method, ?array $params = null, ?float $deadline = null): boolNotification leg of the protocol: no reply is awaited, but delivery is reported — true once the whole line went out, false when it did not (not started, dead pipe, lock or $deadline lost), so an embedder sending notifications/cancelled or progress can tell a dropped one.
writeFramed(string $json, ?float $deadline = null): boolPublic framing primitive: write exactly one newline-delimited JSON-RPC frame (payload + "\n") under an optional monotonic deadline, absorbing stderr while waiting for write-readiness — the same drain law every internal leg obeys, so a full stderr pipe can never wedge this side.
static monotonicNow(): floatThe clock every $deadline in this class is measured on: monotonic seconds since an arbitrary boot-relative origin (hrtime), never wall clock, never rewound by an NTP step (a handshake bound must ride a clock that only moves forward, matching sugar-core BoundedShutdown's own hrtime basis). Public so elapsed-time arithmetic is possible; to BOUND a wait, prefer self::deadlineAfter() over hand-adding.
static deadlineAfter(float $seconds): floatThe seatbelt for the two deadline idioms: self::request() and self::notify() take an ABSOLUTE monotonic instant while self::callTool() takes a RELATIVE duration — mixing them up (passing a duration where an instant belongs) fails quietly, because a small boot-relative instant sits in the past and the wait simply never starts, or a wall-clock magnitude can never be reached. This helper turns "how long" into "until when" on the one basis this class reads, so embedders never hand-combine the idioms.

SugarCraft\McpClient\JsonLines

Reader final class

Incremental newline splitter for JSON-Lines / NDJSON streams.

MethodSummary
__construct(private readonly ?int $maxLineBytes = null)
feed(string $chunk): arrayAppend a chunk; return the complete lines it finished, in order, WITHOUT their "\n". Empty lines are returned as ''.
partial(): stringThe retained unterminated tail, or '' — what an EOF-is-a-frame caller reads before reset(); an EOF-is-an-error caller reports it.
pendingBytes(): intBytes currently retained.
takeOversized(): intOver-cap lines discarded since the last call, then reset to zero.
reset(): voidForget the retained tail, any skip in progress, and the oversized count.

SugarCraft\McpClient\Protocol

ErrorCode enum

The candy-code.v1 error codes (Appendix O §6.2).

Cases: ParseError · InvalidRequest · MethodNotFound · InvalidParams · Unauthorized · NotInitialized · Forbidden · NotFound · Conflict · Busy · RateLimited · PermissionModeRefused · UnsupportedInServer · Internal

PHP also provides cases(), from() and tryFrom().

MethodSummary
kind(): stringThe default data.kind of an error with this code.
isRetryable(): boolWhether a client may simply retry a request that failed with this code.

JsonRpc final class

The candy-code.v1 JSON-RPC 2.0 codec (Appendix O §6.1).

MethodSummary
static decode(string $text): Request|arrayOne client message, or the error to answer it with. The error's id is the request's when one could be read, else null.
static result(string|int|null $id, mixed $result): stringA success response.
static error(string|int|null $id, RpcError $error): stringAn error response.
static notification(string $method, array $params): arrayA server→client notification, as an array (a caller may coalesce it before encoding).
static encodeValue(mixed $value, int $depth = self::MAX_DEPTH_VALUE): stringA bare value encoded under the wire's flags, with no envelope around it. The in-process door takes its answers through this so invalid UTF-8 is substituted the way the wire substitutes it, without building a JSON-RPC frame.
static encode(array $message): string

Refusal interface

A refused candy-code.v1 call, read the same way on the wire and in-process.

MethodSummary
refusalKind(): stringThe refusal's kind, the wire's data.kind (for example session_not_found).
refusalData(): array

Request final class

One decoded client message: a request (it has an id, and is answered) or a notification (it has none, and never is). The id is kept exactly as the client spelled it — string or integer — because a JSON-RPC response must echo it unchanged.

MethodSummary
__construct(public readonly string|int|null $id, public readonly bool $hasId, public readonly string $method, public readonly array $params)
isNotification(): bool

RpcError final class

A candy-code.v1 method's refusal: thrown by a method, answered by the Dispatcher as a JSON-RPC error object whose data.kind is the machine-readable reason (Appendix O §6.2). Nothing a client sent is echoed in the message; data carries only what the method chose to put there.

MethodSummary
static of(ErrorCode $code, string $message, ?string $kind = null, array $data = []): self
static invalidParams(string $message, string $kind = 'invalid_params'): self
static notFound(string $message, string $kind = 'not_found'): self
refusalKind(): string
refusalData(): arrayThe wire's data object: the same fields a JSON-RPC client decodes.
toArray(): arrayThe JSON-RPC error member.

Examples

examples/echo.php is a self-contained round trip. Run plainly, the file is the client: it starts itself as a server, runs initialize, tools/list and tools/call, and prints the exchange. Run with --serve, it is the stdio server. It needs no Node.js, no download and no network.

php examples/echo.php
server: example-echo 1.0.0
tool: echo - Echoes the message argument back as text
reply: echo: dependency-free round trip
OK

The suite runs this example headless (ExamplesTest), so the promise cannot rot.

Testing

cd sugar-mcp-client && composer install && vendor/bin/phpunit

The fixture servers under tests/Fixtures are PHP scripts that misbehave on purpose: they send oversized frames, stall, fork, write noise to stdout, or answer the handshake wrongly. The suite checks that the client refuses each of them with a named cause, so it needs no Node.js.

Troubleshooting and FAQ

start() throws after 60 seconds

The handshake deadline is 60 seconds by default, sized for a cold npx fetch. Raise startTimeoutSeconds: for a slow start. The exception carries the captured stderr, so the cause is usually in the message.

A tool shows up with escape codes or fails to list

Descriptions are server-authored prose. The transport does not scrub them, so pass every name and description through Sanitize::untrusted() before it reaches a terminal. A definition whose name carries control bytes is skipped. malformedToolDefinitions() lists what was skipped during the last start(), and malformedToolDefinitionsReport() gives a one-line summary.

foreach ($server->malformedToolDefinitions() as $label) {
    error_log("skipped MCP tool definition: {$label}");
}

A call returns ['error' => …] instead of throwing

This is by design. A failed call never throws, so check for the error key, as the task above shows. The payload names the cause: the server's JSON-RPC code and message, a dead child, or a refused frame.

A forked worker blocks on another worker's call

Each connection has one ExchangeLock, so exchanges serialize by design. Give each worker its own server if it needs to call in parallel. If start() fails with a lock error, check that lockDir: exists and that the filesystem accepts mode 0600.

The child sees my secrets

It inherits the full parent environment by default. Use envRemove: to drop named variables, or curatedEnv: to replace the environment entirely.

Upstream mapping

There is no Go port. The protocol is the Model Context Protocol revision 2024-11-05, which StdioMcpServer::PROTOCOL_VERSION pins. The table maps each protocol element to the class that implements it.

MCP protocol element to SugarCraft class
Protocol elementWhere it lives
JSON-RPC 2.0 envelopesMcpMessage, Protocol\JsonRpc
initialize and notifications/initializedStdioMcpServer::start()
tools/listStdioMcpServer::listTools(), McpTool
tools/callStdioMcpServer::callTool(), ArgumentShape::conform() for argument shapes
Resources and promptslistResources(), readResource(), listPrompts(), getPrompt()
Newline-delimited stdio transportStdioMcpServer, JsonLines\Reader

Changelog and versioning

This page does not record a release history. The commit history on GitHub is the change record. Two facts are stable and worth pinning on: the protocol revision (2024-11-05), and the deprecated ExchangeLock::create() alias, which is scheduled for removal in the 2.0.0 major.

Source and demos

Try the quickstart →