PHP code example of mesh0 / sdk

1. Go to this page and download the library: Download mesh0/sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mesh0 / sdk example snippets


use Mesh0\Client;
use Mesh0\Event\Event;

$mesh0 = Client::create('m0_abcde_xxxxxxxxxxxxxxxxxxxxxxxx');

// Send a single event. The wire shape is intentionally narrow — identity,
// time, plus two open bins (`attributes` queryable, `data` opaque).
// Anything domain-specific goes inside attributes / data.
$mesh0->events->send(
    Event::now()
        ->withAttributes([
            'app.id'          => 'checkout',
            'app.environment' => 'prod',
            'span.name'       => 'charge.captured',
            'user.id'         => 'user_42',
            'order_id'        => 'ord_123',
            'amount_usd'      => 19.99,
        ]),
);

$mesh0 = Client::fromEnv();

$logger = $mesh0->logger(defaults: [
    'app.id'          => 'web',
    'app.environment' => 'prod',
]);

$logger->info('user {user} signed up', ['user' => 'alice', 'plan' => 'pro']);

try {
    chargeCard($order);
} catch (\Throwable $e) {
    $logger->error('charge failed', [
        'exception' => $e,
        'order_id'  => $order->id,
        'user.id'   => $order->userId,
    ]);
}

$logger = $mesh0->logger(
    defaults: ['app.id' => 'web'],
    fallback: $appLogger, // receives flush errors + malformed-input warnings
);

// config/logging.php
'channels' => [
    'mesh0' => [
        'driver' => 'custom',
        'via'    => fn () => Mesh0\Client::fromEnv()->logger(defaults: [
            'app.id'          => config('app.name'),
            'app.environment' => config('app.env'),
        ]),
    ],
],

$mesh0->events->send(
    Event::now()
        ->withTraceId($traceId)
        ->withAttributes([
            'app.id'                       => 'agents',
            'app.environment'              => 'prod',
            'span.name'                    => 'agent.run',
            'duration_ms'                  => 820,
            'status'                       => 'success',
            'gen_ai.system'                => 'anthropic',
            'gen_ai.request.model'         => 'claude-opus-4-7',
            'gen_ai.usage.input_tokens'    => 1_240,
            'gen_ai.usage.output_tokens'   => 380,
            'gen_ai.usage.cost_usd'        => 0.0184,
            'tools'                        => ['search', 'retrieve'],
            'workflow'                     => 'onboarding',
        ])
        // Big payloads (LLM message arrays, raw req/resp) go in `data` —
        // opaque, not TQL-queryable, only shown on single-event drilldown.
        ->withData(['messages' => $messages]),
);

// Bulk: send up to 5,000 events per HTTP call. Larger batches are split.
$mesh0->events->sendMany($events);

$spans = $mesh0->traces->get($traceId);

$metrics = $mesh0->metrics(); // reads MESH0_AGENT_SOCKET / Config::$agentSocketPath

$metrics->increment('checkout.charge', tags: ['tier' => 'pro']);
$metrics->gauge('queue.depth', 42);
$metrics->timing('db.query_ms', 12.4, tags: ['table' => 'orders']);
$metrics->histogram('upload.bytes', 8192);

// Convenience: time a block; metric is emitted whether $fn returns or throws.
$rows = $metrics->time('db.select_ms', fn () => $pdo->query($sql)->fetchAll());

$metrics = $mesh0->metrics(socketPath: '/tmp/mesh0-test.sock', defaultTags: [
    'service' => 'checkout',
    'env'     => 'prod',
]);

$agent = $mesh0->events->agent(); // reads MESH0_AGENT_SOCKET / Config::$agentSocketPath

$agent->send(
    Mesh0\Event\Event::now()
        ->withAttributes([
            'app.id'          => 'checkout',
            'app.environment' => 'prod',
            'span.name'       => 'charge.succeeded',
            'order_id'        => 'ord_123',
        ]),
);

// Bulk loop — the agent batches before forwarding to mesh0.
$agent->sendMany([$e1, $e2, $e3]);

$tracer = $mesh0->tracer();

// Closure form — exception-safe, auto-pop, recommended:
$result = $tracer->span(['span.name' => 'block.if', 'block_id' => 'b_123'], function () use ($tracer) {
    return $tracer->span(['span.name' => 'block.http_request', 'url' => $url], fn () => $client->get($url));
});

// Manual form — when a closure doesn't fit (e.g. block dispatchers):
$h = $tracer->enter(['span.name' => 'block.loop', 'block_id' => 'b_456']);
try {
    // run block...
    $tracer->exit($h, attributes: ['iterations' => $n]);
} catch (\Throwable $e) {
    $tracer->exit($h, [
        'status'        => 'error',
        'error.type'    => $e::class,
        'error.message' => $e->getMessage(),
    ]);
    throw $e;
}

$tracer->startTrace($_SERVER['HTTP_TRACEPARENT'] ?? null);
// First enter() of the request now links to the upstream parent span.

$logger = $mesh0->logger(
    defaults: ['app.id' => 'no-code-runtime'],
    tracer: $tracer,
);

$tracer->span(['span.name' => 'block.http_request'], function () use ($logger) {
    $logger->info('calling upstream'); // trace_id / span_id stamped automatically
});

// Only the identity/time TQL builtins resolve at the top level:
// `timestamp, project.id, trace.id, span.id, parent_span.id`. Anything
// else (status, duration_ms, span.name, gen_ai.*, …) must be exposed via
// a per-project alias or promoted column — set those up in the dashboard,
// then reference them by their alias name here.
$rows = $mesh0->query->run([
    'from'    => 'events',
    'select'  => ['status', 'count()'],
    'where'   => ['status' => 'error'],
    'groupBy' => ['status'],
    'orderBy' => [['count()', 'desc']],
    'limit'   => 25,
]);

$page = $mesh0->events->list(limit: 100);
foreach ($page['events'] as $row) { /* … */ }

// Or stream every event, transparently following cursors:
foreach ($mesh0->events->iterate() as $row) { /* … */ }

// Alerts (project key, m0_… — POST sends Idempotency-Key automatically).
$alerts   = $mesh0->alerts->listAlerts();
$channels = $mesh0->alerts->listChannels();
$mesh0->alerts->createAlert([/* AlertInput */]);

// PII scrubbers (project key, crubbers->setMode('enforce'); // 'enforce' | 'audit' | 'off'

// Schema — aliases + promoted (typed) columns
// (project key, = $mesh0->usage->summary();         // current cap period
$series  = $mesh0->usage->series('2026-01-01', '2026-04-01', 'month');

// User / org / project management (user key, m0u_…).
$me    = $mesh0->user->me();
$keys  = $mesh0->user->listProjectKeys('acme', 'p_1');

use Mesh0\Client;
use Mesh0\Config;

$mesh0 = new Client(new Config(
    apiKey: 'm0_abcde_xxxxxxxxxxxxxxxxxxxxxxxx',
    baseUrl: 'https://api.mesh0.ai',
    timeout: 10.0,
    connectTimeout: 5.0,
    maxRetries: 2,
    userAgent: 'my-app/1.0',
    defaultHeaders: ['X-Tenant' => 'acme'],
));

use GuzzleHttp\Client as Guzzle;
use GuzzleHttp\Psr7\HttpFactory;

$guzzle = new Guzzle(['timeout' => 5]);
$factory = new HttpFactory();

$mesh0 = new Client(Config::fromEnv(), $guzzle, $factory, $factory);