Repository navigation
Expand file tree
/
Copy pathTool.php
More file actions
327 lines (298 loc) · 12.4 KB
/
Copy pathTool.php
File metadata and controls
327 lines (298 loc) · 12.4 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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
<?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\Schema;
use Mcp\Schema\Exception\InvalidArgumentException;
use Mcp\Schema\Wire\McpHeader;
/**
* Definition for a tool the client can call.
*
* @phpstan-import-type ToolAnnotationsData from ToolAnnotations
* @phpstan-import-type IconData from Icon
* @phpstan-import-type ToolExecutionData from ToolExecution
*
* @phpstan-type ToolInputSchema array{
* type: 'object',
* properties?: array<mixed>|\stdClass,
* required?: array<mixed>|null
* }
* @phpstan-type ToolOutputSchema array<string, mixed>
* @phpstan-type ToolData array{
* name: string,
* title?: string,
* inputSchema: ToolInputSchema,
* description?: string|null,
* annotations?: ToolAnnotationsData,
* icons?: IconData[],
* _meta?: array<string, mixed>,
* outputSchema?: ToolOutputSchema,
* execution?: ToolExecutionData
* }
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
class Tool implements \JsonSerializable
{
/**
* JSON Schema keywords whose value is a single sub-schema.
*/
private const SUB_SCHEMA_KEYWORDS = [
'additionalItems',
'additionalProperties',
'contains',
'else',
'if',
'not',
'propertyNames',
'then',
'unevaluatedItems',
'unevaluatedProperties',
];
/**
* JSON Schema keywords whose value maps names to sub-schemas.
*/
private const SUB_SCHEMA_MAP_KEYWORDS = [
'$defs',
'definitions',
'dependentSchemas',
'patternProperties',
'properties',
];
/**
* JSON Schema keywords whose value is a list of sub-schemas.
*/
private const SUB_SCHEMA_LIST_KEYWORDS = [
'allOf',
'anyOf',
'oneOf',
'prefixItems',
];
/**
* @var ToolInputSchema
*/
public readonly array $inputSchema;
/**
* @var ToolOutputSchema|null
*/
public readonly ?array $outputSchema;
/**
* @param string $name the name of the tool
* @param ?string $title Optional human-readable title for display in UI
* @param array<string, mixed> $inputSchema a JSON Schema object (as a PHP array) defining the expected 'arguments' for the tool
* @param ?string $description A human-readable description of the tool.
* This can be used by clients to improve the LLM's understanding of
* available tools. It can be thought of like a "hint" to the model.
* @param ?ToolAnnotations $annotations optional additional tool information
* @param ?Icon[] $icons optional icons representing the tool
* @param ?array<string, mixed> $meta Optional metadata
* @param array<string, mixed>|null $outputSchema Optional JSON Schema (as a PHP array) describing the tool's
* structuredContent. Unlike $inputSchema its root is unconstrained —
* it may describe an array, a primitive, or a composition.
* @param ?ToolExecution $execution optional execution-related properties, such as whether the
* tool can be called as a task
*/
public function __construct(
public readonly string $name,
public readonly ?string $title,
array $inputSchema,
public readonly ?string $description,
public readonly ?ToolAnnotations $annotations,
public readonly ?array $icons = null,
public readonly ?array $meta = null,
?array $outputSchema = null,
public readonly ?ToolExecution $execution = null,
) {
// Always normalize here so every construction path emits `{}` for empty
// sub-schemas — not only SchemaGenerator / fromArray.
$this->inputSchema = self::normalizeInputSchema($inputSchema);
$this->outputSchema = null !== $outputSchema ? self::normalizeSchema($outputSchema) : null;
// An out-of-bounds `x-mcp-header` reachable through `properties` makes
// the whole tool definition invalid, so it is refused where the tool
// is defined rather than discovered when a header comparison
// mysteriously fails.
if (null !== $reason = McpHeader::checkAnnotations($this->inputSchema)) {
throw new InvalidArgumentException(\sprintf('Tool "%s" has an invalid "x-mcp-header" annotation: %s', $this->name, $reason));
}
}
/**
* @param ToolData|array<mixed> $data
*/
public static function fromArray(array $data): self
{
if (empty($data['name']) || !\is_string($data['name'])) {
throw new InvalidArgumentException('Invalid or missing "name" in Tool data.');
}
if (!isset($data['inputSchema']) || !\is_array($data['inputSchema'])) {
throw new InvalidArgumentException('Invalid or missing "inputSchema" in Tool data.');
}
if (!isset($data['inputSchema']['type']) || 'object' !== $data['inputSchema']['type']) {
throw new InvalidArgumentException('Tool inputSchema must be of type "object".');
}
$outputSchema = null;
if (isset($data['outputSchema']) && \is_array($data['outputSchema'])) {
$outputSchema = $data['outputSchema'];
}
return new self(
name: $data['name'],
title: isset($data['title']) && \is_string($data['title']) ? $data['title'] : null,
inputSchema: $data['inputSchema'],
description: isset($data['description']) && \is_string($data['description']) ? $data['description'] : null,
annotations: isset($data['annotations']) && \is_array($data['annotations']) ? ToolAnnotations::fromArray($data['annotations']) : null,
icons: isset($data['icons']) && \is_array($data['icons']) ? Icon::listFromArray($data['icons'], 'Tool') : null,
meta: isset($data['_meta']) && \is_array($data['_meta']) ? $data['_meta'] : null,
outputSchema: $outputSchema,
execution: isset($data['execution']) && \is_array($data['execution']) ? ToolExecution::fromArray($data['execution']) : null,
);
}
/**
* @return array{
* name: string,
* title?: string,
* inputSchema: ToolInputSchema,
* description?: string,
* annotations?: ToolAnnotations,
* icons?: Icon[],
* _meta?: array<string, mixed>,
* outputSchema?: ToolOutputSchema|\stdClass,
* execution?: ToolExecution
* }
*/
public function jsonSerialize(): array
{
$data = ['name' => $this->name];
if (null !== $this->title) {
$data['title'] = $this->title;
}
$data['inputSchema'] = $this->inputSchema;
if (null !== $this->description) {
$data['description'] = $this->description;
}
if (null !== $this->annotations) {
$data['annotations'] = $this->annotations;
}
if (null !== $this->icons) {
$data['icons'] = $this->icons;
}
if (null !== $this->meta) {
$data['_meta'] = $this->meta;
}
if (null !== $this->outputSchema) {
$data['outputSchema'] = [] === $this->outputSchema ? new \stdClass() : $this->outputSchema;
}
if (null !== $this->execution) {
$data['execution'] = $this->execution;
}
return $data;
}
/**
* Normalize an input schema and refuse members that are not what they claim.
*
* `fromArray()` feeds this untrusted wire data, so a member of the wrong
* type is rejected rather than replaced: quietly turning `properties: "x"`
* into `{}` would publish a tool contract nobody declared.
*
* @param array<string, mixed> $schema
*
* @return ToolInputSchema
*/
private static function normalizeInputSchema(array $schema): array
{
$normalized = self::normalizeSchema($schema);
if (!isset($normalized['type']) || 'object' !== $normalized['type']) {
throw new InvalidArgumentException('Tool inputSchema must be a JSON Schema of type "object".');
}
if (\array_key_exists('properties', $normalized)
&& !\is_array($normalized['properties'])
&& !$normalized['properties'] instanceof \stdClass
) {
throw new InvalidArgumentException('Tool inputSchema "properties" must be an object.');
}
if (\array_key_exists('required', $normalized)
&& null !== $normalized['required']
&& !\is_array($normalized['required'])
) {
throw new InvalidArgumentException('Tool inputSchema "required" must be a list of property names.');
}
return $normalized;
}
/**
* Normalize a JSON Schema so that empty sub-schemas JSON-encode as `{}` rather than `[]`.
*
* Once JSON is decoded into associative arrays, PHP cannot tell the empty object `{}`
* from the empty array `[]` — both are `[]`. Re-encoding then produces `[]`, which is
* invalid wherever a schema is expected (`properties`, `items`, `additionalProperties`,
* …), and strict clients reject it. Every empty sub-schema is therefore replaced with a
* `\stdClass` before serialization.
*
* The walk is recursive and covers the schema keywords of draft-07 through 2020-12, so
* nested object parameters, `$defs`, combinators, and `outputSchema` are all covered —
* not only the top-level `properties` map.
*
* @param array<string, mixed> $schema
*
* @return array<string, mixed>
*/
private static function normalizeSchema(array $schema): array
{
foreach (self::SUB_SCHEMA_KEYWORDS as $keyword) {
if (isset($schema[$keyword]) && \is_array($schema[$keyword])) {
$schema[$keyword] = self::normalizeSubSchema($schema[$keyword]);
}
}
foreach (self::SUB_SCHEMA_MAP_KEYWORDS as $keyword) {
if (!isset($schema[$keyword]) || !\is_array($schema[$keyword])) {
continue;
}
if ([] === $schema[$keyword]) {
$schema[$keyword] = new \stdClass();
continue;
}
foreach ($schema[$keyword] as $name => $subSchema) {
if (\is_array($subSchema)) {
$schema[$keyword][$name] = self::normalizeSubSchema($subSchema);
}
}
}
foreach (self::SUB_SCHEMA_LIST_KEYWORDS as $keyword) {
if (!isset($schema[$keyword]) || !\is_array($schema[$keyword])) {
continue;
}
// An empty list stays a list — `allOf: []` is already valid JSON.
foreach ($schema[$keyword] as $index => $subSchema) {
if (\is_array($subSchema)) {
$schema[$keyword][$index] = self::normalizeSubSchema($subSchema);
}
}
}
if (isset($schema['items']) && \is_array($schema['items'])) {
// `items` is a single sub-schema, or a list of them in draft-07 tuple form.
// An empty array is read as the empty schema `{}` — what an `items: {}` from
// SchemaGenerator decodes to — rather than as an empty tuple.
if ([] !== $schema['items'] && array_is_list($schema['items'])) {
foreach ($schema['items'] as $index => $itemSchema) {
if (\is_array($itemSchema)) {
$schema['items'][$index] = self::normalizeSubSchema($itemSchema);
}
}
} else {
$schema['items'] = self::normalizeSubSchema($schema['items']);
}
}
return $schema;
}
/**
* @param array<string, mixed> $schema
*
* @return array<string, mixed>|\stdClass
*/
private static function normalizeSubSchema(array $schema): array|\stdClass
{
return [] === $schema ? new \stdClass() : self::normalizeSchema($schema);
}
}