transport = $transport ?? Closure::fromCallable([self::class, 'curlTransport']); } private static function curlTransport(string $endpoint, array $message, array $headers): array { if (!extension_loaded('curl')) throw new EwooksMcpExampleError('Enable the PHP curl extension.'); $curl = curl_init($endpoint); $body = ''; $oversized = false; try { curl_setopt_array($curl, [ CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($message, JSON_THROW_ON_ERROR), CURLOPT_HTTPHEADER => $headers, CURLOPT_FOLLOWLOCATION => false, CURLOPT_PROTOCOLS => CURLPROTO_HTTPS, CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_TIMEOUT => 30, CURLOPT_WRITEFUNCTION => static function ($handle, string $chunk) use (&$body, &$oversized): int { if (strlen($body) + strlen($chunk) > self::MAX_BYTES) { $oversized = true; return 0; } $body .= $chunk; return strlen($chunk); }, ]); if (curl_exec($curl) === false) { throw new EwooksMcpExampleError($oversized ? 'Response exceeds the client size limit.' : 'MCP connection failed.'); } return ['status' => (int)curl_getinfo($curl, CURLINFO_HTTP_CODE), 'body' => $body]; } finally { curl_close($curl); } } public function request(string $method, array $params, bool $notification = false): array { $id = ++$this->sequence; $message = ['jsonrpc' => '2.0', 'method' => $method, 'params' => $params ?: (object)[]]; if (!$notification) $message['id'] = $id; try { $response = ($this->transport)($this->endpoint, $message, [ 'Authorization: Bearer ' . $this->key, 'Content-Type: application/json', 'Accept: application/json, text/event-stream', 'MCP-Protocol-Version: ' . self::PROTOCOL, ]); } catch (Throwable $error) { throw $error instanceof EwooksMcpExampleError ? $error : new EwooksMcpExampleError('MCP connection failed.'); } $status = $response['status'] ?? 0; if ($status >= 300 && $status < 400) throw new EwooksMcpExampleError('Redirect refused. Verify the fixed HTTPS endpoint.'); if ($notification && in_array($status, [200, 202, 204], true)) return []; if ($status !== 200) throw new EwooksMcpExampleError('MCP HTTP request failed. Check access or retry later with bounded backoff.'); $raw = $response['body'] ?? null; if (!is_string($raw) || strlen($raw) > self::MAX_BYTES) throw new EwooksMcpExampleError('Invalid or oversized response.'); try { $body = json_decode($raw, true, 64, JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING); } catch (JsonException $error) { throw new EwooksMcpExampleError('MCP returned invalid JSON.'); } if (!is_array($body) || ($body['jsonrpc'] ?? null) !== '2.0' || ($body['id'] ?? null) !== $id) throw new EwooksMcpExampleError('Unexpected JSON-RPC response.'); if (array_key_exists('error', $body)) throw new EwooksMcpExampleError('JSON-RPC request failed.'); if (!is_array($body['result'] ?? null) || !empty($body['result']['isError'])) throw new EwooksMcpExampleError('MCP tool failed. Check limits, cursor and authorization.'); return $body['result']; } public function initialize(): void { $result = $this->request('initialize', [ 'protocolVersion' => self::PROTOCOL, 'capabilities' => (object)[], 'clientInfo' => ['name' => 'ewooks-php-snapshot-example', 'version' => '1.0'], ]); $version = is_array($result['serverInfo'] ?? null) ? ($result['serverInfo']['version'] ?? null) : null; if (!is_string($version) || !preg_match('/\A0\.2\.[0-9]+\z/', $version)) throw new EwooksMcpExampleError('This example requires a verified Ewooks MCP 0.2 deployment.'); if (($result['protocolVersion'] ?? null) !== self::PROTOCOL) throw new EwooksMcpExampleError('Unexpected negotiated protocol version.'); $this->request('notifications/initialized', [], true); } private static function dateValue(string $value): DateTimeImmutable { $date = DateTimeImmutable::createFromFormat('!Y-m-d', $value, new DateTimeZone('UTC')); if (!$date || $date->format('Y-m-d') !== $value || (int)$date->format('Y') < 1) throw new EwooksMcpExampleError('Use valid dates in YYYY-MM-DD format.'); return $date; } public function records(string $resource, string $from, string $to, ?string $driver = null): Generator { if (!in_array($resource, ['drives', 'work-sessions'], true)) throw new EwooksMcpExampleError('Unsupported resource.'); $first = self::dateValue($from); $last = self::dateValue($to); if ($last < $first || $first->diff($last)->days >= 366) throw new EwooksMcpExampleError('Choose at most 366 inclusive dates.'); if ($driver !== null && !preg_match('/\A.{0,100}\z/us', $driver)) throw new EwooksMcpExampleError('Invalid driver filter.'); $field = $resource === 'drives' ? 'drives' : 'work_sessions'; $args = ['from' => $from, 'to' => $to, 'pagination' => 'snapshot', 'limit' => 100]; if ($driver !== null) $args['driver'] = $driver; $cursors = $identities = []; $fleet = null; for ($page = 0; $page < 10000; $page++) { $result = $this->request('tools/call', ['name' => 'list_' . $field, 'arguments' => $args]); $data = $result['structuredContent'] ?? null; if (!is_array($data) || ($data['pagination'] ?? null) !== 'snapshot' || !array_key_exists('next_cursor', $data)) throw new EwooksMcpExampleError('Snapshot pagination unavailable; no live-pagination fallback is allowed.'); $rows = $data[$field] ?? null; if (!is_array($rows) || !array_is_list($rows) || count($rows) > 100) throw new EwooksMcpExampleError('Unexpected page shape.'); foreach ($rows as $row) { if (!is_array($row)) throw new EwooksMcpExampleError('Unexpected source record shape.'); $id = $row['id'] ?? null; if ((!is_int($id) && !is_string($id)) || !preg_match('/\A[0-9]+\z/', (string)$id) || !is_string($row['fleet_id'] ?? null) || $row['fleet_id'] === '') throw new EwooksMcpExampleError('Missing or unsafe source identity.'); $fleet ??= $row['fleet_id']; if ($fleet !== $row['fleet_id']) throw new EwooksMcpExampleError('Unexpected fleet change. Stop and investigate.'); $identity = json_encode([$row['fleet_id'], (string)$id], JSON_THROW_ON_ERROR); if (isset($identities[$identity])) throw new EwooksMcpExampleError('Duplicate source identity. Stop and reconcile.'); $identities[$identity] = true; yield $row; } $cursor = $data['next_cursor']; if ($cursor === null) return; if (!is_string($cursor) || $cursor === '' || isset($cursors[$cursor])) throw new EwooksMcpExampleError('Invalid or repeated continuation cursor.'); $cursors[$cursor] = true; $args['cursor'] = $cursor; } throw new EwooksMcpExampleError('Page limit reached.'); } } function ewooksMcpExampleMain(array $argv, ?Closure $transport = null): int { $stream = null; $temporary = null; try { $options = ['resource' => 'drives']; for ($i = 1; $i < count($argv); $i++) { if ($argv[$i] === '--help') { echo "Usage: php ewooks_mcp_client.php.txt --from YYYY-MM-DD --to YYYY-MM-DD [--resource drives|work-sessions] [--driver NAME] [--output NEW_FILE]\n"; return 0; } if (!in_array($argv[$i], ['--from', '--to', '--resource', '--driver', '--output'], true) || !isset($argv[$i + 1])) throw new EwooksMcpExampleError('Use --from YYYY-MM-DD --to YYYY-MM-DD and the documented optional arguments.'); $name = substr($argv[$i], 2); $i++; $options[$name] = $argv[$i]; } if (!isset($options['from'], $options['to'])) throw new EwooksMcpExampleError('Both --from and --to are required.'); $client = new EwooksMcpExampleClient(getenv('EWOOKS_MCP_URL') ?: 'https://mcp.ewooks.fi/mcp', getenv('EWOOKS_MCP_KEY') ?: '', $transport); if (isset($options['output'])) { if (file_exists($options['output']) || is_link($options['output'])) throw new EwooksMcpExampleError('Output already exists; choose a new file.'); $candidate = dirname($options['output']) . DIRECTORY_SEPARATOR . '.ewooks-' . bin2hex(random_bytes(16)); $mask = umask(0077); try { $stream = @fopen($candidate, 'x+b'); } finally { umask($mask); } if ($stream === false) throw new EwooksMcpExampleError('Could not create a private temporary output.'); $temporary = $candidate; } $client->initialize(); $count = 0; foreach ($client->records($options['resource'], $options['from'], $options['to'], $options['driver'] ?? null) as $row) { $count++; if ($stream) { $line = json_encode($row, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . "\n"; if (fwrite($stream, $line) !== strlen($line)) throw new EwooksMcpExampleError('Output write failed.'); } } if ($stream) { if (!fclose($stream)) throw new EwooksMcpExampleError('Output close failed.'); $stream = null; if (!@link($temporary, $options['output'])) throw new EwooksMcpExampleError('Could not publish a complete new output file.'); } echo "Read {$count} records from one bounded snapshot. No downstream writes performed.\n"; return 0; } catch (Throwable $error) { fwrite(STDERR, ($error instanceof EwooksMcpExampleError ? $error->getMessage() : 'Read failed; no complete output was published.') . "\n"); return 1; } finally { if (is_resource($stream)) fclose($stream); if ($temporary !== null) @unlink($temporary); } } if (realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === __FILE__) { if (PHP_SAPI !== 'cli') { http_response_code(404); exit; } exit(ewooksMcpExampleMain($argv)); }