-
Notifications
You must be signed in to change notification settings - Fork 125
Expand file tree
/
Copy pathReferenceHandler.php
More file actions
282 lines (239 loc) · 9.78 KB
/
ReferenceHandler.php
File metadata and controls
282 lines (239 loc) · 9.78 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
277
278
279
280
281
282
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Capability\Registry;
use Mcp\Exception\InvalidArgumentException;
use Mcp\Exception\RegistryException;
use Mcp\Server\RequestContext;
use Mcp\Server\Session\SessionInterface;
use Psr\Container\ContainerInterface;
/**
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
final class ReferenceHandler implements ReferenceHandlerInterface
{
public function __construct(
private readonly ?ContainerInterface $container = null,
) {
}
/**
* @param array<string, mixed> $arguments
*/
public function handle(ElementReference $reference, array $arguments): mixed
{
$session = $arguments['_session'];
if (\is_string($reference->handler)) {
if (class_exists($reference->handler) && method_exists($reference->handler, '__invoke')) {
$reflection = new \ReflectionMethod($reference->handler, '__invoke');
$instance = $this->getClassInstance($reference->handler);
$arguments = $this->prepareArguments($reflection, $arguments);
return \call_user_func($instance, ...$arguments);
}
if (\function_exists($reference->handler)) {
$reflection = new \ReflectionFunction($reference->handler);
$arguments = $this->prepareArguments($reflection, $arguments);
return \call_user_func($reference->handler, ...$arguments);
}
}
if (\is_callable($reference->handler)) {
$reflection = $this->getReflectionForCallable($reference->handler, $session);
$arguments = $this->prepareArguments($reflection, $arguments);
return \call_user_func($reference->handler, ...$arguments);
}
if (\is_array($reference->handler)) {
[$className, $methodName] = $reference->handler;
$reflection = new \ReflectionMethod($className, $methodName);
$instance = $this->getClassInstance($className);
$arguments = $this->prepareArguments($reflection, $arguments);
return \call_user_func([$instance, $methodName], ...$arguments);
}
throw new InvalidArgumentException('Invalid handler type');
}
private function getClassInstance(string $className): object
{
if (null !== $this->container && $this->container->has($className)) {
return $this->container->get($className);
}
return new $className();
}
/**
* @param array<string, mixed> $arguments
*
* @return array<int, mixed>
*/
private function prepareArguments(\ReflectionFunctionAbstract $reflection, array $arguments): array
{
$finalArgs = [];
foreach ($reflection->getParameters() as $parameter) {
// TODO: Handle variadic parameters.
$paramName = $parameter->getName();
$paramPosition = $parameter->getPosition();
// Check if parameter is a special injectable type
$type = $parameter->getType();
if ($type instanceof \ReflectionNamedType && !$type->isBuiltin()) {
$typeName = $type->getName();
if (RequestContext::class === $typeName && isset($arguments['_session'], $arguments['_request'])) {
$finalArgs[$paramPosition] = new RequestContext($arguments['_session'], $arguments['_request']);
continue;
}
}
if (isset($arguments[$paramName])) {
$argument = $arguments[$paramName];
try {
$finalArgs[$paramPosition] = $this->castArgumentType($argument, $parameter);
} catch (InvalidArgumentException $e) {
throw RegistryException::invalidParams($e->getMessage(), $e);
} catch (\Throwable $e) {
throw RegistryException::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 RegistryException::internalError("Missing required argument `{$paramName}` for {$reflectionName}.");
}
}
return array_values($finalArgs);
}
/**
* Gets a ReflectionMethod or ReflectionFunction for a callable.
*/
private function getReflectionForCallable(callable $handler, SessionInterface $session): \ReflectionMethod|\ReflectionFunction
{
if (\is_string($handler)) {
return new \ReflectionFunction($handler);
}
if ($handler instanceof \Closure) {
return new \ReflectionFunction($handler);
}
if (\is_array($handler) && 2 === \count($handler)) {
[$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
*/
private function castArgumentType(mixed $argument, \ReflectionParameter $parameter): mixed
{
$type = $parameter->getType();
if (null === $argument) {
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 (null === $value) {
throw new InvalidArgumentException("Invalid value '{$argument}' for backed enum {$typeName}. Expected one of its backing values.");
}
return $value;
}
if (\is_string($argument)) {
foreach ($typeName::cases() as $case) {
if ($case->name === $argument) {
return $case;
}
}
$validNames = array_map(static fn ($c) => $c->name, $typeName::cases());
throw new InvalidArgumentException("Invalid value '{$argument}' for unit enum {$typeName}. Expected one of: ".implode(', ', $validNames).'.');
}
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 (1 === $argument || '1' === $argument || 'true' === strtolower((string) $argument)) {
return true;
}
if (0 === $argument || '0' === $argument || 'false' === strtolower((string) $argument)) {
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.
*
* @return array<int, mixed>
*/
private function castToArray(mixed $argument): array
{
if (\is_array($argument)) {
return $argument;
}
throw new InvalidArgumentException('Cannot cast value to array. Expected array.');
}
}