SugarMCPClient
MCP client core — JSON-RPC codec, stdio transport, server narrowing
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. Extracted from candy-code's src/MCP stack and McpMessage codec, so every surface that talks to an MCP server rides the same framing and the same handshake-and-deadline doctrine wherever the transport is stdio. First-party — MCP is a spec, not a Go port.
Install
composer require sugarcraft/sugar-mcp-client
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(); // close pipes first, then TERM→KILL→reap — bounded teardown (see Fork safety for the SIGKILLed-owner residual).
// __destruct calls stop() for you if you forget.
The example spawns npx -y @modelcontextprotocol/server-everything, so it needs Node.js on PATH; the library itself depends only on PHP 8.3 and sugar-core — substitute any stdio MCP server command (name, command, argv list) for a dependency-free trial, or run php examples/echo.php, which is the whole trial in one file: it acts as the client when run plainly and as the stdio server when run with --serve, with nothing to install or download.
The model
McpServer interface: lifecycle, tool surface, and the shared raw legs request()/notify().hrtime) deadline across the whole handshake, protocol-version negotiation, and a per-second handshake beat via start(onWait:).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.Use it for
- Speaking MCP from any PHP process — spawn a stdio server child, handshake, list and call tools, with the framing and timeout discipline already fought for.
- Agent tool surfaces — narrow which servers each agent may see with globs and deny-before-allow, tool rosters following servers, the same semantics candy-code builds on.
- Bounded subprocess I/O — the transport doubles as 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); the named residual is external — a process SIGKILLed mid-use leaves its child to the embedding process manager.
Source
API
| Class | Method | Description |
|---|---|---|
| McpMessage | parse(string $json): ?self | Decode 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); nesting past the 64-level bound yields null, depth 64 itself parses |
| McpMessage | request(string $id, string $method, ?array $params) / notification(string $method, ?array $params): self | Outbound request and notification envelopes |
| McpMessage | success(string $id, mixed $result) / error(string $id, int $code, string $message, mixed $data = null): self | Outbound response envelopes; result is mixed by design; an explicit "data": null is indistinguishable from an absent one on round-trip |
| McpMessage | toJson(): string / isRequest() / isResponse() / isNotification() / isError(): bool | Wire serialization + role predicates; toJson() throws InvalidArgumentException for an envelope JSON cannot carry (INF/NAN, invalid UTF-8) instead of emitting a blank frame |
| McpMessage | parsePreservingId(string $json): ?self / withWireId(string|int|null $wireId): self | The 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) |
| McpMessage | errorCode(): ?int / errorMessage(): ?string | Honest 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' |
| StdioMcpServer | start(?\Closure $onWait = null): void / stop(): void / isUp(): bool | Handshake 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 |
| StdioMcpServer | listResources(): array / readResource(string $uri): array / listPrompts(): array / getPrompt(string $name, array $arguments = []): array | the 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 |
| StdioMcpServer | writeFramed(string $json, ?float $deadline = null): bool | The 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() |
| StdioMcpServer | listTools(): list<McpTool> / callTool(string $name, array $arguments, ?\Closure $onWait = null, ?float $timeoutSeconds = null, ?\Closure $onServerMessage = null): array | tools/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; 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) |
| StdioMcpServer | request(string $method, ?array $params = null, ?float $deadline = null, ?\Closure $onServerMessage = null): ?McpMessage / notify(string $method, ?array $params = null, ?float $deadline = null): bool | Escapeway 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 |
| StdioMcpServer | stderrTail(): string / static monotonicNow(): float | The 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 |
| StdioMcpServer | pumpStderr(): void | Non-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 |
| StdioMcpServer | malformedToolDefinitions(): list<string> / malformedToolDefinitionsReport(): string | The 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() |
| StdioMcpServer | serverInfo(): ?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 |
| McpServer | interface: 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): bool | The 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 |
| ArgumentShape | conform(array $arguments, array $inputSchema): array | Restores 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 |
| RequestIdSequence | next(): int|string / claim(): bool / isOwner(): bool | JSON-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 |
| RequestIdSequence | ownerPid(): int / currentPid(): int | The 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) |
| McpTool | fromArray(array $definition, string $serverName): self / tryFromArray(array $definition, string $serverName): ?self | Parse 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 |
| McpRouter | resolveAllowedTools(array $allowList = []): list<McpTool> / resolveAllowedServers(array $allowList = []): array | Deny-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 |
| McpRouter | static serverDenied(string $server, array $denyPatterns): bool / static serverAllowed(string $name, array $allowList): bool | The 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 |
| ExchangeLock | static new(string $label, ?string $dir = null): self / static sweepStale(?string $dir = null): int | Cross-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 |
| ExchangeLock | acquire(?float $deadline, \Closure $serverAlive): bool / load(): array / store(string $phase, string $buffer): bool / markPhase(string $phase): bool | Phase byte + carried read buffer under the lock; store()/markPhase() return false when the write did not land, and an empty file loads as dirty |
| ExchangeLock | release(): void / close(): void / destroy(): void | The 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 |