devbox/examples/mcpd/status.php
shoemoney 70054e68e6
Some checks are pending
CI / vet-build-test (push) Waiting to run
docs: add tested Mozilla AI mcpd integration and PHP example
2026-11-27 22:03:23 -06:00

45 lines
1.7 KiB
PHP

<?php
declare(strict_types=1);
// Plain HTTP example for mcpd's REST API. Plugin SDKs are a separate layer.
$base = rtrim(getenv('MCPD_URL') ?: 'http://127.0.0.1:8090', '/');
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => "Content-Type: application/json\r\nAccept: application/json\r\n",
'content' => '{}',
'timeout' => 10,
'ignore_errors' => true,
],
]);
try {
$response = file_get_contents($base . '/api/v1/servers/devbox/tools/devbox_status', false, $context);
if ($response === false) {
throw new RuntimeException('Could not reach mcpd; check MCPD_URL and daemon status.');
}
$headers = $http_response_header ?? [];
$status = 0;
foreach ($headers as $header) {
if (preg_match('~^HTTP/\S+\s+(\d{3})~', $header, $matches)) {
$status = (int) $matches[1];
}
}
if ($status < 200 || $status >= 300) {
throw new RuntimeException('mcpd returned HTTP ' . $status . ': ' . $response);
}
$result = json_decode($response, true, 512, JSON_THROW_ON_ERROR);
// mcpd v0.7.0 returns a JSON string containing devbox's text envelope.
if (is_string($result)) {
$result = json_decode($result, true, 512, JSON_THROW_ON_ERROR);
}
if (!is_array($result) || !array_key_exists('exit_code', $result)) {
throw new RuntimeException('Unexpected mcpd response shape.');
}
echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR), PHP_EOL;
exit($result['exit_code'] === 0 && empty($result['error']) ? 0 : 1);
} catch (Throwable $error) {
fwrite(STDERR, $error->getMessage() . PHP_EOL);
exit(1);
}