forked from php-mcp/server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRegisteredElement.php
More file actions
276 lines (241 loc) · 9.63 KB
/
RegisteredElement.php
File metadata and controls
276 lines (241 loc) · 9.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
<?php
declare(strict_types=1);
namespace PhpMcp\Server\Elements;
use InvalidArgumentException;
use JsonSerializable;
use PhpMcp\Server\Context;
use PhpMcp\Server\Exception\McpServerException;
use Psr\Container\ContainerInterface;
use ReflectionException;
use ReflectionFunctionAbstract;
use ReflectionMethod;
use ReflectionNamedType;
use ReflectionParameter;
use Throwable;
use TypeError;
class RegisteredElement implements JsonSerializable
{
/** @var callable|array|string */
public readonly mixed $handler;
public readonly bool $isManual;
public function __construct(
callable|array|string $handler,
bool $isManual = false,
) {
$this->handler = $handler;
$this->isManual = $isManual;
}
public function handle(ContainerInterface $container, array $arguments, Context $context): mixed
{
if (is_string($this->handler)) {
if (class_exists($this->handler) && method_exists($this->handler, '__invoke')) {
$reflection = new \ReflectionMethod($this->handler, '__invoke');
$arguments = $this->prepareArguments($reflection, $arguments, $context);
$instance = $container->get($this->handler);
return call_user_func($instance, ...$arguments);
}
if (function_exists($this->handler)) {
$reflection = new \ReflectionFunction($this->handler);
$arguments = $this->prepareArguments($reflection, $arguments, $context);
return call_user_func($this->handler, ...$arguments);
}
}
if (is_callable($this->handler)) {
$reflection = $this->getReflectionForCallable($this->handler);
$arguments = $this->prepareArguments($reflection, $arguments, $context);
return call_user_func($this->handler, ...$arguments);
}
if (is_array($this->handler)) {
[$className, $methodName] = $this->handler;
$reflection = new \ReflectionMethod($className, $methodName);
$arguments = $this->prepareArguments($reflection, $arguments, $context);
$instance = $container->get($className);
return call_user_func([$instance, $methodName], ...$arguments);
}
throw new \InvalidArgumentException('Invalid handler type');
}
protected function prepareArguments(\ReflectionFunctionAbstract $reflection, array $arguments, Context $context): array
{
$finalArgs = [];
foreach ($reflection->getParameters() as $parameter) {
// TODO: Handle variadic parameters.
$paramName = $parameter->getName();
$paramType = $parameter->getType();
$paramPosition = $parameter->getPosition();
if ($paramType instanceof ReflectionNamedType && $paramType->getName() === Context::class) {
$finalArgs[$paramPosition] = $context;
continue;
}
if (isset($arguments[$paramName])) {
$argument = $arguments[$paramName];
try {
$finalArgs[$paramPosition] = $this->castArgumentType($argument, $parameter);
} catch (InvalidArgumentException $e) {
throw McpServerException::invalidParams($e->getMessage(), $e);
} catch (Throwable $e) {
throw McpServerException::internalError(
"Error processing parameter `{$paramName}`: {$e->getMessage()}",
$e
);
}
} elseif ($parameter->isDefaultValueAvailable()) {
$finalArgs[$paramPosition] = $parameter->getDefaultValue();
} elseif ($parameter->allowsNull()) {
$finalArgs[$paramPosition] = null;
} elseif ($parameter->isOptional()) {
continue;
} else {
$reflectionName = $reflection instanceof \ReflectionMethod
? $reflection->class . '::' . $reflection->name
: 'Closure';
throw McpServerException::internalError(
"Missing required argument `{$paramName}` for {$reflectionName}."
);
}
}
return array_values($finalArgs);
}
/**
* Gets a ReflectionMethod or ReflectionFunction for a callable.
*/
private function getReflectionForCallable(callable $handler): \ReflectionMethod|\ReflectionFunction
{
if (is_string($handler)) {
return new \ReflectionFunction($handler);
}
if ($handler instanceof \Closure) {
return new \ReflectionFunction($handler);
}
if (is_array($handler) && count($handler) === 2) {
[$class, $method] = $handler;
return new \ReflectionMethod($class, $method);
}
throw new \InvalidArgumentException('Cannot create reflection for this callable type');
}
/**
* Attempts type casting based on ReflectionParameter type hints.
*
* @throws InvalidArgumentException If casting is impossible for the required type.
* @throws TypeError If internal PHP casting fails unexpectedly.
*/
private function castArgumentType(mixed $argument, ReflectionParameter $parameter): mixed
{
$type = $parameter->getType();
if ($argument === null) {
if ($type && $type->allowsNull()) {
return null;
}
}
if (! $type instanceof ReflectionNamedType) {
return $argument;
}
$typeName = $type->getName();
if (enum_exists($typeName)) {
if (is_object($argument) && $argument instanceof $typeName) {
return $argument;
}
if (is_subclass_of($typeName, \BackedEnum::class)) {
$value = $typeName::tryFrom($argument);
if ($value === null) {
throw new InvalidArgumentException(
"Invalid value '{$argument}' for backed enum {$typeName}. Expected one of its backing values.",
);
}
return $value;
} else {
if (is_string($argument)) {
foreach ($typeName::cases() as $case) {
if ($case->name === $argument) {
return $case;
}
}
$validNames = array_map(fn($c) => $c->name, $typeName::cases());
throw new InvalidArgumentException(
"Invalid value '{$argument}' for unit enum {$typeName}. Expected one of: " . implode(', ', $validNames) . "."
);
} else {
throw new InvalidArgumentException(
"Invalid value type '{$argument}' for unit enum {$typeName}. Expected a string matching a case name."
);
}
}
}
try {
return match (strtolower($typeName)) {
'int', 'integer' => $this->castToInt($argument),
'string' => (string) $argument,
'bool', 'boolean' => $this->castToBoolean($argument),
'float', 'double' => $this->castToFloat($argument),
'array' => $this->castToArray($argument),
default => $argument,
};
} catch (TypeError $e) {
throw new InvalidArgumentException(
"Value cannot be cast to required type `{$typeName}`.",
0,
$e
);
}
}
/** Helper to cast strictly to boolean */
private function castToBoolean(mixed $argument): bool
{
if (is_bool($argument)) {
return $argument;
}
if ($argument === 1 || $argument === '1' || strtolower((string) $argument) === 'true') {
return true;
}
if ($argument === 0 || $argument === '0' || strtolower((string) $argument) === 'false') {
return false;
}
throw new InvalidArgumentException('Cannot cast value to boolean. Use true/false/1/0.');
}
/** Helper to cast strictly to integer */
private function castToInt(mixed $argument): int
{
if (is_int($argument)) {
return $argument;
}
if (is_numeric($argument) && floor((float) $argument) == $argument && ! is_string($argument)) {
return (int) $argument;
}
if (is_string($argument) && ctype_digit(ltrim($argument, '-'))) {
return (int) $argument;
}
throw new InvalidArgumentException('Cannot cast value to integer. Expected integer representation.');
}
/** Helper to cast strictly to float */
private function castToFloat(mixed $argument): float
{
if (is_float($argument)) {
return $argument;
}
if (is_int($argument)) {
return (float) $argument;
}
if (is_numeric($argument)) {
return (float) $argument;
}
throw new InvalidArgumentException('Cannot cast value to float. Expected numeric representation.');
}
/** Helper to cast strictly to array */
private function castToArray(mixed $argument): array
{
if (is_array($argument)) {
return $argument;
}
throw new InvalidArgumentException('Cannot cast value to array. Expected array.');
}
public function toArray(): array
{
return [
'handler' => $this->handler,
'isManual' => $this->isManual,
];
}
public function jsonSerialize(): array
{
return $this->toArray();
}
}