Skip to content

Commit 48f878f

Browse files
feat: add callable tool handler example
[skip ci]
1 parent 2269c70 commit 48f878f

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

examples/02-discovery-http-userprofile/server.php

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,48 @@ public function log($level, \Stringable|string $message, array $context = []): v
7070
->withCapabilities(ServerCapabilities::make(completions: true, logging: true))
7171
->withLogger($logger)
7272
->withContainer($container)
73+
->withTool(
74+
function (float $a, float $b, string $operation = 'add'): array {
75+
$result = match ($operation) {
76+
'add' => $a + $b,
77+
'subtract' => $a - $b,
78+
'multiply' => $a * $b,
79+
'divide' => $b != 0 ? $a / $b : throw new \InvalidArgumentException('Cannot divide by zero'),
80+
default => throw new \InvalidArgumentException("Unknown operation: {$operation}")
81+
};
82+
83+
return [
84+
'operation' => $operation,
85+
'operands' => [$a, $b],
86+
'result' => $result
87+
];
88+
},
89+
name: 'calculator',
90+
description: 'Perform basic math operations (add, subtract, multiply, divide)'
91+
)
92+
->withResource(
93+
function (): array {
94+
$memoryUsage = memory_get_usage(true);
95+
$memoryPeak = memory_get_peak_usage(true);
96+
$uptime = time() - $_SERVER['REQUEST_TIME_FLOAT'] ?? time();
97+
$serverSoftware = $_SERVER['SERVER_SOFTWARE'] ?? 'CLI';
98+
99+
return [
100+
'server_time' => date('Y-m-d H:i:s'),
101+
'uptime_seconds' => $uptime,
102+
'memory_usage_mb' => round($memoryUsage / 1024 / 1024, 2),
103+
'memory_peak_mb' => round($memoryPeak / 1024 / 1024, 2),
104+
'php_version' => PHP_VERSION,
105+
'server_software' => $serverSoftware,
106+
'operating_system' => PHP_OS_FAMILY,
107+
'status' => 'healthy'
108+
];
109+
},
110+
uri: 'system://status',
111+
name: 'system_status',
112+
description: 'Current system status and runtime information',
113+
mimeType: 'application/json'
114+
)
73115
->build();
74116

75117
$server->discover(__DIR__, ['.']);

0 commit comments

Comments
 (0)