forked from php-mcp/server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRegisteredResource.php
More file actions
234 lines (194 loc) · 8.38 KB
/
RegisteredResource.php
File metadata and controls
234 lines (194 loc) · 8.38 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
<?php
declare(strict_types=1);
namespace PhpMcp\Server\Elements;
use PhpMcp\Schema\Content\BlobResourceContents;
use PhpMcp\Schema\Content\EmbeddedResource;
use PhpMcp\Schema\Content\ResourceContents;
use PhpMcp\Schema\Content\TextResourceContents;
use PhpMcp\Schema\Resource;
use PhpMcp\Server\Context;
use Psr\Container\ContainerInterface;
use Throwable;
class RegisteredResource extends RegisteredElement
{
public function __construct(
public readonly Resource $schema,
callable|array|string $handler,
bool $isManual = false,
) {
parent::__construct($handler, $isManual);
}
public static function make(Resource $schema, callable|array|string $handler, bool $isManual = false): self
{
return new self($schema, $handler, $isManual);
}
/**
* Reads the resource content.
*
* @return array<TextResourceContents|BlobResourceContents> Array of ResourceContents objects.
*/
public function read(ContainerInterface $container, string $uri, Context $context): array
{
$result = $this->handle($container, ['uri' => $uri], $context);
return $this->formatResult($result, $uri, $this->schema->mimeType);
}
/**
* Formats the raw result of a resource read operation into MCP ResourceContent items.
*
* @param mixed $readResult The raw result from the resource handler method.
* @param string $uri The URI of the resource that was read.
* @param ?string $mimeType The MIME type from the ResourceDefinition.
* @return array<TextResourceContents|BlobResourceContents> Array of ResourceContents objects.
*
* @throws \RuntimeException If the result cannot be formatted.
*
* Supported result types:
* - ResourceContent: Used as-is
* - EmbeddedResource: Resource is extracted from the EmbeddedResource
* - string: Converted to text content with guessed or provided MIME type
* - stream resource: Read and converted to blob with provided MIME type
* - array with 'blob' key: Used as blob content
* - array with 'text' key: Used as text content
* - SplFileInfo: Read and converted to blob
* - array: Converted to JSON if MIME type is application/json or contains 'json'
* For other MIME types, will try to convert to JSON with a warning
*/
protected function formatResult(mixed $readResult, string $uri, ?string $mimeType): array
{
if ($readResult instanceof ResourceContents) {
return [$readResult];
}
if ($readResult instanceof EmbeddedResource) {
return [$readResult->resource];
}
if (is_array($readResult)) {
if (empty($readResult)) {
return [TextResourceContents::make($uri, 'application/json', '[]')];
}
$allAreResourceContents = true;
$hasResourceContents = false;
$allAreEmbeddedResource = true;
$hasEmbeddedResource = false;
foreach ($readResult as $item) {
if ($item instanceof ResourceContents) {
$hasResourceContents = true;
$allAreEmbeddedResource = false;
} elseif ($item instanceof EmbeddedResource) {
$hasEmbeddedResource = true;
$allAreResourceContents = false;
} else {
$allAreResourceContents = false;
$allAreEmbeddedResource = false;
}
}
if ($allAreResourceContents && $hasResourceContents) {
return $readResult;
}
if ($allAreEmbeddedResource && $hasEmbeddedResource) {
return array_map(fn($item) => $item->resource, $readResult);
}
if ($hasResourceContents || $hasEmbeddedResource) {
$result = [];
foreach ($readResult as $item) {
if ($item instanceof ResourceContents) {
$result[] = $item;
} elseif ($item instanceof EmbeddedResource) {
$result[] = $item->resource;
} else {
$result = array_merge($result, $this->formatResult($item, $uri, $mimeType));
}
}
return $result;
}
}
if (is_string($readResult)) {
$mimeType = $mimeType ?? $this->guessMimeTypeFromString($readResult);
return [TextResourceContents::make($uri, $mimeType, $readResult)];
}
if (is_resource($readResult) && get_resource_type($readResult) === 'stream') {
$result = BlobResourceContents::fromStream(
$uri,
$readResult,
$mimeType ?? 'application/octet-stream'
);
@fclose($readResult);
return [$result];
}
if (is_array($readResult) && isset($readResult['blob']) && is_string($readResult['blob'])) {
$mimeType = $readResult['mimeType'] ?? $mimeType ?? 'application/octet-stream';
return [BlobResourceContents::make($uri, $mimeType, $readResult['blob'])];
}
if (is_array($readResult) && isset($readResult['text']) && is_string($readResult['text'])) {
$mimeType = $readResult['mimeType'] ?? $mimeType ?? 'text/plain';
return [TextResourceContents::make($uri, $mimeType, $readResult['text'])];
}
if ($readResult instanceof \SplFileInfo && $readResult->isFile() && $readResult->isReadable()) {
if ($mimeType && str_contains(strtolower($mimeType), 'text')) {
return [TextResourceContents::make($uri, $mimeType, file_get_contents($readResult->getPathname()))];
}
return [BlobResourceContents::fromSplFileInfo($uri, $readResult, $mimeType)];
}
if (is_array($readResult)) {
if ($mimeType && (str_contains(strtolower($mimeType), 'json') ||
$mimeType === 'application/json')) {
try {
$jsonString = json_encode($readResult, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT);
return [TextResourceContents::make($uri, $mimeType, $jsonString)];
} catch (\JsonException $e) {
throw new \RuntimeException("Failed to encode array as JSON for URI '{$uri}': {$e->getMessage()}");
}
}
try {
$jsonString = json_encode($readResult, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT);
$mimeType = $mimeType ?? 'application/json';
return [TextResourceContents::make($uri, $mimeType, $jsonString)];
} catch (\JsonException $e) {
throw new \RuntimeException("Failed to encode array as JSON for URI '{$uri}': {$e->getMessage()}");
}
}
throw new \RuntimeException("Cannot format resource read result for URI '{$uri}'. Handler method returned unhandled type: " . gettype($readResult));
}
/** Guesses MIME type from string content (very basic) */
private function guessMimeTypeFromString(string $content): string
{
$trimmed = ltrim($content);
if (str_starts_with($trimmed, '<') && str_ends_with(rtrim($content), '>')) {
if (str_contains($trimmed, '<html')) {
return 'text/html';
}
if (str_contains($trimmed, '<?xml')) {
return 'application/xml';
}
return 'text/plain';
}
if (str_starts_with($trimmed, '{') && str_ends_with(rtrim($content), '}')) {
return 'application/json';
}
if (str_starts_with($trimmed, '[') && str_ends_with(rtrim($content), ']')) {
return 'application/json';
}
return 'text/plain';
}
public function toArray(): array
{
return [
'schema' => $this->schema->toArray(),
...parent::toArray(),
];
}
public static function fromArray(array $data): self|false
{
try {
if (! isset($data['schema']) || ! isset($data['handler'])) {
return false;
}
return new self(
Resource::fromArray($data['schema']),
$data['handler'],
$data['isManual'] ?? false,
);
} catch (Throwable $e) {
return false;
}
}
}