From 58996eca2dd0455a10c8c4482fef0adbe896aac7 Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 19:53:25 +0100 Subject: [PATCH 001/181] Add a normalizer for optional nullable tool parameters --- src/Schema/SchemaNormalizer.php | 57 +++++++++++++++ .../TestCase/Schema/SchemaNormalizerTest.php | 70 +++++++++++++++++++ 2 files changed, 127 insertions(+) create mode 100644 src/Schema/SchemaNormalizer.php create mode 100644 tests/TestCase/Schema/SchemaNormalizerTest.php diff --git a/src/Schema/SchemaNormalizer.php b/src/Schema/SchemaNormalizer.php new file mode 100644 index 0000000..cfd2bb9 --- /dev/null +++ b/src/Schema/SchemaNormalizer.php @@ -0,0 +1,57 @@ + $inputSchema A tool input schema. + * @return array + */ + public static function normalize(array $inputSchema): array + { + $properties = $inputSchema['properties'] ?? null; + if (!is_array($properties) || $properties === []) { + return $inputSchema; + } + $required = is_array($inputSchema['required'] ?? null) ? $inputSchema['required'] : []; + + foreach ($properties as $name => $property) { + if (!is_array($property) || in_array($name, $required, true)) { + continue; + } + $properties[$name] = self::optional($property); + } + $inputSchema['properties'] = $properties; + + return $inputSchema; + } + + /** + * @param array $property The schema of an optional parameter. + * @return array + */ + private static function optional(array $property): array + { + if (is_array($property['type'] ?? null) && in_array('null', $property['type'], true)) { + $types = array_values(array_filter($property['type'], fn(mixed $type): bool => $type !== 'null')); + $property['type'] = count($types) === 1 ? $types[0] : $types; + } + if (is_array($property['enum'] ?? null) && in_array(null, $property['enum'], true)) { + $property['enum'] = array_values(array_filter($property['enum'], fn(mixed $value): bool => $value !== null)); + } + if (array_key_exists('default', $property) && $property['default'] === null) { + unset($property['default']); + } + + return $property; + } +} diff --git a/tests/TestCase/Schema/SchemaNormalizerTest.php b/tests/TestCase/Schema/SchemaNormalizerTest.php new file mode 100644 index 0000000..8ae2b13 --- /dev/null +++ b/tests/TestCase/Schema/SchemaNormalizerTest.php @@ -0,0 +1,70 @@ + 'object', 'properties' => [ + 'date_from' => ['type' => ['null', 'string'], 'description' => 'First day.', 'default' => null], + ]]); + + $this->assertSame(['type' => 'string', 'description' => 'First day.'], $out['properties']['date_from']); + } + + public function testRequiredNullableIsKept(): void + { + $schema = ['type' => 'object', 'properties' => ['x' => ['type' => ['null', 'string']]], 'required' => ['x']]; + + $this->assertSame($schema, SchemaNormalizer::normalize($schema)); + } + + public function testWiderUnionKeepsTheOtherTypes(): void + { + $out = SchemaNormalizer::normalize(['type' => 'object', 'properties' => [ + 'ref' => ['type' => ['null', 'string', 'integer'], 'default' => null], + ]]); + + $this->assertSame(['type' => ['string', 'integer']], $out['properties']['ref']); + } + + public function testNullableEnumLosesNull(): void + { + $out = SchemaNormalizer::normalize(['type' => 'object', 'properties' => [ + 'field' => ['type' => ['string', 'null'], 'enum' => ['signed', 'study', null], 'default' => null], + ]]); + + $this->assertSame(['type' => 'string', 'enum' => ['signed', 'study']], $out['properties']['field']); + } + + public function testSingleTypeWithNullDefaultLosesTheDefault(): void + { + $out = SchemaNormalizer::normalize(['type' => 'object', 'properties' => [ + 'date_from' => ['type' => 'string', 'format' => 'date', 'default' => null], + ]]); + + $this->assertSame(['type' => 'string', 'format' => 'date'], $out['properties']['date_from']); + } + + public function testRealDefaultsAreKept(): void + { + $schema = ['type' => 'object', 'properties' => ['field' => ['type' => 'string', 'default' => 'signed']]]; + + $this->assertSame($schema, SchemaNormalizer::normalize($schema)); + } + + public function testNoPropertiesIsLeftAlone(): void + { + $empty = ['type' => 'object', 'properties' => []]; + $this->assertSame($empty, SchemaNormalizer::normalize($empty)); + + $object = ['type' => 'object', 'properties' => new stdClass()]; + $this->assertSame($object, SchemaNormalizer::normalize($object)); + } +} From 197ff88bed53df7fd3fa2cf7406a49bb52ab5eee Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 19:53:36 +0100 Subject: [PATCH 002/181] Keep the normalizer within the line length --- src/Schema/SchemaNormalizer.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Schema/SchemaNormalizer.php b/src/Schema/SchemaNormalizer.php index cfd2bb9..9478ea2 100644 --- a/src/Schema/SchemaNormalizer.php +++ b/src/Schema/SchemaNormalizer.php @@ -46,7 +46,7 @@ private static function optional(array $property): array $property['type'] = count($types) === 1 ? $types[0] : $types; } if (is_array($property['enum'] ?? null) && in_array(null, $property['enum'], true)) { - $property['enum'] = array_values(array_filter($property['enum'], fn(mixed $value): bool => $value !== null)); + $property['enum'] = array_values(array_filter($property['enum'], fn(mixed $v): bool => $v !== null)); } if (array_key_exists('default', $property) && $property['default'] === null) { unset($property['default']); From c1e09f1230bdea3a60b6470c279540d5389ab92e Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 19:54:41 +0100 Subject: [PATCH 003/181] Add Mcp.schema.normalize to clean optional nullable parameters in tools/list --- docs/configuration.md | 1 + docs/tools.md | 44 ++++++++++++ src/Event/ToolSchemaNormalizer.php | 46 +++++++++++++ src/McpConfig.php | 1 + src/Server/ServerFactory.php | 5 ++ .../Event/ToolSchemaNormalizerTest.php | 53 +++++++++++++++ tests/TestCase/Server/SchemaNormalizeTest.php | 68 +++++++++++++++++++ tests/test_app/src/McpSchema/SchemaTools.php | 33 +++++++++ 8 files changed, 251 insertions(+) create mode 100644 src/Event/ToolSchemaNormalizer.php create mode 100644 tests/TestCase/Event/ToolSchemaNormalizerTest.php create mode 100644 tests/TestCase/Server/SchemaNormalizeTest.php create mode 100644 tests/test_app/src/McpSchema/SchemaTools.php diff --git a/docs/configuration.md b/docs/configuration.md index 2968dce..de13ccf 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -53,6 +53,7 @@ want to change; everything else keeps its default. These are the defaults - `discovery.scanDirs`: directories (relative to `ROOT`) scanned for attributes. Missing directories are skipped. - `discovery.excludeDirs`: directories to skip while scanning. - `discovery.cache`: name of the cache config for the discovery result. Set it to `null` or an empty string to disable the cache. +- `schema.normalize`: `true` simplifies the optional parameters in `tools/list`. Default `false`. The SDK describes `?string $from = null` as `"type": ["null", "string"]` with `"default": null`, and some hosts (Gemini-based ones, for example) reject type arrays. When it is on, an optional parameter loses `"null"` from its `type` and its `enum`, and a `default` of `null` is dropped. Required parameters do not change. Only the advertised list changes: arguments are still validated against the original schema, so a client that sends `null` keeps working. See [Input schemas](tools.md#input-schemas). - `session.cache`: name of the cache config that stores handshake-era sessions. - `session.ttl`: session lifetime in seconds. - `http.allowedHosts`: hosts accepted in the `Host` header (DNS-rebinding protection). `null` means the host of `App.fullBaseUrl` plus `localhost`, `127.0.0.1` and `[::1]`, which only protects when `App.fullBaseUrl` is set explicitly (the Cake 5 skeleton derives it from the request `Host` otherwise, and then every host is accepted). A list replaces that. Set it explicitly in production; it is required for servers with `identity.required` set to `false`. diff --git a/docs/tools.md b/docs/tools.md index c9c0446..eabf66b 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -19,6 +19,50 @@ use Mcp\Capability\Attribute\McpTool; The description comes from the method's docblock. The input schema is built from the parameter types, and `@param` lines become the parameter descriptions. +## Input schemas + +Clients show the input schema to the model, and some hosts reject schemas they +find ambiguous. A few habits keep it clean: + +- Describe every parameter in a `@param` line. A parameter without a + description leaves the model guessing. +- Write arrays as `int[]` or `array` in the docblock. The SDK does not + resolve `list` yet, so that form gives `"items": {}`, an array of + anything. +- Prefer `string $from = ''` to `?string $from = null` for an optional string. + The nullable form gives `"type": ["null", "string"]`, a type array that some + hosts (Gemini-based ones, for example) reject. +- Use `#[Schema]` (`Mcp\Capability\Attribute\Schema`) on a parameter for what a + PHP type cannot say: allowed values, a format, a range, or the type of the + items of an array. + +```php +use Mcp\Capability\Attribute\McpTool; +use Mcp\Capability\Attribute\Schema; + +/** + * Orders in a date range. + * + * @param string $from First day, YYYY-MM-DD. Empty: 30 days ago. + * @param string $status Order status. + * @param int[] $facilities Facility ids. Empty: all. + */ +#[McpTool(name: 'list_orders')] +public function list( + #[Schema(format: 'date')] string $from = '', + #[Schema(enum: ['open', 'closed'])] string $status = 'open', + array $facilities = [], +): array { + // ... +} +``` + +For existing tools written with nullable parameters, set +`Mcp.schema.normalize` to `true` (see [Configuration](configuration.md#keys)): +it removes the type arrays from `tools/list` without changing the code. +`bin/cake mcp check` lists the schemas that still have type arrays, untyped +arrays or parameters without a description. + ## Example returning structured data ```php diff --git a/src/Event/ToolSchemaNormalizer.php b/src/Event/ToolSchemaNormalizer.php new file mode 100644 index 0000000..363a78d --- /dev/null +++ b/src/Event/ToolSchemaNormalizer.php @@ -0,0 +1,46 @@ +getResponse(); + $result = $response->result; + if (!$result instanceof ListToolsResult) { + return; + } + + $tools = array_map(fn(Tool $tool): Tool => new Tool( + $tool->name, + $tool->title, + SchemaNormalizer::normalize($tool->inputSchema), + $tool->description, + $tool->annotations, + $tool->icons, + $tool->meta, + $tool->outputSchema, + $tool->execution, + ), $result->tools); + + $event->setResponse(new Response($response->getId(), new ListToolsResult($tools, $result->nextCursor))); + } +} diff --git a/src/McpConfig.php b/src/McpConfig.php index 7ec4dfa..d7b072b 100644 --- a/src/McpConfig.php +++ b/src/McpConfig.php @@ -39,6 +39,7 @@ final class McpConfig 'configure' => null, ], 'discovery' => ['scanDirs' => ['src/Mcp'], 'excludeDirs' => [], 'cache' => '_cake_mcp_'], + 'schema' => ['normalize' => false], 'session' => ['cache' => 'mcp_sessions', 'ttl' => 3600], 'http' => ['allowedHosts' => null, 'allowedOrigins' => [], 'maxBodyBytes' => 4 * 1024 * 1024], 'identity' => ['required' => true, 'attribute' => 'identity', 'scopes' => null], diff --git a/src/Server/ServerFactory.php b/src/Server/ServerFactory.php index 0d83df6..9eb6a00 100644 --- a/src/Server/ServerFactory.php +++ b/src/Server/ServerFactory.php @@ -14,6 +14,7 @@ use CakeDC\Mcp\Event\AuditListener; use CakeDC\Mcp\Event\EventDispatcher; use CakeDC\Mcp\Event\ToolListFilter; +use CakeDC\Mcp\Event\ToolSchemaNormalizer; use CakeDC\Mcp\Identity\CurrentIdentity; use CakeDC\Mcp\Log\McpLogger; use CakeDC\Mcp\McpConfig; @@ -79,6 +80,10 @@ private function build(bool $trusted, LoggerInterface $logger): Server $gate = new ToolGate($this->authorizer(), $this->identity, $trusted); $events = new EventDispatcher(); $events->listen(ResponseEvent::class, new ToolListFilter($gate)); + if (McpConfig::get('schema.normalize') === true) { + // After the filter, on the tools the caller may see. + $events->listen(ResponseEvent::class, new ToolSchemaNormalizer()); + } // The guard goes first: the SDK asks request handlers in the order they were added. $builder = Server::builder()->addRequestHandler(new ToolCallGuard($gate)); $audit = AuditSettings::fromConfig(); diff --git a/tests/TestCase/Event/ToolSchemaNormalizerTest.php b/tests/TestCase/Event/ToolSchemaNormalizerTest.php new file mode 100644 index 0000000..b1124a4 --- /dev/null +++ b/tests/TestCase/Event/ToolSchemaNormalizerTest.php @@ -0,0 +1,53 @@ + 'object', 'properties' => [ + 'date_from' => ['type' => ['null', 'string'], 'default' => null], + ]], 'desc', null, meta: ['ui' => ['visibility' => ['model']]]); + $event = $this->event(new Response(7, new ListToolsResult([$tool], 'cursor-2'))); + + (new ToolSchemaNormalizer())($event); + + $result = $event->getResponse()->result; + $this->assertInstanceOf(ListToolsResult::class, $result); + $this->assertSame(['type' => 'string'], $result->tools[0]->inputSchema['properties']['date_from']); + $this->assertSame(['ui' => ['visibility' => ['model']]], $result->tools[0]->meta); + $this->assertSame('Report', $result->tools[0]->title); + $this->assertSame('desc', $result->tools[0]->description); + $this->assertSame('cursor-2', $result->nextCursor); + $this->assertSame(7, $event->getResponse()->getId()); + } + + public function testLeavesOtherResponsesAlone(): void + { + $response = new Response(4, ['anything' => true]); + $event = $this->event($response); + + (new ToolSchemaNormalizer())($event); + + $this->assertSame($response, $event->getResponse()); + } + + /** + * @param \Mcp\Schema\JsonRpc\Response $response + */ + private function event(Response $response): ResponseEvent + { + return new ResponseEvent($response, (new ListToolsRequest())->withId(1), $this->createStub(SessionInterface::class)); + } +} diff --git a/tests/TestCase/Server/SchemaNormalizeTest.php b/tests/TestCase/Server/SchemaNormalizeTest.php new file mode 100644 index 0000000..b701743 --- /dev/null +++ b/tests/TestCase/Server/SchemaNormalizeTest.php @@ -0,0 +1,68 @@ + ArrayEngine::class]); + Configure::write('Mcp.discovery.scanDirs', ['src/McpSchema']); + } + + protected function tearDown(): void + { + Cache::drop('mcp_sessions'); + parent::tearDown(); + } + + public function testDefaultConfigKeepsTheUnion(): void + { + $tool = $this->reportTool(); + + $this->assertSame(['null', 'string'], $tool['inputSchema']['properties']['date_from']['type']); + } + + public function testNormalizeRemovesTheUnionFromTheList(): void + { + Configure::write('Mcp.schema.normalize', true); + + $tool = $this->reportTool(); + + $this->assertSame('string', $tool['inputSchema']['properties']['date_from']['type']); + $this->assertArrayNotHasKey('default', $tool['inputSchema']['properties']['date_from']); + } + + public function testANullArgumentIsStillAccepted(): void + { + Configure::write('Mcp.schema.normalize', true); + + $this->mcpCallTool('report', ['date_from' => null]); + + $this->assertMcpToolSucceeded(); + } + + /** + * @return array + */ + private function reportTool(): array + { + foreach ($this->mcpListTools() as $tool) { + if (($tool['name'] ?? null) === 'report') { + return $tool; + } + } + $this->fail('The report tool is not listed.'); + } +} diff --git a/tests/test_app/src/McpSchema/SchemaTools.php b/tests/test_app/src/McpSchema/SchemaTools.php new file mode 100644 index 0000000..deab355 --- /dev/null +++ b/tests/test_app/src/McpSchema/SchemaTools.php @@ -0,0 +1,33 @@ +, which the SDK does not resolve. Its own directory keeps it out of the tool + * lists of the other tests. + */ +class SchemaTools +{ + /** + * Builds a report. + * + * @param string|null $date_from First day. + * @param list $statuses Status ids. + * @param int[] $ids Ids. + * @param string $field Date field. + * @return array + */ + #[McpTool(name: 'report')] + public function report( + ?string $date_from = null, + array $statuses = [], + array $ids = [], + string $field = 'signed', + ): array { + return ['date_from' => $date_from]; + } +} From 52bdf93a08fd4b200971960940bc352f2d7ca16d Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 19:55:49 +0100 Subject: [PATCH 004/181] mcp check: warn about tool schemas strict hosts reject --- src/Command/McpCheckCommand.php | 41 +++++++++++++++++- src/Schema/SchemaLint.php | 42 +++++++++++++++++++ src/Server/ServerFactory.php | 21 ++++++++-- .../TestCase/Command/McpCheckCommandTest.php | 31 ++++++++++++++ tests/TestCase/Schema/SchemaLintTest.php | 38 +++++++++++++++++ 5 files changed, 167 insertions(+), 6 deletions(-) create mode 100644 src/Schema/SchemaLint.php create mode 100644 tests/TestCase/Schema/SchemaLintTest.php diff --git a/src/Command/McpCheckCommand.php b/src/Command/McpCheckCommand.php index a83a17b..f9ea621 100644 --- a/src/Command/McpCheckCommand.php +++ b/src/Command/McpCheckCommand.php @@ -32,6 +32,7 @@ use CakeDC\Mcp\McpConfig; use CakeDC\Mcp\OAuth\AuthSettings; use CakeDC\Mcp\OAuth\ResourceServer; +use CakeDC\Mcp\Schema\SchemaLint; use CakeDC\Mcp\Server\ServerFactory; use CakeDC\OAuthServer\Authenticator\TokenAuthenticator; use CakeDC\OAuthServer\OAuthServer; @@ -55,7 +56,7 @@ class McpCheckCommand extends Command private const LISTED_TOOLS = 10; /** - * @var list|null + * @var list>|null */ private ?array $tools = null; @@ -119,6 +120,7 @@ protected function checks(): array 'CSRF' => fn(): array => $this->csrf(), 'Authenticators' => fn(): array => $this->authenticators(), 'Tools' => fn(): array => $this->toolsCheck(), + 'Tool schemas' => fn(): array => $this->toolSchemas(), 'Authorizer' => fn(): array => $this->authorizerCheck(), 'Tool scopes' => fn(): array => $this->toolScopes(), 'Logging' => fn(): array => $this->logging(), @@ -137,11 +139,46 @@ private function factory(): ServerFactory /** * The tools the server offers, listed once per run. * + * @return list> + */ + private function toolDefinitions(): array + { + return $this->tools ??= $this->factory()->toolDefinitions(); + } + + /** * @return list */ private function toolNames(): array { - return $this->tools ??= $this->factory()->toolNames(); + return array_map(fn(array $tool): string => (string)$tool['name'], $this->toolDefinitions()); + } + + /** + * @return array{0: 'pass'|'warn'|'fail', 1: string} + */ + private function toolSchemas(): array + { + $tools = $this->toolDefinitions(); + if ($tools === []) { + return ['pass', 'no tools to check']; + } + $problems = []; + foreach ($tools as $tool) { + foreach (SchemaLint::problems($tool) as $problem) { + $problems[] = $tool['name'] . '.' . $problem; + } + } + if ($problems === []) { + return ['pass', sprintf('%d tools, no problems', count($tools))]; + } + + return ['warn', sprintf( + '%s. Some hosts reject type arrays and the model cannot tell what an untyped or undescribed ' + . 'parameter takes. See %s', + implode('; ', $problems), + self::DOCS . 'tools.md#input-schemas', + )]; } /** diff --git a/src/Schema/SchemaLint.php b/src/Schema/SchemaLint.php new file mode 100644 index 0000000..3cb5c48 --- /dev/null +++ b/src/Schema/SchemaLint.php @@ -0,0 +1,42 @@ + $tool One tool of a decoded `tools/list` result. + * @return list One message per problem, starting with the parameter name. + */ + public static function problems(array $tool): array + { + $schema = is_array($tool['inputSchema'] ?? null) ? $tool['inputSchema'] : []; + $properties = is_array($schema['properties'] ?? null) ? $schema['properties'] : []; + $required = is_array($schema['required'] ?? null) ? $schema['required'] : []; + + $problems = []; + foreach ($properties as $name => $property) { + if (!is_array($property)) { + continue; + } + $type = $property['type'] ?? null; + if (is_array($type)) { + $problems[] = sprintf('%s: type union %s', $name, implode('|', array_map('strval', $type))); + } + if ($type === 'array' && ($property['items'] ?? []) === []) { + $problems[] = sprintf('%s: array without item type', $name); + } + $description = $property['description'] ?? null; + if (!in_array($name, $required, true) && (!is_string($description) || trim($description) === '')) { + $problems[] = sprintf('%s: optional without a description', $name); + } + } + + return $problems; + } +} diff --git a/src/Server/ServerFactory.php b/src/Server/ServerFactory.php index 9eb6a00..1153325 100644 --- a/src/Server/ServerFactory.php +++ b/src/Server/ServerFactory.php @@ -196,7 +196,6 @@ private function existingDirs(array $dirs): array /** * The names of the tools the server offers, as a trusted client lists them (no authorizer, every page). - * Builds the server the same way the endpoint does, without network calls. * * @internal Used by `bin/cake mcp check`; not part of the public API. * @return list @@ -204,7 +203,21 @@ private function existingDirs(array $dirs): array */ public function toolNames(): array { - $names = []; + return array_map(fn(array $tool): string => $tool['name'], $this->toolDefinitions()); + } + + /** + * The tools the server offers, as a trusted client lists them (no authorizer, every page), decoded from JSON: + * the schemas as clients see them, after `Mcp.schema.normalize` when it is on. Builds the server the same way + * the endpoint does, without network calls. + * + * @internal Used by `bin/cake mcp check`; not part of the public API. + * @return list> Each tool has a string `name`. + * @throws \RuntimeException When the server cannot list its tools. + */ + public function toolDefinitions(): array + { + $tools = []; $cursor = null; for ($page = 0; $page < 100; $page++) { $list = ['jsonrpc' => '2.0', 'id' => 2, 'method' => 'tools/list']; @@ -240,7 +253,7 @@ public function log(mixed $level, string|Stringable $message, array $context = [ } foreach ($result['tools'] as $tool) { if (is_array($tool) && is_string($tool['name'] ?? null)) { - $names[] = $tool['name']; + $tools[] = $tool; } } $cursor = $result['nextCursor'] ?? null; @@ -249,7 +262,7 @@ public function log(mixed $level, string|Stringable $message, array $context = [ } } - return $names; + return $tools; } /** diff --git a/tests/TestCase/Command/McpCheckCommandTest.php b/tests/TestCase/Command/McpCheckCommandTest.php index 4490c91..76c1ac9 100644 --- a/tests/TestCase/Command/McpCheckCommandTest.php +++ b/tests/TestCase/Command/McpCheckCommandTest.php @@ -204,6 +204,37 @@ public function testToolsAreListed(): void $this->assertOutputRegExp('/\\[PASS\\] Tools: \\d+ tools: .*echo/'); } + public function testToolSchemasWarnAboutUnionsAndUntypedArrays(): void + { + Configure::write('Mcp.discovery.scanDirs', ['src/McpSchema']); + + $this->exec('mcp check'); + + $this->assertExitSuccess(); + $this->assertOutputContains('[WARN] Tool schemas: report.date_from: type union null|string'); + $this->assertOutputContains('report.statuses: array without item type'); + $this->assertOutputContains('tools.md#input-schemas'); + } + + public function testToolSchemasFollowTheNormalizer(): void + { + Configure::write('Mcp.discovery.scanDirs', ['src/McpSchema']); + Configure::write('Mcp.schema.normalize', true); + + $this->exec('mcp check'); + + $this->assertOutputNotContains('type union'); + } + + public function testToolSchemasWithoutToolsPass(): void + { + Configure::write('Mcp.discovery.scanDirs', ['src/NoTools']); + + $this->exec('mcp check'); + + $this->assertOutputContains('[PASS] Tool schemas: no tools to check'); + } + public function testNoToolFoundWarns(): void { Configure::write('Mcp.discovery.scanDirs', ['src/NoTools']); diff --git a/tests/TestCase/Schema/SchemaLintTest.php b/tests/TestCase/Schema/SchemaLintTest.php new file mode 100644 index 0000000..30dc07c --- /dev/null +++ b/tests/TestCase/Schema/SchemaLintTest.php @@ -0,0 +1,38 @@ + 'report', 'inputSchema' => ['type' => 'object', 'properties' => [ + 'date_from' => ['type' => ['null', 'string'], 'description' => 'First day.'], + 'statuses' => ['type' => 'array', 'items' => [], 'description' => 'Ids.'], + 'page' => ['type' => 'integer'], + ]]]); + + $this->assertSame([ + 'date_from: type union null|string', + 'statuses: array without item type', + 'page: optional without a description', + ], $problems); + } + + public function testCleanAndEmptySchemasHaveNoProblems(): void + { + $this->assertSame([], SchemaLint::problems([ + 'name' => 'a', + 'inputSchema' => ['type' => 'object', 'properties' => []], + ])); + $this->assertSame([], SchemaLint::problems(['name' => 'b', 'inputSchema' => [ + 'type' => 'object', + 'properties' => ['ids' => ['type' => 'array', 'items' => ['type' => 'integer']]], + 'required' => ['ids'], + ]])); + } +} From 4419febacba36367111847603a08563e612a659f Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 19:56:39 +0100 Subject: [PATCH 005/181] mcp check: fail when discovery is configured without symfony/finder --- docs/installation.md | 8 +++++ docs/troubleshooting.md | 7 ++-- src/Command/McpCheckCommand.php | 30 ++++++++++++++++ .../TestCase/Command/McpCheckCommandTest.php | 35 +++++++++++++++++++ 4 files changed, 77 insertions(+), 3 deletions(-) diff --git a/docs/installation.md b/docs/installation.md index 1d86c30..f6c06da 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -90,6 +90,14 @@ directories with `Mcp.discovery.scanDirs` (paths relative to `ROOT`). See If the directory does not exist yet, the endpoint still works and returns an empty tool list. +### Why symfony/finder is required + +The plugin's own code does not use `symfony/finder`, but the SDK's attribute +discovery does, and the SDK only suggests it. Without it the SDK logs a warning, +skips discovery, and the server offers no tools at all. That is why the plugin +requires it. `bin/cake mcp check` fails on its `Discovery` line when +`Mcp.discovery.scanDirs` is set and `symfony/finder` cannot be loaded. + ## After deploying new tools Outside debug mode the discovery result is cached in the `_cake_mcp_` cache diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index f401310..aecac9c 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -9,9 +9,10 @@ them without a network call. ## The tool list is empty -Run `bin/cake mcp check` first: its `Tools` line lists the tools the server -offers, and its `Authorizer` line says when `RbacToolAuthorizer` has no rule -that lets anyone call them. Other causes: +Run `bin/cake mcp check` first: its `Discovery` line fails when +`symfony/finder` is missing (the SDK then skips discovery), its `Tools` line +lists the tools the server offers, and its `Authorizer` line says when +`RbacToolAuthorizer` has no rule that lets anyone call them. Other causes: - A class in a scan directory fails to load (a syntax error, a missing parent class or interface). The SDK silently skips discovery and returns diff --git a/src/Command/McpCheckCommand.php b/src/Command/McpCheckCommand.php index f9ea621..3bfdb60 100644 --- a/src/Command/McpCheckCommand.php +++ b/src/Command/McpCheckCommand.php @@ -37,6 +37,7 @@ use CakeDC\OAuthServer\Authenticator\TokenAuthenticator; use CakeDC\OAuthServer\OAuthServer; use ReflectionProperty; +use Symfony\Component\Finder\Finder; use Throwable; /** @@ -119,6 +120,7 @@ protected function checks(): array 'Allowed hosts' => fn(): array => $this->hosts(), 'CSRF' => fn(): array => $this->csrf(), 'Authenticators' => fn(): array => $this->authenticators(), + 'Discovery' => fn(): array => $this->discovery(), 'Tools' => fn(): array => $this->toolsCheck(), 'Tool schemas' => fn(): array => $this->toolSchemas(), 'Authorizer' => fn(): array => $this->authorizerCheck(), @@ -726,6 +728,34 @@ protected function oauthServerInstalled(): bool return class_exists(OAuthServer::class); } + /** + * Whether symfony/finder is installed: the SDK's attribute discovery needs it, and without it the SDK skips + * discovery with only a log warning. + * + * @return bool + */ + protected function finderAvailable(): bool + { + return class_exists(Finder::class); + } + + /** + * @return array{0: 'pass'|'warn'|'fail', 1: string} + */ + private function discovery(): array + { + $dirs = array_values(array_filter((array)McpConfig::get('discovery.scanDirs'), 'is_string')); + if ($dirs === []) { + return ['pass', 'off (no Mcp.discovery.scanDirs)']; + } + if (!$this->finderAvailable()) { + return ['fail', 'Mcp.discovery.scanDirs is set but symfony/finder is not installed, so the SDK skips ' + . 'discovery and the server has no tools. Run: composer require symfony/finder']; + } + + return ['pass', 'scans ' . implode(', ', $dirs)]; + } + /** * The host application, without replacing the running plugin collection; or why it cannot be built. * diff --git a/tests/TestCase/Command/McpCheckCommandTest.php b/tests/TestCase/Command/McpCheckCommandTest.php index 76c1ac9..6c9d94b 100644 --- a/tests/TestCase/Command/McpCheckCommandTest.php +++ b/tests/TestCase/Command/McpCheckCommandTest.php @@ -521,6 +521,41 @@ public function testAnAuthenticatorThatLeavesTheMcpEndpointAlonePasses(): void $this->assertOutputContains('[PASS] Authenticators'); } + public function testDiscoveryPassesWithFinder(): void + { + $this->exec('mcp check'); + + $this->assertOutputContains('[PASS] Discovery: scans src/Mcp'); + } + + public function testDiscoveryIsOffWithoutScanDirs(): void + { + Configure::write('Mcp.discovery.scanDirs', []); + + $this->exec('mcp check'); + + $this->assertOutputContains('[PASS] Discovery: off (no Mcp.discovery.scanDirs)'); + } + + public function testDiscoveryFailsWithoutFinder(): void + { + $out = new StubConsoleOutput(); + $command = new class extends McpCheckCommand { + protected function finderAvailable(): bool + { + return false; + } + }; + + $code = $command->run([], new ConsoleIo($out, new StubConsoleOutput(), new StubConsoleInput([]))); + + $this->assertSame(McpCheckCommand::CODE_ERROR, $code); + $this->assertStringContainsString( + '[FAIL] Discovery: Mcp.discovery.scanDirs is set but symfony/finder is not installed', + $out->output(), + ); + } + public function testMissingOAuthPluginFailsWithTheInstallHint(): void { Configure::write('Mcp.auth', OAuthTestConfig::MCP_AUTH); From c43a8b5a847c93538dd1936c75ef625db3c1eb62 Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 19:57:03 +0100 Subject: [PATCH 006/181] Changelog: schema defaults and checks --- CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6523067..ab16557 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## Unreleased + +- `Mcp.schema.normalize`, off by default: when on, `tools/list` drops `"null"` from the `type` and `enum` of optional parameters and their `default` of `null`, for hosts that reject type arrays. Arguments are still validated against the original schema. See Input schemas in `docs/tools.md`. +- `bin/cake mcp check` warns, on a new `Tool schemas` line, about type arrays, arrays without an item type and optional parameters without a description. +- `bin/cake mcp check` fails, on a new `Discovery` line, when `Mcp.discovery.scanDirs` is set and `symfony/finder` is missing: the SDK then skips discovery and the server has no tools. +- Docs: Input schemas in `docs/tools.md` (`int[]` rather than `list`, `#[Schema]`, optional strings), and why `symfony/finder` is required in `docs/installation.md`. + ## 2.1.1 (2026-11-07) - `bin/cake mcp check` lists the tools the server offers and warns when there is none. From c716b17ec15cc76013ceda0834890c9021ce479b Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 20:03:06 +0100 Subject: [PATCH 007/181] Keep null in nullable parameters whose default is another value --- CHANGELOG.md | 2 +- docs/configuration.md | 2 +- src/Schema/SchemaNormalizer.php | 10 ++++++---- tests/TestCase/Schema/SchemaNormalizerTest.php | 10 ++++++++++ 4 files changed, 18 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ab16557..4c51048 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- `Mcp.schema.normalize`, off by default: when on, `tools/list` drops `"null"` from the `type` and `enum` of optional parameters and their `default` of `null`, for hosts that reject type arrays. Arguments are still validated against the original schema. See Input schemas in `docs/tools.md`. +- `Mcp.schema.normalize`, off by default: when on, `tools/list` drops `"null"` from the `type` and `enum` of optional parameters whose default is `null`, and that default, for hosts that reject type arrays. Arguments are still validated against the original schema. See Input schemas in `docs/tools.md`. - `bin/cake mcp check` warns, on a new `Tool schemas` line, about type arrays, arrays without an item type and optional parameters without a description. - `bin/cake mcp check` fails, on a new `Discovery` line, when `Mcp.discovery.scanDirs` is set and `symfony/finder` is missing: the SDK then skips discovery and the server has no tools. - Docs: Input schemas in `docs/tools.md` (`int[]` rather than `list`, `#[Schema]`, optional strings), and why `symfony/finder` is required in `docs/installation.md`. diff --git a/docs/configuration.md b/docs/configuration.md index de13ccf..42075bb 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -53,7 +53,7 @@ want to change; everything else keeps its default. These are the defaults - `discovery.scanDirs`: directories (relative to `ROOT`) scanned for attributes. Missing directories are skipped. - `discovery.excludeDirs`: directories to skip while scanning. - `discovery.cache`: name of the cache config for the discovery result. Set it to `null` or an empty string to disable the cache. -- `schema.normalize`: `true` simplifies the optional parameters in `tools/list`. Default `false`. The SDK describes `?string $from = null` as `"type": ["null", "string"]` with `"default": null`, and some hosts (Gemini-based ones, for example) reject type arrays. When it is on, an optional parameter loses `"null"` from its `type` and its `enum`, and a `default` of `null` is dropped. Required parameters do not change. Only the advertised list changes: arguments are still validated against the original schema, so a client that sends `null` keeps working. See [Input schemas](tools.md#input-schemas). +- `schema.normalize`: `true` simplifies the optional parameters in `tools/list`. Default `false`. The SDK describes `?string $from = null` as `"type": ["null", "string"]` with `"default": null`, and some hosts (Gemini-based ones, for example) reject type arrays. When it is on, an optional parameter whose default is `null` loses `"null"` from its `type` and its `enum`, and that `default` is dropped. Required parameters and nullable ones with another default do not change. Only the advertised list changes: arguments are still validated against the original schema, so a client that sends `null` keeps working. See [Input schemas](tools.md#input-schemas). - `session.cache`: name of the cache config that stores handshake-era sessions. - `session.ttl`: session lifetime in seconds. - `http.allowedHosts`: hosts accepted in the `Host` header (DNS-rebinding protection). `null` means the host of `App.fullBaseUrl` plus `localhost`, `127.0.0.1` and `[::1]`, which only protects when `App.fullBaseUrl` is set explicitly (the Cake 5 skeleton derives it from the request `Host` otherwise, and then every host is accepted). A list replaces that. Set it explicitly in production; it is required for servers with `identity.required` set to `false`. diff --git a/src/Schema/SchemaNormalizer.php b/src/Schema/SchemaNormalizer.php index 9478ea2..92902fc 100644 --- a/src/Schema/SchemaNormalizer.php +++ b/src/Schema/SchemaNormalizer.php @@ -6,9 +6,11 @@ /** * Simplifies the optional parameters of a tool input schema, for hosts that reject type arrays. * - * Only top-level properties that are not required change: `"null"` leaves a `type` list (a single type left - * becomes a plain string), `null` leaves an `enum`, and a `default` of `null` is dropped. Leaving out an optional - * argument already means "no value", so the advertised schema loses nothing a client needs. + * Only top-level properties that are not required and whose default is `null` (or absent) change: `"null"` leaves + * a `type` list (a single type left becomes a plain string), `null` leaves an `enum`, and the `default` of `null` is + * dropped. Leaving out such an argument already gives `null`, so the advertised schema loses nothing a client needs. + * A nullable parameter with another default (`?string $status = 'open'`) keeps its union: there `null` is a value + * of its own, and `bin/cake mcp check` keeps reporting it. */ final class SchemaNormalizer { @@ -25,7 +27,7 @@ public static function normalize(array $inputSchema): array $required = is_array($inputSchema['required'] ?? null) ? $inputSchema['required'] : []; foreach ($properties as $name => $property) { - if (!is_array($property) || in_array($name, $required, true)) { + if (!is_array($property) || in_array($name, $required, true) || ($property['default'] ?? null) !== null) { continue; } $properties[$name] = self::optional($property); diff --git a/tests/TestCase/Schema/SchemaNormalizerTest.php b/tests/TestCase/Schema/SchemaNormalizerTest.php index 8ae2b13..4e0dfa8 100644 --- a/tests/TestCase/Schema/SchemaNormalizerTest.php +++ b/tests/TestCase/Schema/SchemaNormalizerTest.php @@ -52,6 +52,16 @@ public function testSingleTypeWithNullDefaultLosesTheDefault(): void $this->assertSame(['type' => 'string', 'format' => 'date'], $out['properties']['date_from']); } + public function testNullableWithARealDefaultKeepsNull(): void + { + // ?string $status = 'open', where null means "any status": null stays a value the client can send. + $schema = ['type' => 'object', 'properties' => [ + 'status' => ['type' => ['null', 'string'], 'enum' => ['open', 'closed', null], 'default' => 'open'], + ]]; + + $this->assertSame($schema, SchemaNormalizer::normalize($schema)); + } + public function testRealDefaultsAreKept(): void { $schema = ['type' => 'object', 'properties' => ['field' => ['type' => 'string', 'default' => 'signed']]]; From 1b2e829d51e2aca55c2497000135553a36a2295d Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 20:03:06 +0100 Subject: [PATCH 008/181] Docs: an input schema example whose defaults the schema accepts --- docs/tools.md | 30 ++++++--- .../Server/DocumentedSchemaExampleTest.php | 67 +++++++++++++++++++ tests/test_app/src/McpDocs/OrderTools.php | 32 +++++++++ 3 files changed, 118 insertions(+), 11 deletions(-) create mode 100644 tests/TestCase/Server/DocumentedSchemaExampleTest.php create mode 100644 tests/test_app/src/McpDocs/OrderTools.php diff --git a/docs/tools.md b/docs/tools.md index eabf66b..9b7f913 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -29,12 +29,19 @@ find ambiguous. A few habits keep it clean: - Write arrays as `int[]` or `array` in the docblock. The SDK does not resolve `list` yet, so that form gives `"items": {}`, an array of anything. -- Prefer `string $from = ''` to `?string $from = null` for an optional string. - The nullable form gives `"type": ["null", "string"]`, a type array that some - hosts (Gemini-based ones, for example) reject. - Use `#[Schema]` (`Mcp\Capability\Attribute\Schema`) on a parameter for what a PHP type cannot say: allowed values, a format, a range, or the type of the items of an array. +- Give an optional parameter a default the schema accepts, because the model may + send it back. A free-text string can default to `''`. A string with a format + or allowed values cannot: `''` is not a date, so a model that sends it gets an + error. Make it nullable instead (`?string $from = null`) and say in its + description what leaving it out does, or default to one of the allowed values. +- The nullable form gives `"type": ["null", "string"]`, a type array that some + hosts (Gemini-based ones, for example) reject. Set `Mcp.schema.normalize` to + `true` (see [Configuration](configuration.md#keys)) to advertise those + parameters as plain `"string"` without a default: the model leaves them out, + and a client that still sends `null` keeps working. ```php use Mcp\Capability\Attribute\McpTool; @@ -43,13 +50,13 @@ use Mcp\Capability\Attribute\Schema; /** * Orders in a date range. * - * @param string $from First day, YYYY-MM-DD. Empty: 30 days ago. + * @param string|null $from First day, YYYY-MM-DD. Leave it out for 30 days ago. * @param string $status Order status. - * @param int[] $facilities Facility ids. Empty: all. + * @param int[] $facilities Facility ids. Leave it out for all. */ #[McpTool(name: 'list_orders')] public function list( - #[Schema(format: 'date')] string $from = '', + #[Schema(format: 'date')] ?string $from = null, #[Schema(enum: ['open', 'closed'])] string $status = 'open', array $facilities = [], ): array { @@ -57,11 +64,12 @@ public function list( } ``` -For existing tools written with nullable parameters, set -`Mcp.schema.normalize` to `true` (see [Configuration](configuration.md#keys)): -it removes the type arrays from `tools/list` without changing the code. -`bin/cake mcp check` lists the schemas that still have type arrays, untyped -arrays or parameters without a description. +`Mcp.schema.normalize` only changes optional parameters whose default is +`null`: it removes `null` from their types. A required nullable parameter, a +nullable one with another default (`?string $status = 'open'`, where `null` is a +value of its own) and a wider union (`int|string`) keep their type arrays. +`bin/cake mcp check` lists what is left: type arrays, untyped arrays and +parameters without a description. ## Example returning structured data diff --git a/tests/TestCase/Server/DocumentedSchemaExampleTest.php b/tests/TestCase/Server/DocumentedSchemaExampleTest.php new file mode 100644 index 0000000..fbfc30f --- /dev/null +++ b/tests/TestCase/Server/DocumentedSchemaExampleTest.php @@ -0,0 +1,67 @@ + ArrayEngine::class]); + Configure::write('Mcp.discovery.scanDirs', ['src/McpDocs']); + Configure::write('Mcp.schema.normalize', true); + } + + protected function tearDown(): void + { + Cache::drop('mcp_sessions'); + parent::tearDown(); + } + + public function testEveryAdvertisedDefaultIsAccepted(): void + { + $properties = $this->tool('list_orders')['inputSchema']['properties']; + foreach ($properties as $name => $property) { + if (!array_key_exists('default', $property)) { + continue; + } + + $this->mcpCallTool('list_orders', [$name => $property['default']]); + + $this->assertMcpToolSucceeded(sprintf('Sending the advertised default of "%s" fails.', $name)); + } + } + + public function testLeavingEveryArgumentOutWorks(): void + { + $this->mcpCallTool('list_orders'); + + $this->assertMcpToolSucceeded(); + } + + /** + * @return array + */ + private function tool(string $name): array + { + foreach ($this->mcpListTools() as $tool) { + if (($tool['name'] ?? null) === $name) { + return $tool; + } + } + $this->fail(sprintf('The %s tool is not listed.', $name)); + } +} diff --git a/tests/test_app/src/McpDocs/OrderTools.php b/tests/test_app/src/McpDocs/OrderTools.php new file mode 100644 index 0000000..533532c --- /dev/null +++ b/tests/test_app/src/McpDocs/OrderTools.php @@ -0,0 +1,32 @@ + + */ + #[McpTool(name: 'list_orders')] + public function list( + #[Schema(format: 'date')] + ?string $from = null, + #[Schema(enum: ['open', 'closed'])] + string $status = 'open', + array $facilities = [], + ): array { + return ['from' => $from, 'status' => $status]; + } +} From e6fbf7b13aff2bc9a629075a881abaff736edd8f Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 20:18:00 +0100 Subject: [PATCH 009/181] Add ToolError::message() for errors the model should read --- src/Tool/ToolError.php | 11 +++++++++++ tests/TestCase/Tool/ToolErrorTest.php | 9 +++++++++ 2 files changed, 20 insertions(+) diff --git a/src/Tool/ToolError.php b/src/Tool/ToolError.php index 44f1b88..5802105 100644 --- a/src/Tool/ToolError.php +++ b/src/Tool/ToolError.php @@ -15,6 +15,17 @@ */ final class ToolError { + /** + * An error whose message the model reads as it is, for example "Order "A-1042" does not exist.". + * + * @param string $message What went wrong, written so the model can act on it. + * @return \Mcp\Exception\ToolCallException + */ + public static function message(string $message): ToolCallException + { + return new ToolCallException($message); + } + /** * A validation failure, one line per field. * diff --git a/tests/TestCase/Tool/ToolErrorTest.php b/tests/TestCase/Tool/ToolErrorTest.php index e3746af..9e414a1 100644 --- a/tests/TestCase/Tool/ToolErrorTest.php +++ b/tests/TestCase/Tool/ToolErrorTest.php @@ -6,6 +6,7 @@ use Cake\ORM\Entity; use Cake\TestSuite\TestCase; use CakeDC\Mcp\Tool\ToolError; +use Mcp\Exception\ToolCallException; class ToolErrorTest extends TestCase { @@ -64,6 +65,14 @@ public function testMessageWithoutAFieldIsListedAlone(): void $this->assertSame("The data is invalid.\n- Something is off", ToolError::invalid(['Something is off'])->getMessage()); } + public function testMessageIsSentAsItIs(): void + { + $exception = ToolError::message('Order "A-1" does not exist.'); + + $this->assertInstanceOf(ToolCallException::class, $exception); + $this->assertSame('Order "A-1" does not exist.', $exception->getMessage()); + } + public function testNoErrorsLeavesOnlyTheFirstLine(): void { $this->assertSame('The data is invalid.', ToolError::invalid([])->getMessage()); From 920323344e91c209810fbf535307124bc2e5843e Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 20:19:07 +0100 Subject: [PATCH 010/181] Docs: what a client receives from a tool, pinned by tests --- docs/tools.md | 64 ++++++++++- .../TestCase/Server/DocumentedResultsTest.php | 103 ++++++++++++++++++ tests/test_app/src/McpDocs/ResultTools.php | 89 +++++++++++++++ 3 files changed, 251 insertions(+), 5 deletions(-) create mode 100644 tests/TestCase/Server/DocumentedResultsTest.php create mode 100644 tests/test_app/src/McpDocs/ResultTools.php diff --git a/docs/tools.md b/docs/tools.md index 9b7f913..cd0c722 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -71,7 +71,18 @@ value of its own) and a wider union (`int|string`) keep their type arrays. `bin/cake mcp check` lists what is left: type arrays, untyped arrays and parameters without a description. -## Example returning structured data +## Results + +What a tool returns decides what the client receives: + +| The tool returns | The client receives | +|---|---| +| a string | that text | +| an associative array | the array as pretty-printed JSON text, and the same array as `structuredContent` | +| a list (`['A-1', 'A-2']`) | the list as pretty-printed JSON text, without `structuredContent` | +| a `Mcp\Schema\Result\CallToolResult` | exactly its content and `structuredContent` | + +An associative array is the quickest way to return data: ```php namespace App\Mcp; @@ -103,6 +114,47 @@ class OrderTools } ``` +The array travels twice, as text and as `structuredContent`, and the model may +read both. That is fine for a small result. For a large one, return a single +compact JSON text instead, so the model reads it once: + +```php +use Mcp\Schema\Content\TextContent; +use Mcp\Schema\Result\CallToolResult; + +return new CallToolResult([ + new TextContent(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)), +]); +``` + +### Output schemas + +When a client parses the result (an agent framework, a script, a client that +shows it as a table), declare its shape with `outputSchema` and return a +`CallToolResult` with a short text for the model and the data as +`structuredContent`: + +```php +#[McpTool(name: 'order_summary', outputSchema: [ + 'type' => 'object', + 'properties' => ['total' => ['type' => 'number'], 'count' => ['type' => 'integer']], + 'required' => ['total'], +])] +public function summary(): CallToolResult +{ + return new CallToolResult( + [new TextContent('2 open orders, 25.50 in total.')], + false, + ['total' => 25.5, 'count' => 2], + ); +} +``` + +`tools/list` shows the `outputSchema`, and the SDK checks the +`structuredContent` against it: a result that breaks it reaches the client as a +tool error ("Invalid structured output for tool ..."), not as data. Test the +tool's result with `assertMcpStructuredContent()` (see [Testing](testing.md)). + ## Annotations Annotations tell the client how a tool behaves. Clients such as Claude use them @@ -200,18 +252,20 @@ If a tool throws an unexpected exception, the client receives a JSON-RPC message never reaches the client, so internals do not leak. With the stateless 2026-07-28 protocol revision the SDK answers that error with HTTP 400. -To return a message to the client on purpose, throw -`Mcp\Exception\ToolCallException`: +To return a message to the client on purpose, throw the exception that +`CakeDC\Mcp\Tool\ToolError::message()` builds (a +`Mcp\Exception\ToolCallException`). The model reads the message and can try +again: ```php -use Mcp\Exception\ToolCallException; +use CakeDC\Mcp\Tool\ToolError; #[McpTool(name: 'cancel_order')] public function cancel(string $number): string { $order = $this->fetchTable('Orders')->find()->where(['number' => $number])->first(); if ($order === null) { - throw new ToolCallException(sprintf('Order "%s" does not exist.', $number)); + throw ToolError::message(sprintf('Order "%s" does not exist.', $number)); } return 'Cancelled.'; diff --git a/tests/TestCase/Server/DocumentedResultsTest.php b/tests/TestCase/Server/DocumentedResultsTest.php new file mode 100644 index 0000000..4b31758 --- /dev/null +++ b/tests/TestCase/Server/DocumentedResultsTest.php @@ -0,0 +1,103 @@ + ArrayEngine::class]); + Configure::write('Mcp.discovery.scanDirs', ['src/McpDocs']); + } + + protected function tearDown(): void + { + Cache::drop('mcp_sessions'); + parent::tearDown(); + } + + public function testAnArrayIsSentAsTextAndStructuredContent(): void + { + $this->mcpCallTool('find_order', ['number' => 'A-1']); + + $expected = ['number' => 'A-1', 'status' => 'open', 'total' => 12.5]; + $this->assertMcpToolSucceeded(); + $this->assertSame(json_encode($expected, JSON_PRETTY_PRINT), $this->mcpResultText()); + $this->assertSame($expected, $this->mcpResult()['structuredContent']); + } + + public function testAListIsSentAsTextOnly(): void + { + $this->mcpCallTool('order_numbers'); + + $this->assertMcpToolSucceeded(); + $this->assertSame(json_encode(['A-1', 'A-2'], JSON_PRETTY_PRINT), $this->mcpResultText()); + $this->assertArrayNotHasKey('structuredContent', $this->mcpResult()); + } + + public function testAStringIsSentAsTextOnly(): void + { + $this->mcpCallTool('order_status', ['number' => 'A-1']); + + $this->assertMcpToolSucceeded(); + $this->assertSame('open', $this->mcpResultText()); + $this->assertArrayNotHasKey('structuredContent', $this->mcpResult()); + } + + public function testOutputSchemaIsListedAndStructuredContentSent(): void + { + $tool = $this->tool('order_summary'); + $this->assertSame(['total'], $tool['outputSchema']['required']); + + $this->mcpCallTool('order_summary'); + + $this->assertMcpToolSucceeded(); + $this->assertSame('2 open orders, 25.50 in total.', $this->mcpResultText()); + $this->assertMcpStructuredContent(['total' => 25.5, 'count' => 2]); + } + + public function testACompactResultIsOneLineOfJson(): void + { + $this->mcpCallTool('orders_compact'); + + $this->assertMcpToolSucceeded(); + $this->assertStringNotContainsString("\n", $this->mcpResultText()); + $this->assertArrayNotHasKey('structuredContent', $this->mcpResult()); + } + + public function testStructuredContentThatBreaksTheOutputSchemaIsAToolError(): void + { + $this->mcpCallTool('bad_summary'); + + $this->assertMcpToolError(); + $this->assertMcpResultContains('Invalid structured output'); + } + + /** + * @return array + */ + private function tool(string $name): array + { + foreach ($this->mcpListTools() as $tool) { + if (($tool['name'] ?? null) === $name) { + return $tool; + } + } + $this->fail(sprintf('The %s tool is not listed.', $name)); + } +} diff --git a/tests/test_app/src/McpDocs/ResultTools.php b/tests/test_app/src/McpDocs/ResultTools.php new file mode 100644 index 0000000..6e6d516 --- /dev/null +++ b/tests/test_app/src/McpDocs/ResultTools.php @@ -0,0 +1,89 @@ + 'object', + 'properties' => ['total' => ['type' => 'number'], 'count' => ['type' => 'integer']], + 'required' => ['total'], + ]; + + /** + * Finds an order by its number. + * + * @param string $number The order number. + * @return array + */ + #[McpTool(name: 'find_order')] + public function find(string $number): array + { + return ['number' => $number, 'status' => 'open', 'total' => 12.5]; + } + + /** + * The numbers of the open orders. + * + * @return list + */ + #[McpTool(name: 'order_numbers')] + public function numbers(): array + { + return ['A-1', 'A-2']; + } + + /** + * The status of an order. + * + * @param string $number The order number. + */ + #[McpTool(name: 'order_status')] + public function status(string $number): string + { + return 'open'; + } + + /** + * Totals of the open orders. + */ + #[McpTool(name: 'order_summary', outputSchema: self::SUMMARY_SCHEMA)] + public function summary(): CallToolResult + { + return new CallToolResult( + [new TextContent('2 open orders, 25.50 in total.')], + false, + ['total' => 25.5, 'count' => 2], + ); + } + + /** + * The open orders, as one compact JSON text. + */ + #[McpTool(name: 'orders_compact')] + public function compact(): CallToolResult + { + $data = ['orders' => [['number' => 'A-1', 'total' => 12.5], ['number' => 'A-2', 'total' => 12.5]]]; + + return new CallToolResult([ + new TextContent(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)), + ]); + } + + /** + * A summary that breaks its own output schema (no total). + */ + #[McpTool(name: 'bad_summary', outputSchema: self::SUMMARY_SCHEMA)] + public function bad(): CallToolResult + { + return new CallToolResult([new TextContent('2 open orders.')], false, ['count' => 2]); + } +} From 325db340e0a7209446ce95e047977e51aac39f46 Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 20:19:22 +0100 Subject: [PATCH 011/181] Changelog: results docs and ToolError::message() --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c51048..6df3d5c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ - `Mcp.schema.normalize`, off by default: when on, `tools/list` drops `"null"` from the `type` and `enum` of optional parameters whose default is `null`, and that default, for hosts that reject type arrays. Arguments are still validated against the original schema. See Input schemas in `docs/tools.md`. - `bin/cake mcp check` warns, on a new `Tool schemas` line, about type arrays, arrays without an item type and optional parameters without a description. - `bin/cake mcp check` fails, on a new `Discovery` line, when `Mcp.discovery.scanDirs` is set and `symfony/finder` is missing: the SDK then skips discovery and the server has no tools. +- `ToolError::message()` builds the error a tool throws to send the model a message it can act on. +- Docs: Results in `docs/tools.md`: what a string, an array, a list and a `CallToolResult` become, `outputSchema` and `structuredContent`, and a compact JSON text for large results. - Docs: Input schemas in `docs/tools.md` (`int[]` rather than `list`, `#[Schema]`, optional strings), and why `symfony/finder` is required in `docs/installation.md`. ## 2.1.1 (2026-11-07) From f058bdb9ef717b5e250c9b71310911ae79a51378 Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 20:20:49 +0100 Subject: [PATCH 012/181] Add CacheHints to read Mcp.server.cache --- src/Server/CacheHints.php | 66 ++++++++++++++++++++++++ tests/TestCase/Server/CacheHintsTest.php | 63 ++++++++++++++++++++++ 2 files changed, 129 insertions(+) create mode 100644 src/Server/CacheHints.php create mode 100644 tests/TestCase/Server/CacheHintsTest.php diff --git a/src/Server/CacheHints.php b/src/Server/CacheHints.php new file mode 100644 index 0000000..cc5a34b --- /dev/null +++ b/src/Server/CacheHints.php @@ -0,0 +1,66 @@ + ms, 'scope' => 'public'|'private', 'methods' => [method => [...]]]`. + * @return \Mcp\Server\Wire\CachePolicy|null Null keeps the SDK default (private, not cached). + * @throws \InvalidArgumentException When the config is not of that shape. + */ + public static function fromConfig(mixed $config): ?CachePolicy + { + if ($config === null) { + return null; + } + if (!is_array($config)) { + throw new InvalidArgumentException('"Mcp.server.cache" must be null or an array.'); + } + [$ttl, $scope] = self::hint($config, 'Mcp.server.cache'); + $policy = CachePolicy::default($ttl, $scope); + + $methods = $config['methods'] ?? []; + if (!is_array($methods)) { + throw new InvalidArgumentException('"Mcp.server.cache.methods" must be an array of method => hint.'); + } + foreach ($methods as $method => $hint) { + $path = sprintf('Mcp.server.cache.methods.%s', $method); + if (!is_string($method) || !is_array($hint)) { + throw new InvalidArgumentException(sprintf('"%s" must be an array with ttl and scope.', $path)); + } + [$methodTtl, $methodScope] = self::hint($hint + ['ttl' => $ttl, 'scope' => $scope->value], $path); + $policy = $policy->withMethod($method, $methodTtl, $methodScope); + } + + return $policy; + } + + /** + * @param array $hint An array with optional `ttl` and `scope`. + * @param string $path The config path, for the error message. + * @return array{0: int, 1: \Mcp\Schema\Enum\CacheScope} + */ + private static function hint(array $hint, string $path): array + { + $ttl = $hint['ttl'] ?? 0; + if (!is_int($ttl) || $ttl < 0) { + throw new InvalidArgumentException(sprintf('"%s.ttl" must be zero or more milliseconds.', $path)); + } + $scope = is_string($hint['scope'] ?? null) ? CacheScope::tryFrom($hint['scope']) : null; + if (array_key_exists('scope', $hint) && $scope === null) { + throw new InvalidArgumentException(sprintf('"%s.scope" must be "public" or "private".', $path)); + } + + return [$ttl, $scope ?? CacheScope::Private]; + } +} diff --git a/tests/TestCase/Server/CacheHintsTest.php b/tests/TestCase/Server/CacheHintsTest.php new file mode 100644 index 0000000..de3bedf --- /dev/null +++ b/tests/TestCase/Server/CacheHintsTest.php @@ -0,0 +1,63 @@ +assertNull(CacheHints::fromConfig(null)); + } + + public function testDefaultTtlAndScope(): void + { + $policy = CacheHints::fromConfig(['ttl' => 60000, 'scope' => 'public']); + + $this->assertNotNull($policy); + $this->assertSame(60000, $policy->ttlFor('tools/list')); + $this->assertSame(CacheScope::Public, $policy->scopeFor('tools/list')); + } + + public function testPerMethodOverride(): void + { + $policy = CacheHints::fromConfig([ + 'ttl' => 60000, + 'methods' => ['tools/list' => ['ttl' => 300000, 'scope' => 'public']], + ]); + + $this->assertNotNull($policy); + $this->assertSame(300000, $policy->ttlFor('tools/list')); + $this->assertSame(CacheScope::Public, $policy->scopeFor('tools/list')); + $this->assertSame(60000, $policy->ttlFor('resources/read')); + $this->assertSame(CacheScope::Private, $policy->scopeFor('resources/read')); + } + + /** + * @return array + */ + public static function invalidConfigs(): array + { + return [ + 'not an array' => ['yes'], + 'negative ttl' => [['ttl' => -1]], + 'unknown scope' => [['scope' => 'shared']], + 'method entry not an array' => [['methods' => ['tools/list' => 5]]], + ]; + } + + #[DataProvider('invalidConfigs')] + public function testInvalidConfigFails(mixed $config): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessageMatches('/^"Mcp\.server\.cache/'); + + CacheHints::fromConfig($config); + } +} From 769ffd46a335c854cc07769c615a03d54478d9d7 Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 20:21:25 +0100 Subject: [PATCH 013/181] Mcp.server.cache sets the cache hints of the 2026-07-28 protocol --- CHANGELOG.md | 1 + docs/configuration.md | 1 + src/McpConfig.php | 1 + src/Server/ServerFactory.php | 5 +++ .../TestCase/Controller/McpControllerTest.php | 40 +++++++++++++++++++ 5 files changed, 48 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6df3d5c..3f8899a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ - `Mcp.schema.normalize`, off by default: when on, `tools/list` drops `"null"` from the `type` and `enum` of optional parameters whose default is `null`, and that default, for hosts that reject type arrays. Arguments are still validated against the original schema. See Input schemas in `docs/tools.md`. - `bin/cake mcp check` warns, on a new `Tool schemas` line, about type arrays, arrays without an item type and optional parameters without a description. - `bin/cake mcp check` fails, on a new `Discovery` line, when `Mcp.discovery.scanDirs` is set and `symfony/finder` is missing: the SDK then skips discovery and the server has no tools. +- `Mcp.server.cache` sets the cache hints (`ttlMs`, `cacheScope`) of the 2026-07-28 protocol, as a default and per method. Off by default (private, not cached). - `ToolError::message()` builds the error a tool throws to send the model a message it can act on. - Docs: Results in `docs/tools.md`: what a string, an array, a list and a `CallToolResult` become, `outputSchema` and `structuredContent`, and a compact JSON text for large results. - Docs: Input schemas in `docs/tools.md` (`int[]` rather than `list`, `#[Schema]`, optional strings), and why `symfony/finder` is required in `docs/installation.md`. diff --git a/docs/configuration.md b/docs/configuration.md index 42075bb..376bf55 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -49,6 +49,7 @@ want to change; everything else keeps its default. These are the defaults - `server.name`, `server.version`: reported to clients in the `initialize` result. - `server.title`, `server.description`, `server.websiteUrl`: optional, also reported to clients. `null` sends none. - `server.instructions`: optional text telling the client's model how to use your server. `null` sends none. +- `server.cache`: the cache hints of the 2026-07-28 protocol revision, which tell a client how long it may keep a result of `server/discover`, `tools/list`, `prompts/list`, `resources/list`, `resources/templates/list` and `resources/read`. `null` (the default) marks them private and not to be cached. Otherwise an array: `ttl` in milliseconds (default `0`), `scope` `'private'` (one user, the default) or `'public'` (any user, only for results that are the same for everyone), and `methods` to set them per method, for example `['ttl' => 60000, 'methods' => ['tools/list' => ['ttl' => 300000]]]`. Clients of the older revisions get no hints. Keep `tools/list` private when the authorizer gives each user different tools. - `server.configure`: optional callable that receives the SDK `Mcp\Server\Builder` before the server is built. See [Using the SDK builder](#using-the-sdk-builder). - `discovery.scanDirs`: directories (relative to `ROOT`) scanned for attributes. Missing directories are skipped. - `discovery.excludeDirs`: directories to skip while scanning. diff --git a/src/McpConfig.php b/src/McpConfig.php index d7b072b..8ab4991 100644 --- a/src/McpConfig.php +++ b/src/McpConfig.php @@ -36,6 +36,7 @@ final class McpConfig 'description' => null, 'websiteUrl' => null, 'instructions' => null, + 'cache' => null, 'configure' => null, ], 'discovery' => ['scanDirs' => ['src/Mcp'], 'excludeDirs' => [], 'cache' => '_cake_mcp_'], diff --git a/src/Server/ServerFactory.php b/src/Server/ServerFactory.php index 1153325..9278624 100644 --- a/src/Server/ServerFactory.php +++ b/src/Server/ServerFactory.php @@ -123,6 +123,11 @@ private function build(bool $trusted, LoggerInterface $logger): Server (int)McpConfig::get('session.ttl'), )); + $cachePolicy = CacheHints::fromConfig(McpConfig::get('server.cache')); + if ($cachePolicy !== null) { + $builder->setCachePolicy($cachePolicy); + } + $instructions = McpConfig::get('server.instructions'); if (is_string($instructions) && $instructions !== '') { $builder->setInstructions($instructions); diff --git a/tests/TestCase/Controller/McpControllerTest.php b/tests/TestCase/Controller/McpControllerTest.php index 25468c8..5c18f54 100644 --- a/tests/TestCase/Controller/McpControllerTest.php +++ b/tests/TestCase/Controller/McpControllerTest.php @@ -66,6 +66,46 @@ public function testModernEraListsAndCallsWithoutASession(): void $this->assertSame('stateless', $this->json()['result']['content'][0]['text'] ?? null); } + public function testModernListCarriesPrivateNoCacheHintsByDefault(): void + { + $this->mcp($this->modern(1, 'tools/list'), $this->modernHeaders('tools/list')); + + $this->assertResponseOk(); + $this->assertSame(0, $this->json()['result']['ttlMs'] ?? null); + $this->assertSame('private', $this->json()['result']['cacheScope'] ?? null); + } + + public function testServerCacheSetsTheHints(): void + { + Configure::write('Mcp.server.cache', [ + 'ttl' => 60000, + 'scope' => 'public', + 'methods' => ['tools/list' => ['ttl' => 300000]], + ]); + + $this->mcp($this->modern(1, 'tools/list'), $this->modernHeaders('tools/list')); + + $this->assertResponseOk(); + $this->assertSame(300000, $this->json()['result']['ttlMs'] ?? null); + $this->assertSame('public', $this->json()['result']['cacheScope'] ?? null); + } + + public function testHandshakeEraHasNoCacheHints(): void + { + Configure::write('Mcp.server.cache', ['ttl' => 60000, 'scope' => 'public']); + $this->mcp($this->initialize(1)); + $headers = [ + 'Mcp-Session-Id' => $this->_response->getHeaderLine('Mcp-Session-Id'), + 'MCP-Protocol-Version' => self::HANDSHAKE, + ]; + $this->mcp(['jsonrpc' => '2.0', 'method' => 'notifications/initialized'], $headers); + + $this->mcp(['jsonrpc' => '2.0', 'id' => 2, 'method' => 'tools/list'], $headers); + + $this->assertResponseOk(); + $this->assertArrayNotHasKey('ttlMs', $this->json()['result'] ?? []); + } + public function testJsonBodyIsReadAfterBodyParserMiddleware(): void { $this->mcp( From 10a09b93e3fb0801f500afaa837373a75192daa5 Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 20:22:20 +0100 Subject: [PATCH 014/181] Add ToolValidation::check() to validate tool arguments with a Cake Validator --- CHANGELOG.md | 1 + docs/tools.md | 25 ++++++++++ src/Tool/ToolValidation.php | 37 ++++++++++++++ tests/TestCase/Tool/ToolValidationTest.php | 58 ++++++++++++++++++++++ 4 files changed, 121 insertions(+) create mode 100644 src/Tool/ToolValidation.php create mode 100644 tests/TestCase/Tool/ToolValidationTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f8899a..239a2e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ - `bin/cake mcp check` warns, on a new `Tool schemas` line, about type arrays, arrays without an item type and optional parameters without a description. - `bin/cake mcp check` fails, on a new `Discovery` line, when `Mcp.discovery.scanDirs` is set and `symfony/finder` is missing: the SDK then skips discovery and the server has no tools. - `Mcp.server.cache` sets the cache hints (`ttlMs`, `cacheScope`) of the 2026-07-28 protocol, as a default and per method. Off by default (private, not cached). +- `ToolValidation::check()` validates a tool's arguments with a Cake `Validator` and throws a tool error with one line per field. - `ToolError::message()` builds the error a tool throws to send the model a message it can act on. - Docs: Results in `docs/tools.md`: what a string, an array, a list and a `CallToolResult` become, `outputSchema` and `structuredContent`, and a compact JSON text for large results. - Docs: Input schemas in `docs/tools.md` (`int[]` rather than `list`, `#[Schema]`, optional strings), and why `symfony/finder` is required in `docs/installation.md`. diff --git a/docs/tools.md b/docs/tools.md index cd0c722..5655429 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -319,3 +319,28 @@ array returned by `Validator::validate()` or `getErrors()`, or a simple catch `Cake\ORM\Exception\PersistenceFailedException` and pass `$exception->getEntity()`. The messages are your validation messages as they are, so write them for someone who has to fix the data. + +To check the arguments themselves before doing any work, pass them and a +`Cake\Validation\Validator` to `CakeDC\Mcp\Tool\ToolValidation::check()`. It +throws the same kind of error when a rule fails. Keep the shape and the types in +the input schema (`#[Schema]`, PHP types) and put in the validator what a schema +cannot say: limits that depend on your data, rules across fields, or a validator +your application already has. + +```php +use Cake\Validation\Validator; +use CakeDC\Mcp\Tool\ToolValidation; + +#[McpTool(name: 'reserve_stock')] +public function reserve(string $sku, int $quantity): array +{ + $available = $this->stock->available($sku); + $validator = (new Validator()) + ->range('quantity', [1, $available], sprintf('Between 1 and %d, the stock of %s.', $available, $sku)); + ToolValidation::check(['sku' => $sku, 'quantity' => $quantity], $validator, 'Nothing was reserved.'); + + // ... +} +``` + +Pass `newRecord: false` to apply the validator's `'update'` rules. diff --git a/src/Tool/ToolValidation.php b/src/Tool/ToolValidation.php new file mode 100644 index 0000000..a7b59ab --- /dev/null +++ b/src/Tool/ToolValidation.php @@ -0,0 +1,37 @@ + $arguments The tool's arguments. + * @param \Cake\Validation\Validator $validator The rules. + * @param string $message The first line of the error. + * @param bool $newRecord False to apply the validator's update rules (`'update'` presence, for example). + * @return void + * @throws \Mcp\Exception\ToolCallException When a rule fails; the model reads its message. + */ + public static function check( + array $arguments, + Validator $validator, + string $message = 'The arguments are invalid.', + bool $newRecord = true, + ): void { + $errors = $validator->validate($arguments, $newRecord); + if ($errors !== []) { + throw ToolError::invalid($errors, $message); + } + } +} diff --git a/tests/TestCase/Tool/ToolValidationTest.php b/tests/TestCase/Tool/ToolValidationTest.php new file mode 100644 index 0000000..220360a --- /dev/null +++ b/tests/TestCase/Tool/ToolValidationTest.php @@ -0,0 +1,58 @@ + 3, 'email' => 'buyer@example.com'], $this->validator()); + + $this->addToAssertionCount(1); + } + + public function testInvalidArgumentsThrowOneLinePerField(): void + { + try { + ToolValidation::check(['quantity' => 0, 'email' => 'x'], $this->validator()); + $this->fail('No exception was thrown.'); + } catch (ToolCallException $exception) { + $lines = explode("\n", $exception->getMessage()); + $this->assertSame('The arguments are invalid.', $lines[0]); + $this->assertContains('- quantity: Between 1 and 100', $lines); + $this->assertStringStartsWith('- email: ', $lines[2]); + } + } + + public function testCustomFirstLine(): void + { + $this->expectException(ToolCallException::class); + $this->expectExceptionMessage("The order was not placed.\n- quantity: Between 1 and 100"); + + ToolValidation::check(['quantity' => 500], $this->validator(), 'The order was not placed.'); + } + + public function testUpdateRulesWithNewRecordFalse(): void + { + $validator = (new Validator())->requirePresence('id', 'update', 'The id is required to update.'); + + ToolValidation::check([], $validator); + + $this->expectException(ToolCallException::class); + $this->expectExceptionMessage('- id: The id is required to update.'); + ToolValidation::check([], $validator, newRecord: false); + } + + private function validator(): Validator + { + return (new Validator()) + ->range('quantity', [1, 100], 'Between 1 and 100') + ->email('email'); + } +} From eb61f9ddc5997c8fd653d8c127cd0619b2be04f2 Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 20:24:27 +0100 Subject: [PATCH 015/181] McpTestTrait: structured content paths and tool lists of another identity --- CHANGELOG.md | 1 + docs/testing.md | 12 +++ src/TestSuite/McpTestTrait.php | 99 +++++++++++++++++++ tests/TestCase/TestSuite/McpTestTraitTest.php | 48 +++++++++ 4 files changed, 160 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 239a2e7..8a9092f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ - `bin/cake mcp check` warns, on a new `Tool schemas` line, about type arrays, arrays without an item type and optional parameters without a description. - `bin/cake mcp check` fails, on a new `Discovery` line, when `Mcp.discovery.scanDirs` is set and `symfony/finder` is missing: the SDK then skips discovery and the server has no tools. - `Mcp.server.cache` sets the cache hints (`ttlMs`, `cacheScope`) of the 2026-07-28 protocol, as a default and per method. Off by default (private, not cached). +- `McpTestTrait`: `assertMcpStructuredContentPath()` and `assertMcpStructuredContentHas()` check one value of `structuredContent` by dot path; `assertMcpToolListedFor()` and `assertMcpToolNotListedFor()` check what another identity sees in `tools/list`. - `ToolValidation::check()` validates a tool's arguments with a Cake `Validator` and throws a tool error with one line per field. - `ToolError::message()` builds the error a tool throws to send the model a message it can act on. - Docs: Results in `docs/tools.md`: what a string, an array, a list and a `CallToolResult` become, `outputSchema` and `structuredContent`, and a compact JSON text for large results. diff --git a/docs/testing.md b/docs/testing.md index dee2750..c7adaf2 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -117,12 +117,24 @@ endpoint (`IntegrationTestTrait`, a `POST` to `/mcp` with your | `assertMcpInsufficientScope(?$scopes)` | was refused because the token lacks scopes, the way the endpoint answers `403 insufficient_scope`. With `$scopes` it also checks the scopes the call needs (any order). | | `assertMcpResultContains($text)` | returned text containing `$text`. | | `assertMcpStructuredContent($expected)` | returned this `structuredContent`. Key order does not matter, value types do. | +| `assertMcpStructuredContentPath($path, $expected)` | returned `$expected` at a dot path of its `structuredContent` (`order.lines.0.sku`). Value types matter, and a missing path fails. | +| `assertMcpStructuredContentHas($path)` | returned a `structuredContent` with that dot path, even with a `null` value. | `assertMcpToolListed($name)` and `assertMcpToolNotListed($name)` check what the current identity sees in `tools/list`. They make their own call. `assertMcpToolNotListed()` also checks that the tool exists, for the same reason as `assertMcpToolDenied()`. +`assertMcpToolListedFor($identity, $name)` and +`assertMcpToolNotListedFor($identity, $name)` do the same for another identity, +with default scopes, and leave the test's own identity, scopes and claims as +they were: + +```php +$this->assertMcpToolListedFor(['id' => 1, 'role' => 'admin'], 'refund_order'); +$this->assertMcpToolNotListedFor(['id' => 2, 'role' => 'user'], 'refund_order'); +``` + ## Replacing services The trait uses Cake's `ContainerStubTrait`, so `mockService()` replaces a diff --git a/src/TestSuite/McpTestTrait.php b/src/TestSuite/McpTestTrait.php index 79711a2..3e35f18 100644 --- a/src/TestSuite/McpTestTrait.php +++ b/src/TestSuite/McpTestTrait.php @@ -296,6 +296,105 @@ public function assertMcpStructuredContent(array $expected, string $message = '' ); } + /** + * Asserts one value of the last result's `structuredContent`, found by a dot path + * (`order.lines.0.sku`). Value types matter. Fails when the path does not exist. + * + * @param string $path Dot path into the structured content. + * @param mixed $expected The expected value. + * @param string $message The failure message. + * @return void + */ + public function assertMcpStructuredContentPath(string $path, mixed $expected, string $message = ''): void + { + [$found, $value] = $this->mcpStructuredContentAt($path); + if (!$found) { + Assert::fail($message ?: sprintf('The structuredContent has no "%s".', $path)); + } + Assert::assertSame($expected, $value, $message); + } + + /** + * Asserts that a dot path exists in the last result's `structuredContent`, even with a `null` value. + * + * @param string $path Dot path into the structured content. + * @param string $message The failure message. + * @return void + */ + public function assertMcpStructuredContentHas(string $path, string $message = ''): void + { + Assert::assertTrue( + $this->mcpStructuredContentAt($path)[0], + $message ?: sprintf('The structuredContent has no "%s".', $path), + ); + } + + /** + * Asserts that another identity sees a tool in `tools/list`, with default scopes and no claims. The test's own + * identity, scopes and claims stay as they were. + * + * @param mixed $identity The identity to list the tools for. + * @param string $name The tool name. + * @param string $message The failure message. + * @return void + */ + public function assertMcpToolListedFor(mixed $identity, string $name, string $message = ''): void + { + $this->mcpAs($identity, fn() => $this->assertMcpToolListed( + $name, + $message ?: sprintf('Tool "%s" is not listed for that identity.', $name), + )); + } + + /** + * Asserts that another identity does not see a tool in `tools/list` (and that the tool exists), with default + * scopes and no claims. The test's own identity, scopes and claims stay as they were. + * + * @param mixed $identity The identity to list the tools for. + * @param string $name The tool name. + * @param string $message The failure message. + * @return void + */ + public function assertMcpToolNotListedFor(mixed $identity, string $name, string $message = ''): void + { + $this->mcpAs($identity, fn() => $this->assertMcpToolNotListed($name, $message)); + } + + /** + * Runs $assertion as $identity, then puts back the test's identity, scopes and claims. + * + * @param mixed $identity The identity. + * @param callable(): void $assertion The assertion. + * @return void + */ + private function mcpAs(mixed $identity, callable $assertion): void + { + $saved = [$this->_mcpIdentity, $this->_mcpScopes, $this->_mcpClaims]; + $this->mcpActingAs($identity); + try { + $assertion(); + } finally { + [$this->_mcpIdentity, $this->_mcpScopes, $this->_mcpClaims] = $saved; + } + } + + /** + * @param string $path Dot path into the last result's structured content. + * @return array{0: bool, 1: mixed} Whether the path exists, and its value. + */ + private function mcpStructuredContentAt(string $path): array + { + $value = $this->mcpResult()['structuredContent'] ?? null; + foreach (explode('.', $path) as $key) { + if (!is_array($value) || !array_key_exists($key, $value)) { + return [false, null]; + } + $value = $value[$key]; + } + + return [true, $value]; + } + /** * Asserts that the current identity sees a tool in `tools/list`. * diff --git a/tests/TestCase/TestSuite/McpTestTraitTest.php b/tests/TestCase/TestSuite/McpTestTraitTest.php index 4ba4236..ee5ea77 100644 --- a/tests/TestCase/TestSuite/McpTestTraitTest.php +++ b/tests/TestCase/TestSuite/McpTestTraitTest.php @@ -51,6 +51,54 @@ public function testToolsSeeTheIdentityAndTheAccessToken(): void $this->assertMcpStructuredContent(['subject' => '7', 'identifier' => 7]); } + public function testStructuredContentPath(): void + { + $this->mcpActingAs(['id' => 7]); + $this->mcpCallTool('whoami'); + + $this->assertMcpStructuredContentPath('identifier', 7); + + $this->expectException(AssertionFailedError::class); + $this->assertMcpStructuredContentPath('identifier', '7'); + } + + public function testStructuredContentPathFailsWhenMissing(): void + { + $this->mcpCallTool('whoami'); + + $this->expectException(AssertionFailedError::class); + $this->expectExceptionMessage('nope.deeper'); + $this->assertMcpStructuredContentPath('nope.deeper', null); + } + + public function testStructuredContentHasSeesNullValues(): void + { + $this->mcpCallTool('whoami'); + + $this->assertMcpStructuredContentHas('identifier'); + + $this->expectException(AssertionFailedError::class); + $this->assertMcpStructuredContentHas('nope'); + } + + public function testListedForAnotherIdentityKeepsTheTestIdentity(): void + { + Configure::write('Mcp.authorization.authorizer', $this->onlyForAdmins('admin_only')); + $this->mcpActingAs(['id' => 7, 'role' => 'admin'], ['mcp:tools']); + + $this->assertMcpToolListedFor(['id' => 2, 'role' => 'admin'], 'admin_only'); + $this->assertMcpToolNotListedFor(['id' => 1, 'role' => 'user'], 'admin_only'); + try { + $this->assertMcpToolListedFor(['id' => 1, 'role' => 'user'], 'admin_only'); + $this->fail('The assertion passed for a user.'); + } catch (AssertionFailedError) { + } + + $this->mcpCallTool('whoami'); + $this->assertMcpStructuredContentPath('identifier', 7); + $this->assertSame(['mcp:tools'], $this->_mcpScopes); + } + public function testAnonymousByDefault(): void { $this->mcpCallTool('whoami'); From 5c883926afd9d025b36be0fa54efad3a408b4388 Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 20:28:42 +0100 Subject: [PATCH 016/181] Bake generators for MCP tools, resources and prompts --- CHANGELOG.md | 1 + composer.json | 2 + docs/tools.md | 18 +++ src/Bake/McpBakeCommand.php | 126 +++++++++++++++ src/Command/Bake/McpPromptCommand.php | 28 ++++ src/Command/Bake/McpResourceCommand.php | 28 ++++ src/Command/Bake/McpToolCommand.php | 28 ++++ templates/bake/Mcp/prompt.twig | 23 +++ templates/bake/Mcp/resource.twig | 20 +++ templates/bake/Mcp/tool.twig | 27 ++++ templates/bake/tests/prompt.twig | 18 +++ templates/bake/tests/resource.twig | 17 ++ templates/bake/tests/tool.twig | 21 +++ .../Command/Bake/McpBakeCommandsTest.php | 147 ++++++++++++++++++ .../BakeTarget/src/BakeTargetPlugin.php | 13 ++ .../plugins/BakeTarget/tests/.gitkeep | 0 16 files changed, 517 insertions(+) create mode 100644 src/Bake/McpBakeCommand.php create mode 100644 src/Command/Bake/McpPromptCommand.php create mode 100644 src/Command/Bake/McpResourceCommand.php create mode 100644 src/Command/Bake/McpToolCommand.php create mode 100644 templates/bake/Mcp/prompt.twig create mode 100644 templates/bake/Mcp/resource.twig create mode 100644 templates/bake/Mcp/tool.twig create mode 100644 templates/bake/tests/prompt.twig create mode 100644 templates/bake/tests/resource.twig create mode 100644 templates/bake/tests/tool.twig create mode 100644 tests/TestCase/Command/Bake/McpBakeCommandsTest.php create mode 100644 tests/test_app/plugins/BakeTarget/src/BakeTargetPlugin.php create mode 100644 tests/test_app/plugins/BakeTarget/tests/.gitkeep diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a9092f..cb644f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ - `bin/cake mcp check` warns, on a new `Tool schemas` line, about type arrays, arrays without an item type and optional parameters without a description. - `bin/cake mcp check` fails, on a new `Discovery` line, when `Mcp.discovery.scanDirs` is set and `symfony/finder` is missing: the SDK then skips discovery and the server has no tools. - `Mcp.server.cache` sets the cache hints (`ttlMs`, `cacheScope`) of the 2026-07-28 protocol, as a default and per method. Off by default (private, not cached). +- Bake commands `mcp_tool`, `mcp_resource` and `mcp_prompt` (with `cakephp/bake`) create an invokable class in `src/Mcp/` and its test. - `McpTestTrait`: `assertMcpStructuredContentPath()` and `assertMcpStructuredContentHas()` check one value of `structuredContent` by dot path; `assertMcpToolListedFor()` and `assertMcpToolNotListedFor()` check what another identity sees in `tools/list`. - `ToolValidation::check()` validates a tool's arguments with a Cake `Validator` and throws a tool error with one line per field. - `ToolError::message()` builds the error a tool throws to send the model a message it can act on. diff --git a/composer.json b/composer.json index 8b94eea..f4713d0 100644 --- a/composer.json +++ b/composer.json @@ -21,6 +21,7 @@ "cakedc/cakephp-oauth-server": "^1.0", "cakedc/oauth-server": "^1.0", "cakephp/authentication": "^3.3", + "cakephp/bake": "^3.0", "cakephp/cakephp-codesniffer": "^5.1", "cakephp/migrations": "^4.0 || ^5.0", "firebase/php-jwt": "^6.10 || ^7.0", @@ -29,6 +30,7 @@ "psr/cache": "^2.0 || ^3.0" }, "suggest": { + "cakephp/bake": "Generates MCP tools, resources and prompts with their tests (bin/cake bake mcp_tool, mcp_resource, mcp_prompt)", "cakephp/authentication": "Identifies the caller of the MCP endpoint (for example with a Bearer token authenticator)", "cakedc/auth": "Enables RbacToolAuthorizer, per-tool permissions in the config/permissions.php format", "cakedc/cakephp-oauth-server": "OAuth 2.1 sign-in for remote MCP clients with the application's own login (Mcp.auth.mode oauth)", diff --git a/docs/tools.md b/docs/tools.md index 5655429..acd1566 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -155,6 +155,24 @@ public function summary(): CallToolResult tool error ("Invalid structured output for tool ..."), not as data. Test the tool's result with `assertMcpStructuredContent()` (see [Testing](testing.md)). +## Generating classes with bake + +With `cakephp/bake` installed, three bake commands create a class in +`src/Mcp/` and its test in `tests/TestCase/Mcp/`: + +```bash +bin/cake bake mcp_tool ListOrders # src/Mcp/ListOrdersTool.php, tool list_orders +bin/cake bake mcp_resource OrderGuide # src/Mcp/OrderGuideResource.php, app://order-guide +bin/cake bake mcp_prompt WeeklyReport # src/Mcp/WeeklyReportPrompt.php, prompt weekly_report +``` + +Each class is invokable, with the attribute on the class and the work in +`__invoke()`, one class per tool. The generated tool is read-only, has every +parameter described and passes the `Tool schemas` line of `bin/cake mcp check`. +Replace the placeholder description: the model reads it to decide when to call +the tool. `--plugin Shop` bakes into a plugin, `--no-test` skips the test, and +`--force` overwrites an existing file. + ## Annotations Annotations tell the client how a tool behaves. Clients such as Claude use them diff --git a/src/Bake/McpBakeCommand.php b/src/Bake/McpBakeCommand.php new file mode 100644 index 0000000..c549fbc --- /dev/null +++ b/src/Bake/McpBakeCommand.php @@ -0,0 +1,126 @@ +kind(); + } + + /** + * @inheritDoc + */ + public function fileName(string $name): string + { + return $this->className($name) . '.php'; + } + + /** + * @inheritDoc + */ + public function template(): string + { + return 'CakeDC/Mcp.Mcp/' . $this->kind(); + } + + /** + * @inheritDoc + */ + public function templateData(Arguments $arguments): array + { + $name = $this->baseName(Inflector::camelize((string)$arguments->getArgumentAt(0))); + + return parent::templateData($arguments) + [ + 'className' => $this->className($name), + 'mcpName' => Inflector::underscore($name), + 'uriName' => Inflector::dasherize($name), + ]; + } + + /** + * Bakes the class, then its test unless `--no-test` is given. + * + * @param string $className The class name, as given. + * @param \Cake\Console\Arguments $args The arguments. + * @param \Cake\Console\ConsoleIo $io The console. + * @return void + */ + public function bakeTest(string $className, Arguments $args, ConsoleIo $io): void + { + if ($args->getOption('no-test')) { + return; + } + $data = $this->templateData($args); + $namespace = (string)$data['namespace']; + $contents = $this->createTemplateRenderer() + ->set($data + ['testNamespace' => $namespace . '\\Test\\TestCase\\Mcp']) + ->generate('CakeDC/Mcp.tests/' . $this->kind()); + + $base = $this->plugin ? $this->_pluginPath($this->plugin) : ROOT . DS; + $io->createFile( + $base . 'tests' . DS . 'TestCase' . DS . 'Mcp' . DS . $data['className'] . 'Test.php', + $contents, + $this->force, + ); + } + + /** + * The class name: the base name plus the kind's suffix (`ListOrders` and `ListOrdersTool` give `ListOrdersTool`). + * + * @param string $name The name as given. + * @return string + */ + private function className(string $name): string + { + return $this->baseName($name) . $this->suffix(); + } + + /** + * @param string $name The name as given. + * @return string The name without the kind's suffix. + */ + private function baseName(string $name): string + { + $suffix = $this->suffix(); + if ($name !== $suffix && str_ends_with($name, $suffix)) { + return substr($name, 0, -strlen($suffix)); + } + + return $name; + } + + /** + * @return string `Tool`, `Resource` or `Prompt`. + */ + private function suffix(): string + { + return ucfirst($this->kind()); + } +} diff --git a/src/Command/Bake/McpPromptCommand.php b/src/Command/Bake/McpPromptCommand.php new file mode 100644 index 0000000..cb0da8a --- /dev/null +++ b/src/Command/Bake/McpPromptCommand.php @@ -0,0 +1,28 @@ +`: an MCP prompt as an invokable class in `src/Mcp/`, and its test. + */ +class McpPromptCommand extends McpBakeCommand +{ + /** + * @inheritDoc + */ + public static function getDescription(): string + { + return 'Bake an MCP prompt class and its test.'; + } + + /** + * @inheritDoc + */ + protected function kind(): string + { + return 'prompt'; + } +} diff --git a/src/Command/Bake/McpResourceCommand.php b/src/Command/Bake/McpResourceCommand.php new file mode 100644 index 0000000..52ef1a4 --- /dev/null +++ b/src/Command/Bake/McpResourceCommand.php @@ -0,0 +1,28 @@ +`: an MCP resource as an invokable class in `src/Mcp/`, and its test. + */ +class McpResourceCommand extends McpBakeCommand +{ + /** + * @inheritDoc + */ + public static function getDescription(): string + { + return 'Bake an MCP resource class and its test.'; + } + + /** + * @inheritDoc + */ + protected function kind(): string + { + return 'resource'; + } +} diff --git a/src/Command/Bake/McpToolCommand.php b/src/Command/Bake/McpToolCommand.php new file mode 100644 index 0000000..7a757db --- /dev/null +++ b/src/Command/Bake/McpToolCommand.php @@ -0,0 +1,28 @@ +`: an MCP tool as an invokable class in `src/Mcp/`, and its test. + */ +class McpToolCommand extends McpBakeCommand +{ + /** + * @inheritDoc + */ + public static function getDescription(): string + { + return 'Bake an MCP tool class and its test.'; + } + + /** + * @inheritDoc + */ + protected function kind(): string + { + return 'tool'; + } +} diff --git a/templates/bake/Mcp/prompt.twig b/templates/bake/Mcp/prompt.twig new file mode 100644 index 0000000..1b91b37 --- /dev/null +++ b/templates/bake/Mcp/prompt.twig @@ -0,0 +1,23 @@ +{{ element('Bake.file_header', { + namespace: "#{namespace}\\Mcp", + classImports: [ + 'Mcp\\Capability\\Attribute\\McpPrompt', + ], +}) }} + +#[McpPrompt(name: '{{ mcpName }}')] +class {{ className }} +{ + /** + * Describe what the prompt is for: clients show it in their prompt list. + * + * @param string $topic What the prompt is about. Leave it out for a general one. + * @return list + */ + public function __invoke(string $topic = ''): array + { + return [ + ['role' => 'user', 'content' => trim('Write the prompt here. ' . $topic)], + ]; + } +} diff --git a/templates/bake/Mcp/resource.twig b/templates/bake/Mcp/resource.twig new file mode 100644 index 0000000..38da1fd --- /dev/null +++ b/templates/bake/Mcp/resource.twig @@ -0,0 +1,20 @@ +{{ element('Bake.file_header', { + namespace: "#{namespace}\\Mcp", + classImports: [ + 'Mcp\\Capability\\Attribute\\McpResource', + ], +}) }} + +#[McpResource(uri: 'app://{{ uriName }}', name: '{{ mcpName }}', mimeType: 'text/markdown')] +class {{ className }} +{ + /** + * Describe what this resource holds: clients show it when they list resources. + * + * @return string + */ + public function __invoke(): string + { + return "# {{ className }}\n\nWrite the content here.\n"; + } +} diff --git a/templates/bake/Mcp/tool.twig b/templates/bake/Mcp/tool.twig new file mode 100644 index 0000000..e7b1296 --- /dev/null +++ b/templates/bake/Mcp/tool.twig @@ -0,0 +1,27 @@ +{{ element('Bake.file_header', { + namespace: "#{namespace}\\Mcp", + classImports: [ + 'Mcp\\Capability\\Attribute\\McpTool', + 'Mcp\\Capability\\Attribute\\Schema', + 'Mcp\\Schema\\ToolAnnotations', + ], +}) }} + +#[McpTool(name: '{{ mcpName }}', annotations: new ToolAnnotations(readOnlyHint: true, openWorldHint: false))] +class {{ className }} +{ + /** + * Describe what the tool does and when to use it: the model reads this to decide whether to call it. + * + * @param string $query What to look for. Leave it out for everything. + * @param int $limit How many results to return, 1 to 50. + * @return array + */ + public function __invoke( + string $query = '', + #[Schema(minimum: 1, maximum: 50)] + int $limit = 10, + ): array { + return ['query' => $query, 'limit' => $limit, 'items' => []]; + } +} diff --git a/templates/bake/tests/prompt.twig b/templates/bake/tests/prompt.twig new file mode 100644 index 0000000..d65cb94 --- /dev/null +++ b/templates/bake/tests/prompt.twig @@ -0,0 +1,18 @@ +{{ element('Bake.file_header', { + namespace: testNamespace, + classImports: [ + 'Cake\\TestSuite\\TestCase', + "#{namespace}\\Mcp\\#{className}", + ], +}) }} + +class {{ className }}Test extends TestCase +{ + public function testItBuildsMessages(): void + { + $messages = (new {{ className }}())('example'); + + $this->assertNotEmpty($messages); + $this->assertSame('user', $messages[0]['role']); + } +} diff --git a/templates/bake/tests/resource.twig b/templates/bake/tests/resource.twig new file mode 100644 index 0000000..b3f63e5 --- /dev/null +++ b/templates/bake/tests/resource.twig @@ -0,0 +1,17 @@ +{{ element('Bake.file_header', { + namespace: testNamespace, + classImports: [ + 'Cake\\TestSuite\\TestCase', + "#{namespace}\\Mcp\\#{className}", + ], +}) }} + +class {{ className }}Test extends TestCase +{ + public function testItHasContent(): void + { + $content = (new {{ className }}())(); + + $this->assertNotSame('', trim($content)); + } +} diff --git a/templates/bake/tests/tool.twig b/templates/bake/tests/tool.twig new file mode 100644 index 0000000..9b1e0c4 --- /dev/null +++ b/templates/bake/tests/tool.twig @@ -0,0 +1,21 @@ +{{ element('Bake.file_header', { + namespace: testNamespace, + classImports: [ + 'Cake\\TestSuite\\TestCase', + 'CakeDC\\Mcp\\TestSuite\\McpTestTrait', + ], +}) }} + +class {{ className }}Test extends TestCase +{ + use McpTestTrait; + + public function testItAnswers(): void + { + $this->mcpActingAs(['id' => 1]); + + $this->mcpCallTool('{{ mcpName }}', ['query' => 'example', 'limit' => 5]); + + $this->assertMcpToolSucceeded(); + } +} diff --git a/tests/TestCase/Command/Bake/McpBakeCommandsTest.php b/tests/TestCase/Command/Bake/McpBakeCommandsTest.php new file mode 100644 index 0000000..eeafcb2 --- /dev/null +++ b/tests/TestCase/Command/Bake/McpBakeCommandsTest.php @@ -0,0 +1,147 @@ + + */ + private const BAKED = [ + 'src/Mcp/ListOrdersTool.php', + 'src/Mcp/OrderGuideResource.php', + 'src/Mcp/WeeklyReportPrompt.php', + 'tests/TestCase/Mcp/ListOrdersToolTest.php', + 'tests/TestCase/Mcp/OrderGuideResourceTest.php', + 'tests/TestCase/Mcp/WeeklyReportPromptTest.php', + ]; + + protected function setUp(): void + { + parent::setUp(); + // Not autoloaded: the test plugin exists only for these tests. + require_once self::PLUGIN . 'src' . DS . 'BakeTargetPlugin.php'; + $this->loadPlugins(['Bake', 'BakeTarget' => ['path' => self::PLUGIN]]); + } + + protected function tearDown(): void + { + foreach (self::BAKED as $file) { + if (is_file(self::PLUGIN . $file)) { + unlink(self::PLUGIN . $file); + } + } + foreach (['src/Mcp', 'tests/TestCase/Mcp', 'tests/TestCase'] as $dir) { + if (is_dir(self::PLUGIN . $dir)) { + rmdir(self::PLUGIN . $dir); + } + } + parent::tearDown(); + } + + public function testBakesAToolAndItsTest(): void + { + $this->exec('bake mcp_tool ListOrders --plugin BakeTarget --force'); + + $this->assertExitSuccess(); + $class = $this->baked('src/Mcp/ListOrdersTool.php'); + $this->assertStringContainsString('namespace BakeTarget\Mcp;', $class); + $this->assertStringContainsString('class ListOrdersTool', $class); + $this->assertStringContainsString("name: 'list_orders'", $class); + $test = $this->baked('tests/TestCase/Mcp/ListOrdersToolTest.php'); + $this->assertStringContainsString('namespace BakeTarget\Test\TestCase\Mcp;', $test); + $this->assertStringContainsString('use McpTestTrait;', $test); + $this->assertStringContainsString("mcpCallTool('list_orders'", $test); + } + + public function testTheSuffixIsNotDoubled(): void + { + $this->exec('bake mcp_tool ListOrdersTool --plugin BakeTarget --force --no-test'); + + $this->assertExitSuccess(); + $this->assertFileExists(self::PLUGIN . 'src/Mcp/ListOrdersTool.php'); + $this->assertStringContainsString("name: 'list_orders'", $this->baked('src/Mcp/ListOrdersTool.php')); + } + + public function testBakesAResourceAndAPrompt(): void + { + $this->exec('bake mcp_resource OrderGuide --plugin BakeTarget --force'); + $this->assertExitSuccess(); + $this->assertStringContainsString("uri: 'app://order-guide'", $this->baked('src/Mcp/OrderGuideResource.php')); + $this->assertFileExists(self::PLUGIN . 'tests/TestCase/Mcp/OrderGuideResourceTest.php'); + + $this->exec('bake mcp_prompt WeeklyReport --plugin BakeTarget --force'); + $this->assertExitSuccess(); + $this->assertStringContainsString("name: 'weekly_report'", $this->baked('src/Mcp/WeeklyReportPrompt.php')); + $this->assertFileExists(self::PLUGIN . 'tests/TestCase/Mcp/WeeklyReportPromptTest.php'); + } + + public function testNoTestOption(): void + { + $this->exec('bake mcp_tool ListOrders --plugin BakeTarget --force --no-test'); + + $this->assertExitSuccess(); + $this->assertFileDoesNotExist(self::PLUGIN . 'tests/TestCase/Mcp/ListOrdersToolTest.php'); + } + + public function testBakedClassesWork(): void + { + foreach (['mcp_tool ListOrders', 'mcp_resource OrderGuide', 'mcp_prompt WeeklyReport'] as $command) { + $this->exec(sprintf('bake %s --plugin BakeTarget --force --no-test', $command)); + $this->assertExitSuccess(); + } + foreach (['ListOrdersTool', 'OrderGuideResource', 'WeeklyReportPrompt'] as $class) { + require_once self::PLUGIN . 'src/Mcp/' . $class . '.php'; + } + + $transport = new RecordingTransport(array_map('json_encode', [ + ['jsonrpc' => '2.0', 'id' => 1, 'method' => 'initialize', 'params' => [ + 'protocolVersion' => '2025-06-18', + 'capabilities' => new stdClass(), + 'clientInfo' => ['name' => 'test', 'version' => '1'], + ]], + ['jsonrpc' => '2.0', 'method' => 'notifications/initialized'], + ['jsonrpc' => '2.0', 'id' => 2, 'method' => 'tools/list'], + ['jsonrpc' => '2.0', 'id' => 3, 'method' => 'tools/call', 'params' => [ + 'name' => 'list_orders', + 'arguments' => ['query' => 'late', 'limit' => 5], + ]], + ['jsonrpc' => '2.0', 'id' => 4, 'method' => 'resources/read', 'params' => ['uri' => 'app://order-guide']], + ['jsonrpc' => '2.0', 'id' => 5, 'method' => 'prompts/get', 'params' => ['name' => 'weekly_report']], + ])); + Server::builder() + ->setServerInfo('bake', '1') + ->setDiscovery(rtrim(self::PLUGIN, DS), ['src/Mcp']) + ->build() + ->run($transport); + + $tools = $transport->responseFor(2)['result']['tools'] ?? []; + $this->assertSame(['list_orders'], array_column($tools, 'name')); + $this->assertSame([], SchemaLint::problems($tools[0])); + $this->assertFalse($transport->responseFor(3)['result']['isError'] ?? true, (string)json_encode($transport->responseFor(3))); + $this->assertNotEmpty($transport->responseFor(4)['result']['contents'] ?? null, (string)json_encode($transport->responseFor(4))); + $this->assertNotEmpty($transport->responseFor(5)['result']['messages'] ?? null, (string)json_encode($transport->responseFor(5))); + } + + private function baked(string $file): string + { + $this->assertFileExists(self::PLUGIN . $file); + + return (string)file_get_contents(self::PLUGIN . $file); + } +} diff --git a/tests/test_app/plugins/BakeTarget/src/BakeTargetPlugin.php b/tests/test_app/plugins/BakeTarget/src/BakeTargetPlugin.php new file mode 100644 index 0000000..6b60fc5 --- /dev/null +++ b/tests/test_app/plugins/BakeTarget/src/BakeTargetPlugin.php @@ -0,0 +1,13 @@ + Date: Fri, 20 Nov 2026 20:31:44 +0100 Subject: [PATCH 017/181] McpConfig: resolve the config of named servers --- src/McpConfig.php | 147 +++++++++++++++++++++++++++---- tests/TestCase/McpConfigTest.php | 110 +++++++++++++++++++++++ 2 files changed, 238 insertions(+), 19 deletions(-) diff --git a/src/McpConfig.php b/src/McpConfig.php index 8ab4991..852b749 100644 --- a/src/McpConfig.php +++ b/src/McpConfig.php @@ -75,25 +75,140 @@ final class McpConfig ]; /** - * @param string|null $path Dot path inside the `Mcp` config, or null for all of it. + * The server the top-level `Mcp` config describes. + */ + public const DEFAULT_SERVER = 'default'; + + /** + * Sections a named server replaces whole when it sets them, so a narrower server never picks up the default + * server's scopes, rules or tools. `server.configure` follows the same rule. + * + * @var list + */ + private const REPLACED_SECTIONS = ['auth', 'authorization', 'discovery']; + + /** + * @param string|null $path Dot path inside the server's config, or null for all of it. + * @param string $server The server: `default` (the top-level `Mcp` config) or a key of `Mcp.servers`. * @return mixed + * @throws \InvalidArgumentException When the server is not configured or its config is invalid. */ - public static function get(?string $path = null): mixed + public static function get(?string $path = null, string $server = self::DEFAULT_SERVER): mixed { - $config = self::merge(self::DEFAULTS, (array)Configure::read('Mcp')); + $config = self::resolve($server); return $path === null ? $config : Hash::get($config, $path); } + /** + * The configured servers: `default` first, then the keys of `Mcp.servers` in order. + * + * @return list + * @throws \InvalidArgumentException When `Mcp.servers` is invalid. + */ + public static function servers(): array + { + return [self::DEFAULT_SERVER, ...array_keys(self::named())]; + } + + /** + * The server whose route or protected resource metadata route $request is for, or null. + * + * @param \Psr\Http\Message\ServerRequestInterface $request The request. + * @return string|null + */ + public static function serverFor(ServerRequestInterface $request): ?string + { + $path = $request instanceof ServerRequest ? $request->getPath() : $request->getUri()->getPath(); + $path = '/' . trim($path, '/'); + foreach (self::servers() as $server) { + $route = self::get('route', $server); + if (!is_string($route) || trim($route, '/') === '') { + continue; + } + $route = '/' . trim($route, '/'); + if ($path === $route || $path === self::METADATA_PREFIX . $route) { + return $server; + } + } + + return null; + } + + /** + * @param string $server The server name. + * @return array The resolved config of $server. + */ + private static function resolve(string $server): array + { + $top = (array)Configure::read('Mcp'); + unset($top['servers']); + $default = self::merge(self::DEFAULTS, $top); + if ($server === self::DEFAULT_SERVER) { + return $default; + } + + $named = self::named()[$server] ?? null; + if ($named === null) { + throw new InvalidArgumentException(sprintf('"Mcp.servers.%s" is not configured.', $server)); + } + $config = $default; + foreach (self::REPLACED_SECTIONS as $section) { + if (array_key_exists($section, $named)) { + $config[$section] = self::merge(self::DEFAULTS[$section], (array)$named[$section]); + unset($named[$section]); + } + } + $hasConfigure = is_array($named['server'] ?? null) && array_key_exists('configure', $named['server']); + if ($hasConfigure) { + $config['server']['configure'] = $named['server']['configure']; + unset($named['server']['configure']); + } + + return self::merge($config, $named); + } + + /** + * @return array> The named servers, validated. + */ + private static function named(): array + { + $servers = Configure::read('Mcp.servers') ?? []; + if (!is_array($servers)) { + throw new InvalidArgumentException('"Mcp.servers" must be an array of server name => config.'); + } + foreach ($servers as $name => $config) { + if (!is_string($name) || $name === '' || !is_array($config)) { + throw new InvalidArgumentException('"Mcp.servers" must be an array of server name => config.'); + } + if ($name === self::DEFAULT_SERVER) { + throw new InvalidArgumentException( + '"Mcp.servers.default" is not allowed: the top-level "Mcp" config is the default server.', + ); + } + if (!is_string($config['route'] ?? null) || trim($config['route'], '/') === '') { + throw new InvalidArgumentException(sprintf( + '"Mcp.servers.%s.route" must be the path of the server, for example "/mcp/%s".', + $name, + $name, + )); + } + } + + /** @var array> $servers */ + return $servers; + } + /** * The cache config used for the discovery cache, or null when it is disabled. * Always null in debug mode, so new tools show up without clearing caches. * + * @param string $server The server. * @return string|null */ - public static function discoveryCache(): ?string + public static function discoveryCache(string $server = self::DEFAULT_SERVER): ?string { - $name = self::get('discovery.cache'); + $name = self::get('discovery.cache', $server); if (Configure::read('debug') || !is_string($name) || $name === '') { return null; } @@ -106,12 +221,13 @@ public static function discoveryCache(): ?string * SDK's own limit). The same value goes to the SDK transport and to its AuthorizationMiddleware, and * BodyLimitMiddleware answers a larger body with 413 before either reads it. * + * @param string $server The server. * @return int * @throws \InvalidArgumentException When the setting is not a positive integer, so the endpoint fails closed. */ - public static function maxBodyBytes(): int + public static function maxBodyBytes(string $server = self::DEFAULT_SERVER): int { - $value = self::get('http.maxBodyBytes'); + $value = self::get('http.maxBodyBytes', $server); if (!is_int($value) || $value < 1) { throw new InvalidArgumentException('`Mcp.http.maxBodyBytes` must be a positive integer (bytes).'); } @@ -124,11 +240,12 @@ public static function maxBodyBytes(): int * `App.fullBaseUrl` plus localhost; the SDK default (localhost only) would * reject every request to a real domain. * + * @param string $server The server. * @return list */ - public static function allowedHosts(): array + public static function allowedHosts(string $server = self::DEFAULT_SERVER): array { - $hosts = self::get('http.allowedHosts'); + $hosts = self::get('http.allowedHosts', $server); if (is_array($hosts)) { return array_values(array_map(fn(mixed $host): string => strtolower((string)$host), $hosts)); } @@ -195,7 +312,7 @@ public static function rbacPermissions(): array } /** - * Whether $request is for the MCP endpoint or its protected resource metadata. Use it to skip + * Whether $request is for the endpoint of any MCP server or its protected resource metadata. Use it to skip * Cake's CSRF check there, and to keep other bearer-token authenticators off these paths. * * @param \Psr\Http\Message\ServerRequestInterface $request The request. @@ -203,14 +320,6 @@ public static function rbacPermissions(): array */ public static function isEndpoint(ServerRequestInterface $request): bool { - $route = self::get('route'); - if (!is_string($route) || trim($route, '/') === '') { - return false; - } - $route = '/' . trim($route, '/'); - $path = $request instanceof ServerRequest ? $request->getPath() : $request->getUri()->getPath(); - $path = '/' . trim($path, '/'); - - return $path === $route || $path === self::METADATA_PREFIX . $route; + return self::serverFor($request) !== null; } } diff --git a/tests/TestCase/McpConfigTest.php b/tests/TestCase/McpConfigTest.php index a367132..249aceb 100644 --- a/tests/TestCase/McpConfigTest.php +++ b/tests/TestCase/McpConfigTest.php @@ -155,6 +155,116 @@ public function testTheBodyLimitDefaultsToTheSdkLimit(): void $this->assertSame(4194304, McpConfig::get('http.maxBodyBytes')); } + public function testWithoutServersOnlyDefaultExists(): void + { + $this->assertSame(['default'], McpConfig::servers()); + $this->assertSame(McpConfig::get('route'), McpConfig::get('route', 'default')); + $this->assertArrayNotHasKey('servers', McpConfig::get()); + } + + public function testNamedServerMergesNonSecuritySectionsKeyByKey(): void + { + Configure::write('Mcp.server.version', '3.1.0'); + Configure::write('Mcp.http.maxBodyBytes', 2048); + Configure::write('Mcp.servers.admin', ['route' => '/mcp/admin', 'server' => ['name' => 'Admin MCP']]); + + $this->assertSame(['default', 'admin'], McpConfig::servers()); + $this->assertSame('/mcp/admin', McpConfig::get('route', 'admin')); + $this->assertSame('Admin MCP', McpConfig::get('server.name', 'admin')); + $this->assertSame('3.1.0', McpConfig::get('server.version', 'admin')); + $this->assertSame(2048, McpConfig::maxBodyBytes('admin')); + $this->assertArrayNotHasKey('servers', McpConfig::get(null, 'admin')); + } + + public function testSecuritySectionsAreReplacedWhole(): void + { + Configure::write('Mcp.authorization.authorizer', 'App\\Mcp\\CustomAuthorizer'); + Configure::write('Mcp.auth.scopes.tools', ['refund' => ['mcp:refund']]); + Configure::write('Mcp.discovery.excludeDirs', ['src/Mcp/Internal']); + Configure::write('Mcp.servers.admin', [ + 'route' => '/mcp/admin', + 'authorization' => ['rbac' => [['role' => 'admin']]], + 'auth' => ['scopes' => ['default' => ['mcp:admin']]], + 'discovery' => ['scanDirs' => ['src/Mcp/Admin']], + ]); + + $this->assertSame(AllowAllToolAuthorizer::class, McpConfig::get('authorization.authorizer', 'admin')); + $this->assertSame([['role' => 'admin']], McpConfig::get('authorization.rbac', 'admin')); + $this->assertSame([], McpConfig::get('auth.scopes.tools', 'admin')); + $this->assertSame(['mcp:admin'], McpConfig::get('auth.scopes.default', 'admin')); + $this->assertSame([], McpConfig::get('discovery.excludeDirs', 'admin')); + $this->assertSame(['src/Mcp/Admin'], McpConfig::get('discovery.scanDirs', 'admin')); + } + + public function testSecuritySectionsAreInheritedWhenNotSet(): void + { + Configure::write('Mcp.authorization.authorizer', 'App\\Mcp\\CustomAuthorizer'); + Configure::write('Mcp.servers.admin', ['route' => '/mcp/admin']); + + $this->assertSame('App\\Mcp\\CustomAuthorizer', McpConfig::get('authorization.authorizer', 'admin')); + $this->assertSame(['src/Mcp'], McpConfig::get('discovery.scanDirs', 'admin')); + } + + public function testServerConfigureIsReplacedOnlyWhenSet(): void + { + $hook = fn(): null => null; + $other = fn(): null => null; + Configure::write('Mcp.server.configure', $hook); + Configure::write('Mcp.servers.inherits', ['route' => '/mcp/a', 'server' => ['name' => 'A']]); + Configure::write('Mcp.servers.own', ['route' => '/mcp/b', 'server' => ['configure' => $other]]); + Configure::write('Mcp.servers.none', ['route' => '/mcp/c', 'server' => ['configure' => null]]); + + $this->assertSame($hook, McpConfig::get('server.configure', 'inherits')); + $this->assertSame($other, McpConfig::get('server.configure', 'own')); + $this->assertNull(McpConfig::get('server.configure', 'none')); + } + + public function testUnknownServerFails(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('"Mcp.servers.nope" is not configured.'); + + McpConfig::get('route', 'nope'); + } + + public function testNamedServerNeedsARoute(): void + { + Configure::write('Mcp.servers.admin', ['server' => ['name' => 'Admin']]); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('"Mcp.servers.admin.route"'); + + McpConfig::get('route', 'admin'); + } + + public function testServersCannotBeNamedDefault(): void + { + Configure::write('Mcp.servers.default', ['route' => '/other']); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('"Mcp.servers.default"'); + + McpConfig::servers(); + } + + public function testIsEndpointAndServerForMatchEveryServer(): void + { + Configure::write('Mcp.servers.admin', ['route' => '/mcp/admin']); + + $cases = [ + '/mcp' => 'default', + '/.well-known/oauth-protected-resource/mcp' => 'default', + '/mcp/admin/' => 'admin', + '/.well-known/oauth-protected-resource/mcp/admin' => 'admin', + '/api/mcp' => null, + ]; + foreach ($cases as $path => $server) { + $request = new ServerRequest(['url' => $path]); + $this->assertSame($server, McpConfig::serverFor($request), $path); + $this->assertSame($server !== null, McpConfig::isEndpoint($request), $path); + } + } + public function testTheBodyLimitMustBeAPositiveInteger(): void { Configure::write('Mcp.http.maxBodyBytes', 1024); From 6a7fad57e51770f8d724494a83f37fcf3f9ed513 Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 20:33:29 +0100 Subject: [PATCH 018/181] Settings and server factory per MCP server --- src/Audit/AuditSettings.php | 7 ++- src/Audit/AuditWriter.php | 10 +++- src/OAuth/AuthSettings.php | 14 ++++-- src/Server/ServerFactory.php | 56 +++++++++++++++------ tests/TestCase/Audit/AuditWriterTest.php | 18 +++++++ tests/TestCase/OAuth/AuthSettingsTest.php | 12 +++++ tests/TestCase/Server/ServerFactoryTest.php | 26 ++++++++++ 7 files changed, 119 insertions(+), 24 deletions(-) diff --git a/src/Audit/AuditSettings.php b/src/Audit/AuditSettings.php index 7d68006..2e10d22 100644 --- a/src/Audit/AuditSettings.php +++ b/src/Audit/AuditSettings.php @@ -34,18 +34,20 @@ private function __construct( public readonly bool $arguments, public readonly array $redact, public readonly int $maxLength, + public readonly string $server = McpConfig::DEFAULT_SERVER, ) { } /** * Reads and validates `Mcp.audit`. * + * @param string $server The MCP server whose audit settings to read. * @return self * @throws \InvalidArgumentException For an invalid setting, named in the message. */ - public static function fromConfig(): self + public static function fromConfig(string $server = McpConfig::DEFAULT_SERVER): self { - $audit = McpConfig::get('audit'); + $audit = McpConfig::get('audit', $server); if (!is_array($audit)) { throw new InvalidArgumentException('"Mcp.audit" must be an array.'); } @@ -80,6 +82,7 @@ public static function fromConfig(): self self::flag($audit['arguments'], 'arguments'), array_map('strtolower', $redact), $maxLength, + $server, ); } diff --git a/src/Audit/AuditWriter.php b/src/Audit/AuditWriter.php index da9fa23..8e91569 100644 --- a/src/Audit/AuditWriter.php +++ b/src/Audit/AuditWriter.php @@ -7,6 +7,7 @@ use Cake\Event\EventManager; use Cake\Log\Log; use CakeDC\Mcp\Log\McpLogger; +use CakeDC\Mcp\McpConfig; use Throwable; /** @@ -95,7 +96,11 @@ public function write(AuditRecord $record): void } } try { - EventManager::instance()->dispatch(new Event(self::EVENT, null, $record->toArray())); + $data = $record->toArray(); + if ($this->settings->server !== McpConfig::DEFAULT_SERVER) { + $data['server'] = $this->settings->server; + } + EventManager::instance()->dispatch(new Event(self::EVENT, null, $data)); } catch (Throwable $exception) { $this->report('a listener of the Mcp.audit event failed', $exception); } @@ -118,6 +123,9 @@ private function line(AuditRecord $record): string $this->field($record->session), $this->field($record->request), ); + if ($this->settings->server !== McpConfig::DEFAULT_SERVER) { + $line .= ' server=' . $this->field($this->settings->server); + } if ($this->settings->arguments) { $line .= ' args=' . json_encode((object)$record->arguments, self::JSON_FLAGS); } diff --git a/src/OAuth/AuthSettings.php b/src/OAuth/AuthSettings.php index 3129996..e4e985d 100644 --- a/src/OAuth/AuthSettings.php +++ b/src/OAuth/AuthSettings.php @@ -43,18 +43,20 @@ private function __construct( public readonly array $implies, public readonly ?Closure $identity, public readonly ?ExternalSettings $external, + public readonly string $server = McpConfig::DEFAULT_SERVER, ) { } /** * Reads and validates `Mcp.auth`. * + * @param string $server The MCP server whose settings to read. * @return self * @throws \InvalidArgumentException For an invalid setting, named in the message. */ - public static function fromConfig(): self + public static function fromConfig(string $server = McpConfig::DEFAULT_SERVER): self { - $auth = McpConfig::get('auth'); + $auth = McpConfig::get('auth', $server); // A non-array (null included) is a typo, never a request for the defaults: fail closed. if (!is_array($auth)) { throw new InvalidArgumentException('"Mcp.auth" must be an array.'); @@ -85,7 +87,7 @@ public static function fromConfig(): self if ($identity !== null && !is_callable($identity)) { throw new InvalidArgumentException('"Mcp.auth.identity" must be a callable or null.'); } - $resource = $mode === self::HOST ? '' : self::resource($auth['resource'] ?? null); + $resource = $mode === self::HOST ? '' : self::resource($auth['resource'] ?? null, $server); return new self( $mode, @@ -98,6 +100,7 @@ public static function fromConfig(): self self::scopeMap($scopes['implies'], 'Mcp.auth.scopes.implies'), $identity === null ? null : Closure::fromCallable($identity), $mode === self::EXTERNAL ? ExternalSettings::fromArray($external, $resource) : null, + $server, ); } @@ -181,9 +184,10 @@ public static function canonicalUrl(string $url, string $key): string * The canonical resource URL: `Mcp.auth.resource`, or the base URL, base path and `Mcp.route`. * * @param mixed $configured `Mcp.auth.resource`. + * @param string $server The server, whose route the derived resource ends with. * @return string */ - private static function resource(mixed $configured): string + private static function resource(mixed $configured, string $server): string { if ($configured !== null) { if (!is_string($configured)) { @@ -193,7 +197,7 @@ private static function resource(mixed $configured): string return self::canonicalUrl($configured, '"Mcp.auth.resource"'); } $base = Configure::read('App.base'); - $route = McpConfig::get('route'); + $route = McpConfig::get('route', $server); return self::canonicalUrl( rtrim((string)Configure::read('App.fullBaseUrl'), '/') diff --git a/src/Server/ServerFactory.php b/src/Server/ServerFactory.php index 9278624..ba2796e 100644 --- a/src/Server/ServerFactory.php +++ b/src/Server/ServerFactory.php @@ -46,13 +46,37 @@ final class ServerFactory /** * @param \Psr\Container\ContainerInterface $container The host container. * @param \CakeDC\Mcp\Identity\CurrentIdentity $identity The shared current identity. + * @param string $server The MCP server this factory builds: `default` or a key of `Mcp.servers`. */ public function __construct( private readonly ContainerInterface $container, private readonly CurrentIdentity $identity, + private readonly string $server = McpConfig::DEFAULT_SERVER, ) { } + /** + * A factory for another MCP server, with the same container and current identity. + * + * @param string $server `default` or a key of `Mcp.servers`. + * @return self + * @throws \InvalidArgumentException When the server is not configured. + */ + public function forServer(string $server): self + { + McpConfig::get('route', $server); + + return new self($this->container, $this->identity, $server); + } + + /** + * @return string The MCP server this factory builds. + */ + public function server(): string + { + return $this->server; + } + /** * @return \CakeDC\Mcp\Identity\CurrentIdentity */ @@ -80,13 +104,13 @@ private function build(bool $trusted, LoggerInterface $logger): Server $gate = new ToolGate($this->authorizer(), $this->identity, $trusted); $events = new EventDispatcher(); $events->listen(ResponseEvent::class, new ToolListFilter($gate)); - if (McpConfig::get('schema.normalize') === true) { + if (McpConfig::get('schema.normalize', $this->server) === true) { // After the filter, on the tools the caller may see. $events->listen(ResponseEvent::class, new ToolSchemaNormalizer()); } // The guard goes first: the SDK asks request handlers in the order they were added. $builder = Server::builder()->addRequestHandler(new ToolCallGuard($gate)); - $audit = AuditSettings::fromConfig(); + $audit = AuditSettings::fromConfig($this->server); if ($audit->enabled) { // The audit needs to know which tools exist, to tell a denied tool from an unknown one: it keeps // the registry. Set before the host hook, which may still replace it (the audit then falls back @@ -108,8 +132,8 @@ private function build(bool $trusted, LoggerInterface $logger): Server // Set after the host hook, so the hook cannot drop the tool list filter or replace these. $builder ->setServerInfo( - (string)McpConfig::get('server.name'), - (string)McpConfig::get('server.version'), + (string)McpConfig::get('server.name', $this->server), + (string)McpConfig::get('server.version', $this->server), $this->optionalString('server.description'), websiteUrl: $this->optionalString('server.websiteUrl'), title: $this->optionalString('server.title'), @@ -118,28 +142,28 @@ private function build(bool $trusted, LoggerInterface $logger): Server ->setLogger($logger) ->setEventDispatcher($events) ->setSession(new Psr16SessionStore( - Cache::pool((string)McpConfig::get('session.cache')), - 'mcp-', - (int)McpConfig::get('session.ttl'), + Cache::pool((string)McpConfig::get('session.cache', $this->server)), + $this->server === McpConfig::DEFAULT_SERVER ? 'mcp-' : 'mcp-' . $this->server . '-', + (int)McpConfig::get('session.ttl', $this->server), )); - $cachePolicy = CacheHints::fromConfig(McpConfig::get('server.cache')); + $cachePolicy = CacheHints::fromConfig(McpConfig::get('server.cache', $this->server)); if ($cachePolicy !== null) { $builder->setCachePolicy($cachePolicy); } - $instructions = McpConfig::get('server.instructions'); + $instructions = McpConfig::get('server.instructions', $this->server); if (is_string($instructions) && $instructions !== '') { $builder->setInstructions($instructions); } - $scanDirs = $this->existingDirs((array)McpConfig::get('discovery.scanDirs')); + $scanDirs = $this->existingDirs((array)McpConfig::get('discovery.scanDirs', $this->server)); if ($scanDirs !== []) { - $cache = McpConfig::discoveryCache(); + $cache = McpConfig::discoveryCache($this->server); $builder->setDiscovery( rtrim(ROOT, DS), $scanDirs, - array_values(array_filter((array)McpConfig::get('discovery.excludeDirs'), 'is_string')), + array_values(array_filter((array)McpConfig::get('discovery.excludeDirs', $this->server), 'is_string')), $cache !== null ? Cache::pool($cache) : null, ); } @@ -156,7 +180,7 @@ private function build(bool $trusted, LoggerInterface $logger): Server */ private function configure(Builder $builder): void { - $configure = McpConfig::get('server.configure'); + $configure = McpConfig::get('server.configure', $this->server); if ($configure === null) { return; } @@ -175,7 +199,7 @@ private function configure(Builder $builder): void */ private function optionalString(string $path): ?string { - $value = McpConfig::get($path); + $value = McpConfig::get($path, $this->server); return is_string($value) && $value !== '' ? $value : null; } @@ -278,12 +302,12 @@ public function log(mixed $level, string|Stringable $message, array $context = [ */ public function authorizer(): ToolAuthorizerInterface { - $authorizer = McpConfig::get('authorization.authorizer'); + $authorizer = McpConfig::get('authorization.authorizer', $this->server); if ($authorizer instanceof ToolAuthorizerInterface) { return $authorizer; } if ($authorizer === RbacToolAuthorizer::class) { - return new RbacToolAuthorizer((array)McpConfig::get('authorization.rbac')); + return new RbacToolAuthorizer((array)McpConfig::get('authorization.rbac', $this->server)); } if (is_string($authorizer) && is_subclass_of($authorizer, ToolAuthorizerInterface::class)) { $instance = (new ContainerBridge($this->container))->get($authorizer); diff --git a/tests/TestCase/Audit/AuditWriterTest.php b/tests/TestCase/Audit/AuditWriterTest.php index 6d490f5..2919944 100644 --- a/tests/TestCase/Audit/AuditWriterTest.php +++ b/tests/TestCase/Audit/AuditWriterTest.php @@ -100,6 +100,24 @@ public function testWritesOneLineWithTheRecord(): void ); } + public function testNamedServerRecordsCarryTheServer(): void + { + Configure::write('Mcp.servers.admin', ['route' => '/mcp/admin']); + + (new AuditWriter(AuditSettings::fromConfig('admin')))->write($this->record()); + + $this->assertStringContainsString(' request=2 server=admin args=', $this->lines()[0]); + $this->assertSame('admin', $this->events[0]->getData()['server'] ?? null); + } + + public function testDefaultServerRecordsHaveNoServerField(): void + { + $this->writer()->write($this->record()); + + $this->assertStringNotContainsString('server=', $this->lines()[0]); + $this->assertArrayNotHasKey('server', $this->events[0]->getData()); + } + public function testClientTextCannotForgeLinesOrPlaceholders(): void { $writer = $this->writer(); diff --git a/tests/TestCase/OAuth/AuthSettingsTest.php b/tests/TestCase/OAuth/AuthSettingsTest.php index 4a09351..dc56be5 100644 --- a/tests/TestCase/OAuth/AuthSettingsTest.php +++ b/tests/TestCase/OAuth/AuthSettingsTest.php @@ -67,6 +67,18 @@ public function testResourceDerivesFromTheBaseUrlAndTheRoute(): void $this->assertSame('https://example.com/mcp', AuthSettings::fromConfig()->resource); } + public function testNamedServerDerivesItsResourceFromItsRoute(): void + { + Configure::write('App.fullBaseUrl', 'https://example.com'); + Configure::write('Mcp.servers.admin', ['route' => '/mcp/admin', 'auth' => ['mode' => 'oauth']]); + + $settings = AuthSettings::fromConfig('admin'); + + $this->assertSame('https://example.com/mcp/admin', $settings->resource); + $this->assertSame('admin', $settings->server); + $this->assertSame('host', AuthSettings::fromConfig()->mode); + } + public function testResourceKeepsTheBasePathOfASubdirectoryInstall(): void { Configure::write('App.fullBaseUrl', 'https://example.com'); diff --git a/tests/TestCase/Server/ServerFactoryTest.php b/tests/TestCase/Server/ServerFactoryTest.php index 0f81123..c462ed6 100644 --- a/tests/TestCase/Server/ServerFactoryTest.php +++ b/tests/TestCase/Server/ServerFactoryTest.php @@ -142,6 +142,32 @@ public function testInstructionsAreAnnouncedOnInitialize(): void $this->assertSame('Use echo to test.', $result['instructions'] ?? null); } + public function testForServerUsesThatServersToolsAndInfo(): void + { + Configure::write('Mcp.servers.admin', [ + 'route' => '/mcp/admin', + 'discovery' => ['scanDirs' => ['src/McpDocs']], + 'server' => ['name' => 'Admin MCP'], + ]); + $this->factory = $this->factory->forServer('admin'); + + $transport = $this->runServer(); + $names = $this->toolNames($transport); + + $this->assertSame('admin', $this->factory->server()); + $this->assertContains('find_order', $names); + $this->assertNotContains('echo', $names); + $this->assertSame('Admin MCP', $transport->responseFor(1)['result']['serverInfo']['name'] ?? null); + } + + public function testForServerRejectsAnUnknownName(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('"Mcp.servers.nope" is not configured.'); + + $this->factory->forServer('nope'); + } + public function testServerInfoFromConfig(): void { Configure::write('Mcp.server', [ From 1f4f525cfc5c9e3d1dca24ed5bff0eae6bf8224b Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 20:35:32 +0100 Subject: [PATCH 019/181] Serve several MCP servers from one application --- src/Controller/McpController.php | 26 ++- .../ProtectedResourceController.php | 6 +- src/Controller/ResolvesServerTrait.php | 30 +++ src/McpPlugin.php | 43 +++-- tests/TestCase/Controller/McpServersTest.php | 177 ++++++++++++++++++ 5 files changed, 254 insertions(+), 28 deletions(-) create mode 100644 src/Controller/ResolvesServerTrait.php create mode 100644 tests/TestCase/Controller/McpServersTest.php diff --git a/src/Controller/McpController.php b/src/Controller/McpController.php index 8f8268a..fbcd65e 100644 --- a/src/Controller/McpController.php +++ b/src/Controller/McpController.php @@ -36,6 +36,7 @@ */ class McpController extends Controller { + use ResolvesServerTrait; use SkipsHostAuthorizationTrait; /** @@ -48,16 +49,21 @@ public function handle(ServerFactory $factory, CurrentIdentity $identity): Respo $this->skipHostAuthorization(); // A long-running worker reuses the container: no request starts with the previous one's identity. $identity->set(null); + $server = $this->mcpServer(); + if ($server === null) { + return $this->response->withStatus(404); + } + $factory = $factory->forServer($server); $responseFactory = new ResponseFactory(); $streamFactory = new StreamFactory(); try { - $maxBodyBytes = McpConfig::maxBodyBytes(); - $origins = array_values(array_filter((array)McpConfig::get('http.allowedOrigins'), 'is_string')); + $maxBodyBytes = McpConfig::maxBodyBytes($server); + $origins = array_values(array_filter((array)McpConfig::get('http.allowedOrigins', $server), 'is_string')); $middleware = [ new CorsMiddleware($origins), new DnsRebindingProtectionMiddleware( - McpConfig::allowedHosts(), + McpConfig::allowedHosts($server), $origins, $responseFactory, $streamFactory, @@ -66,12 +72,12 @@ public function handle(ServerFactory $factory, CurrentIdentity $identity): Respo // Bearer challenge. new BodyLimitMiddleware($maxBodyBytes, $responseFactory, $streamFactory), ]; - $audit = AuditSettings::fromConfig(); + $audit = AuditSettings::fromConfig($server); if ($audit->enabled) { // Right before authentication, to record the calls it refuses. $middleware[] = new AuditRefusalMiddleware($audit, new AuditWriter($audit), $identity); } - $middleware[] = $this->authentication($identity, $responseFactory, $streamFactory, $maxBodyBytes); + $middleware[] = $this->authentication($server, $identity, $responseFactory, $streamFactory, $maxBodyBytes); $transport = new StreamableHttpTransport( $this->request, $responseFactory, @@ -94,6 +100,7 @@ public function handle(ServerFactory $factory, CurrentIdentity $identity): Respo * The middleware that identifies the caller: the host's identity in host mode, an OAuth access * token otherwise. Invalid settings throw, so the endpoint fails closed. * + * @param string $server The MCP server. * @param \CakeDC\Mcp\Identity\CurrentIdentity $identity Shared with the tools. * @param \Cake\Http\ResponseFactory $responseFactory For its responses. * @param \Cake\Http\StreamFactory $streamFactory For their bodies. @@ -101,12 +108,13 @@ public function handle(ServerFactory $factory, CurrentIdentity $identity): Respo * @return \Psr\Http\Server\MiddlewareInterface */ private function authentication( + string $server, CurrentIdentity $identity, ResponseFactory $responseFactory, StreamFactory $streamFactory, int $maxBodyBytes, ): MiddlewareInterface { - $settings = AuthSettings::fromConfig(); + $settings = AuthSettings::fromConfig($server); if ($settings->mode !== AuthSettings::HOST) { return (new ResourceServer($settings))->middleware( $identity, @@ -115,14 +123,14 @@ private function authentication( $maxBodyBytes, ); } - $scopes = McpConfig::get('identity.scopes'); + $scopes = McpConfig::get('identity.scopes', $server); return new IdentityMiddleware( $identity, $responseFactory, $streamFactory, - McpConfig::get('identity.required') !== false, - (string)McpConfig::get('identity.attribute'), + McpConfig::get('identity.required', $server) !== false, + (string)McpConfig::get('identity.attribute', $server), is_callable($scopes) ? Closure::fromCallable($scopes) : null, ); } diff --git a/src/Controller/ProtectedResourceController.php b/src/Controller/ProtectedResourceController.php index 6d87046..740858e 100644 --- a/src/Controller/ProtectedResourceController.php +++ b/src/Controller/ProtectedResourceController.php @@ -18,6 +18,7 @@ */ class ProtectedResourceController extends Controller { + use ResolvesServerTrait; use SkipsHostAuthorizationTrait; private const CORS = [ @@ -42,8 +43,9 @@ public function metadata(): Response } try { - $settings = AuthSettings::fromConfig(); - if ($settings->mode === AuthSettings::HOST) { + $server = $this->mcpServer(); + $settings = $server === null ? null : AuthSettings::fromConfig($server); + if ($settings === null || $settings->mode === AuthSettings::HOST) { return $response->withStatus(404) ->withType('application/json') ->withStringBody((string)json_encode(['error' => 'not_found'])); diff --git a/src/Controller/ResolvesServerTrait.php b/src/Controller/ResolvesServerTrait.php new file mode 100644 index 0000000..1382426 --- /dev/null +++ b/src/Controller/ResolvesServerTrait.php @@ -0,0 +1,30 @@ +request->getParam('server'); + $server = is_string($server) && $server !== '' ? $server : McpConfig::DEFAULT_SERVER; + try { + McpConfig::get('route', $server); + } catch (InvalidArgumentException) { + return null; + } + + return $server; + } +} diff --git a/src/McpPlugin.php b/src/McpPlugin.php index 5d024e9..bb2d223 100644 --- a/src/McpPlugin.php +++ b/src/McpPlugin.php @@ -33,10 +33,14 @@ public function bootstrap(PluginApplicationInterface $app): void { parent::bootstrap($app); - $caches = [McpConfig::get('discovery.cache'), McpConfig::get('session.cache')]; - if (McpConfig::get('auth.mode') === AuthSettings::EXTERNAL) { - // Discovery metadata and signing keys of the external authorization server. - $caches[] = McpConfig::get('auth.external.cache'); + $caches = []; + foreach (McpConfig::servers() as $server) { + $caches[] = McpConfig::get('discovery.cache', $server); + $caches[] = McpConfig::get('session.cache', $server); + if (McpConfig::get('auth.mode', $server) === AuthSettings::EXTERNAL) { + // Discovery metadata and signing keys of the external authorization server. + $caches[] = McpConfig::get('auth.external.cache', $server); + } } foreach ($caches as $name) { if (!is_string($name) || $name === '' || Cache::getConfig($name) !== null) { @@ -60,20 +64,25 @@ public function bootstrap(PluginApplicationInterface $app): void */ public function routes(RouteBuilder $routes): void { - $path = McpConfig::get('route'); - if (!is_string($path) || $path === '') { - return; + foreach (McpConfig::servers() as $server) { + $path = McpConfig::get('route', $server); + if (!is_string($path) || $path === '') { + continue; + } + // The default server keeps the 2.1 routes, without a `server` param, so reverse routing to them still + // matches; the controllers read a missing param as `default`. + $param = $server === McpConfig::DEFAULT_SERVER ? [] : ['server' => $server]; + $routes->connect( + $path, + ['plugin' => 'CakeDC/Mcp', 'controller' => 'Mcp', 'action' => 'handle'] + $param, + )->setMethods(['GET', 'POST', 'DELETE', 'OPTIONS']); + // Always connected: routes are cached, and a mode switch must not need a cache clear. + // In host mode the controller answers 404. + $routes->connect( + McpConfig::METADATA_PREFIX . '/' . ltrim($path, '/'), + ['plugin' => 'CakeDC/Mcp', 'controller' => 'ProtectedResource', 'action' => 'metadata'] + $param, + )->setMethods(['GET', 'OPTIONS']); } - - $routes->connect($path, ['plugin' => 'CakeDC/Mcp', 'controller' => 'Mcp', 'action' => 'handle']) - ->setMethods(['GET', 'POST', 'DELETE', 'OPTIONS']); - - // Always connected: routes are cached, and a mode switch must not need a cache clear. - // In host mode the controller answers 404. - $routes->connect( - McpConfig::METADATA_PREFIX . '/' . ltrim($path, '/'), - ['plugin' => 'CakeDC/Mcp', 'controller' => 'ProtectedResource', 'action' => 'metadata'], - )->setMethods(['GET', 'OPTIONS']); } /** diff --git a/tests/TestCase/Controller/McpServersTest.php b/tests/TestCase/Controller/McpServersTest.php new file mode 100644 index 0000000..9a491be --- /dev/null +++ b/tests/TestCase/Controller/McpServersTest.php @@ -0,0 +1,177 @@ + ArrayEngine::class]); + Configure::write('Mcp.servers.admin', [ + 'route' => '/mcp/admin', + 'discovery' => ['scanDirs' => ['src/McpDocs']], + 'server' => ['name' => 'Admin MCP'], + ]); + } + + protected function tearDown(): void + { + Cache::drop('mcp_oauth_test'); + Router::reload(); + parent::tearDown(); + } + + public function testEachServerListsItsOwnTools(): void + { + $default = $this->listTools('/mcp'); + $admin = $this->listTools('/mcp/admin'); + + $this->assertContains('echo', $default); + $this->assertNotContains('find_order', $default); + $this->assertContains('find_order', $admin); + $this->assertNotContains('echo', $admin); + } + + public function testANamedServerWithoutAuthorizationInheritsTheDefaultAuthorizer(): void + { + Configure::write('Mcp.authorization.authorizer', new class implements ToolAuthorizerInterface { + public function canCall(mixed $identity, string $tool): bool + { + return $tool !== 'find_order'; + } + }); + + $this->assertNotContains('find_order', $this->listTools('/mcp/admin')); + $headers = $this->session('/mcp/admin'); + $this->mcp('/mcp/admin', $this->call(3, 'find_order', ['number' => 'A-1']), $headers); + $this->assertSame('Tool not found: "find_order".', $this->json()['error']['message'] ?? null); + } + + public function testSessionsDoNotCrossServers(): void + { + $headers = $this->session('/mcp'); + + $this->mcp('/mcp/admin', ['jsonrpc' => '2.0', 'id' => 2, 'method' => 'tools/list'], $headers); + + $this->assertResponseCode(404); + } + + public function testEachServerHasItsMetadataRoute(): void + { + Configure::write('Mcp.servers.admin.auth', [ + 'mode' => 'external', + 'external' => ['issuer' => TestJwt::ISSUER, 'cache' => 'mcp_oauth_test', 'httpClient' => TestJwt::client()], + ]); + + $this->get('/.well-known/oauth-protected-resource/mcp/admin'); + + $this->assertResponseOk(); + $document = json_decode((string)$this->_response->getBody(), true); + $this->assertSame('http://localhost/mcp/admin', $document['resource'] ?? null); + $this->assertSame([TestJwt::ISSUER], $document['authorization_servers'] ?? null); + + $this->get('/.well-known/oauth-protected-resource/mcp'); + $this->assertResponseCode(404); + } + + public function testA21ConfigStillServesMcp(): void + { + Configure::delete('Mcp.servers'); + + $this->assertContains('echo', $this->listTools('/mcp')); + // No route: the test application answers unknown paths with its error page, never an MCP answer. + $this->mcp('/mcp/admin', ['jsonrpc' => '2.0', 'id' => 1, 'method' => 'tools/list']); + $this->assertResponseError(); + $this->assertArrayNotHasKey('jsonrpc', $this->json()); + } + + /** + * @return list + */ + private function listTools(string $path): array + { + $headers = $this->session($path); + $this->mcp($path, ['jsonrpc' => '2.0', 'id' => 2, 'method' => 'tools/list'], $headers); + $this->assertResponseOk(); + + return array_column($this->json()['result']['tools'] ?? [], 'name'); + } + + /** + * @return array The headers of an initialized session on $path. + */ + private function session(string $path): array + { + $this->mcp($path, ['jsonrpc' => '2.0', 'id' => 1, 'method' => 'initialize', 'params' => [ + 'protocolVersion' => self::HANDSHAKE, + 'capabilities' => new stdClass(), + 'clientInfo' => ['name' => 'test', 'version' => '1.0'], + ]]); + $this->assertResponseOk(); + $headers = [ + 'Mcp-Session-Id' => $this->_response->getHeaderLine('Mcp-Session-Id'), + 'MCP-Protocol-Version' => self::HANDSHAKE, + ]; + $this->mcp($path, ['jsonrpc' => '2.0', 'method' => 'notifications/initialized'], $headers); + + return $headers; + } + + /** + * @param array $arguments + * @return array + */ + private function call(int $id, string $tool, array $arguments): array + { + return ['jsonrpc' => '2.0', 'id' => $id, 'method' => 'tools/call', 'params' => [ + 'name' => $tool, + 'arguments' => $arguments, + ]]; + } + + /** + * @param array $message + * @param array $headers + */ + private function mcp(string $path, array $message, array $headers = []): void + { + $headers += [ + 'Host' => 'localhost', + 'Accept' => 'application/json, text/event-stream', + 'Content-Type' => 'application/json', + 'Authorization' => 'Bearer ' . TestTokens::EDITOR, + ]; + $this->configRequest(['headers' => $headers]); + $this->post($path, (string)json_encode($message)); + } + + /** + * @return array + */ + private function json(): array + { + $decoded = json_decode((string)$this->_response->getBody(), true); + + return is_array($decoded) ? $decoded : []; + } +} From 9b51fb703a5be4405a6622402aa0dc8189feebad Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 20:36:03 +0100 Subject: [PATCH 020/181] Bake: accept the Plugin.Name form --- src/Bake/McpBakeCommand.php | 4 +++- tests/TestCase/Command/Bake/McpBakeCommandsTest.php | 11 +++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/Bake/McpBakeCommand.php b/src/Bake/McpBakeCommand.php index c549fbc..7360c43 100644 --- a/src/Bake/McpBakeCommand.php +++ b/src/Bake/McpBakeCommand.php @@ -55,7 +55,9 @@ public function template(): string */ public function templateData(Arguments $arguments): array { - $name = $this->baseName(Inflector::camelize((string)$arguments->getArgumentAt(0))); + // `Plugin.Name` names the plugin too; execute() already took the plugin from it. + [, $raw] = pluginSplit((string)$arguments->getArgumentAt(0)); + $name = $this->baseName(Inflector::camelize($raw)); return parent::templateData($arguments) + [ 'className' => $this->className($name), diff --git a/tests/TestCase/Command/Bake/McpBakeCommandsTest.php b/tests/TestCase/Command/Bake/McpBakeCommandsTest.php index eeafcb2..8d8948e 100644 --- a/tests/TestCase/Command/Bake/McpBakeCommandsTest.php +++ b/tests/TestCase/Command/Bake/McpBakeCommandsTest.php @@ -69,6 +69,17 @@ public function testBakesAToolAndItsTest(): void $this->assertStringContainsString("mcpCallTool('list_orders'", $test); } + public function testThePluginDotNameForm(): void + { + $this->exec('bake mcp_tool BakeTarget.ListOrders --force'); + + $this->assertExitSuccess(); + $class = $this->baked('src/Mcp/ListOrdersTool.php'); + $this->assertStringContainsString('class ListOrdersTool', $class); + $this->assertStringContainsString("name: 'list_orders'", $class); + $this->assertFileExists(self::PLUGIN . 'tests/TestCase/Mcp/ListOrdersToolTest.php'); + } + public function testTheSuffixIsNotDoubled(): void { $this->exec('bake mcp_tool ListOrdersTool --plugin BakeTarget --force --no-test'); From 21c20521219122581b5526f799e013b08300d35b Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 20:36:10 +0100 Subject: [PATCH 021/181] Docs: a list is structured content too for 2026-07-28 clients --- docs/tools.md | 6 +++--- tests/TestCase/Controller/McpControllerTest.php | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/docs/tools.md b/docs/tools.md index acd1566..1158e00 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -79,7 +79,7 @@ What a tool returns decides what the client receives: |---|---| | a string | that text | | an associative array | the array as pretty-printed JSON text, and the same array as `structuredContent` | -| a list (`['A-1', 'A-2']`) | the list as pretty-printed JSON text, without `structuredContent` | +| a list (`['A-1', 'A-2']`) | the list as pretty-printed JSON text. Clients of the 2026-07-28 protocol revision also get it as `structuredContent` (a JSON array); clients of the 2025 revisions do not, since that field had to be an object there | | a `Mcp\Schema\Result\CallToolResult` | exactly its content and `structuredContent` | An associative array is the quickest way to return data: @@ -114,8 +114,8 @@ class OrderTools } ``` -The array travels twice, as text and as `structuredContent`, and the model may -read both. That is fine for a small result. For a large one, return a single +The array travels twice, as text and as `structuredContent` (a list too, for +clients of the 2026-07-28 revision), and the model may read both. That is fine for a small result. For a large one, return a single compact JSON text instead, so the model reads it once: ```php diff --git a/tests/TestCase/Controller/McpControllerTest.php b/tests/TestCase/Controller/McpControllerTest.php index 5c18f54..8afe413 100644 --- a/tests/TestCase/Controller/McpControllerTest.php +++ b/tests/TestCase/Controller/McpControllerTest.php @@ -106,6 +106,20 @@ public function testHandshakeEraHasNoCacheHints(): void $this->assertArrayNotHasKey('ttlMs', $this->json()['result'] ?? []); } + public function testModernEraSendsAListAsStructuredContentToo(): void + { + // docs/tools.md, Results: under 2026-07-28 a list also travels as structuredContent. + Configure::write('Mcp.discovery.scanDirs', ['src/McpDocs']); + + $this->mcp( + $this->modern(1, 'tools/call', ['name' => 'order_numbers', 'arguments' => new stdClass()]), + $this->modernHeaders('tools/call', 'order_numbers'), + ); + + $this->assertResponseOk(); + $this->assertSame(['A-1', 'A-2'], $this->json()['result']['structuredContent'] ?? null); + } + public function testJsonBodyIsReadAfterBodyParserMiddleware(): void { $this->mcp( From 38747dcb256ace5e101adcfdaf5a61a267b85789 Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 20:36:45 +0100 Subject: [PATCH 022/181] mcp check: warn about public cache hints on per-user results --- docs/configuration.md | 2 +- src/Command/McpCheckCommand.php | 29 +++++++++++++++++++ .../TestCase/Command/McpCheckCommandTest.php | 27 +++++++++++++++++ 3 files changed, 57 insertions(+), 1 deletion(-) diff --git a/docs/configuration.md b/docs/configuration.md index 376bf55..80a78f1 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -49,7 +49,7 @@ want to change; everything else keeps its default. These are the defaults - `server.name`, `server.version`: reported to clients in the `initialize` result. - `server.title`, `server.description`, `server.websiteUrl`: optional, also reported to clients. `null` sends none. - `server.instructions`: optional text telling the client's model how to use your server. `null` sends none. -- `server.cache`: the cache hints of the 2026-07-28 protocol revision, which tell a client how long it may keep a result of `server/discover`, `tools/list`, `prompts/list`, `resources/list`, `resources/templates/list` and `resources/read`. `null` (the default) marks them private and not to be cached. Otherwise an array: `ttl` in milliseconds (default `0`), `scope` `'private'` (one user, the default) or `'public'` (any user, only for results that are the same for everyone), and `methods` to set them per method, for example `['ttl' => 60000, 'methods' => ['tools/list' => ['ttl' => 300000]]]`. Clients of the older revisions get no hints. Keep `tools/list` private when the authorizer gives each user different tools. +- `server.cache`: the cache hints of the 2026-07-28 protocol revision, which tell a client how long it may keep a result of `server/discover`, `tools/list`, `prompts/list`, `resources/list`, `resources/templates/list` and `resources/read`. `null` (the default) marks them private and not to be cached. Otherwise an array: `ttl` in milliseconds (default `0`), `scope` `'private'` (one user, the default) or `'public'` (any user, only for results that are the same for everyone), and `methods` to set them per method, for example `['ttl' => 60000, 'methods' => ['tools/list' => ['ttl' => 300000]]]`. Clients of the older revisions get no hints. A top-level `scope` applies to all six methods, so use `'public'` only per method, for results that are the same for every user: keep `tools/list` private when the authorizer gives users different tools, and `resources/read` private when a resource depends on who reads it. `bin/cake mcp check` warns, on its `Cache hints` line, when either is public. - `server.configure`: optional callable that receives the SDK `Mcp\Server\Builder` before the server is built. See [Using the SDK builder](#using-the-sdk-builder). - `discovery.scanDirs`: directories (relative to `ROOT`) scanned for attributes. Missing directories are skipped. - `discovery.excludeDirs`: directories to skip while scanning. diff --git a/src/Command/McpCheckCommand.php b/src/Command/McpCheckCommand.php index 3bfdb60..8121f09 100644 --- a/src/Command/McpCheckCommand.php +++ b/src/Command/McpCheckCommand.php @@ -33,9 +33,11 @@ use CakeDC\Mcp\OAuth\AuthSettings; use CakeDC\Mcp\OAuth\ResourceServer; use CakeDC\Mcp\Schema\SchemaLint; +use CakeDC\Mcp\Server\CacheHints; use CakeDC\Mcp\Server\ServerFactory; use CakeDC\OAuthServer\Authenticator\TokenAuthenticator; use CakeDC\OAuthServer\OAuthServer; +use Mcp\Schema\Enum\CacheScope; use ReflectionProperty; use Symfony\Component\Finder\Finder; use Throwable; @@ -125,6 +127,7 @@ protected function checks(): array 'Tool schemas' => fn(): array => $this->toolSchemas(), 'Authorizer' => fn(): array => $this->authorizerCheck(), 'Tool scopes' => fn(): array => $this->toolScopes(), + 'Cache hints' => fn(): array => $this->cacheHints(), 'Logging' => fn(): array => $this->logging(), 'Audit' => fn(): array => $this->audit(), ]; @@ -718,6 +721,32 @@ private static function within(string $path, array $prefixes): bool return false; } + /** + * @return array{0: 'pass'|'warn'|'fail', 1: string} + */ + private function cacheHints(): array + { + $policy = CacheHints::fromConfig(McpConfig::get('server.cache')); + if ($policy === null) { + return ['pass', 'off (private, not cached)']; + } + $warnings = []; + $perUser = !$this->factory()->authorizer() instanceof AllowAllToolAuthorizer; + if ($perUser && $policy->scopeFor('tools/list') === CacheScope::Public) { + $warnings[] = 'tools/list is public, but the authorizer can give each user different tools, so a shared ' + . 'cache could show one user the tool list of another'; + } + if ($policy->scopeFor('resources/read') === CacheScope::Public) { + $warnings[] = 'resources/read is public: only right when every resource reads the same for every user'; + } + if ($warnings !== []) { + return ['warn', implode('; ', $warnings) . '. Set those methods to private in Mcp.server.cache.methods, see ' + . self::DOCS . 'configuration.md#keys']; + } + + return ['pass', sprintf('ttl %d ms', $policy->ttlFor('tools/list'))]; + } + /** * Whether cakedc/cakephp-oauth-server is installed. * diff --git a/tests/TestCase/Command/McpCheckCommandTest.php b/tests/TestCase/Command/McpCheckCommandTest.php index 6c9d94b..1de8630 100644 --- a/tests/TestCase/Command/McpCheckCommandTest.php +++ b/tests/TestCase/Command/McpCheckCommandTest.php @@ -521,6 +521,33 @@ public function testAnAuthenticatorThatLeavesTheMcpEndpointAlonePasses(): void $this->assertOutputContains('[PASS] Authenticators'); } + public function testCacheHintsOffPass(): void + { + $this->exec('mcp check'); + + $this->assertOutputContains('[PASS] Cache hints: off (private, not cached)'); + } + + public function testPublicToolListWithAnAuthorizerWarns(): void + { + Configure::write('Mcp.authorization.authorizer', RbacToolAuthorizer::class); + Configure::write('Mcp.server.cache', ['ttl' => 60000, 'scope' => 'public']); + + $this->exec('mcp check'); + + $this->assertOutputContains('[WARN] Cache hints: tools/list is public'); + $this->assertOutputContains('resources/read is public'); + } + + public function testPublicHintsOnlyForMethodsThatAreTheSameForEveryonePass(): void + { + Configure::write('Mcp.server.cache', ['ttl' => 60000, 'methods' => ['prompts/list' => ['scope' => 'public']]]); + + $this->exec('mcp check'); + + $this->assertOutputContains('[PASS] Cache hints: ttl 60000 ms'); + } + public function testDiscoveryPassesWithFinder(): void { $this->exec('mcp check'); From 30913d864040aa5e2b4dbe25f57b8ce96253930b Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 20:37:01 +0100 Subject: [PATCH 023/181] Keep the cache hints check within the line length --- src/Command/McpCheckCommand.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Command/McpCheckCommand.php b/src/Command/McpCheckCommand.php index 8121f09..948403b 100644 --- a/src/Command/McpCheckCommand.php +++ b/src/Command/McpCheckCommand.php @@ -740,7 +740,8 @@ private function cacheHints(): array $warnings[] = 'resources/read is public: only right when every resource reads the same for every user'; } if ($warnings !== []) { - return ['warn', implode('; ', $warnings) . '. Set those methods to private in Mcp.server.cache.methods, see ' + return ['warn', implode('; ', $warnings) + . '. Set those methods to private in Mcp.server.cache.methods, see ' . self::DOCS . 'configuration.md#keys']; } From 2094c86d296ec97779fbe86fcf858d0c9bf06221 Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 20:40:03 +0100 Subject: [PATCH 024/181] Commands, test trait and docs for several MCP servers --- CHANGELOG.md | 2 + docs/configuration.md | 44 ++++++ docs/stdio.md | 3 + docs/testing.md | 10 ++ src/Command/McpCheckCommand.php | 140 +++++++++++++++--- src/Command/McpInspectorCommand.php | 23 ++- src/Command/McpServerCommand.php | 28 +++- src/TestSuite/McpTestTrait.php | 21 ++- .../TestCase/Command/McpCheckCommandTest.php | 66 +++++++++ .../Command/McpInspectorCommandTest.php | 18 +++ .../TestCase/Command/McpServerCommandTest.php | 23 +++ tests/TestCase/TestSuite/McpTestTraitTest.php | 14 ++ 12 files changed, 365 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cb644f5..fae42fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +- Several MCP servers in one application (`Mcp.servers`): each with its route, metadata route, tools, auth and authorizer; security sections are replaced whole, the rest inherited key by key. `mcp check` checks every server and fails on a shared route or resource; `mcp check`, `mcp server` and `mcp inspector` take `--server`; `McpTestTrait::mcpUseServer()`. +- `bin/cake mcp check` warns, on a new `Cache hints` line, when `tools/list` is public with a per-user authorizer or `resources/read` is public. - `Mcp.schema.normalize`, off by default: when on, `tools/list` drops `"null"` from the `type` and `enum` of optional parameters whose default is `null`, and that default, for hosts that reject type arrays. Arguments are still validated against the original schema. See Input schemas in `docs/tools.md`. - `bin/cake mcp check` warns, on a new `Tool schemas` line, about type arrays, arrays without an item type and optional parameters without a description. - `bin/cake mcp check` fails, on a new `Discovery` line, when `Mcp.discovery.scanDirs` is set and `symfony/finder` is missing: the SDK then skips discovery and the server has no tools. diff --git a/docs/configuration.md b/docs/configuration.md index 80a78f1..7d48db5 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -149,6 +149,50 @@ If you set a cache policy, keep `tools/list` private unless every caller sees the same tools. With an authorizer, the list depends on who asks, and a `CacheScope::Public` hint lets shared caches serve one user's list to others. +## Several servers + +One application can serve several MCP servers, each on its own route with its own +tools, authentication and authorizer. The top-level `Mcp` config is the server +named `default`; `Mcp.servers` adds more: + +```php +'Mcp' => [ + // The default server, at /mcp: what every user may do. + 'route' => '/mcp', + 'authorization' => ['authorizer' => RbacToolAuthorizer::class], + 'servers' => [ + 'admin' => [ + 'route' => '/mcp/admin', + 'server' => ['name' => 'Back office'], + 'discovery' => ['scanDirs' => ['src/Mcp/Admin']], + 'auth' => ['mode' => 'oauth', 'scopes' => ['default' => ['admin']]], + ], + ], +], +``` + +Each named server needs a `route`. What it does not set comes from the default +server, in two ways: + +- `auth`, `authorization`, `discovery` and `server.configure` are replaced whole + when the named server sets them, starting again from the plugin's defaults. A + narrower server never picks up the default server's scopes, rules, tool + directories or code-registered tools by accident. When it does not set them, + it uses the default server's. +- Every other section (`server`, `http`, `identity`, `session`, `stdio`, + `audit`, `schema`) is merged key by key, so `'server' => ['name' => ...]` + keeps the default server's version and instructions. + +Every server gets its endpoint and, in `oauth` and `external` modes, its +protected resource metadata at `/.well-known/oauth-protected-resource` plus its +route. Its resource defaults to its own URL, so a token issued for one server is +not accepted by another. Sessions are kept apart, and audit records of a named +server carry a `server` field (`server=admin` on the log line). + +`bin/cake mcp check` checks every server and fails when two share a route or a +resource. `mcp check`, `mcp server` and `mcp inspector` take +`--server `, and tests pick a server with `mcpUseServer('admin')`. + ## Caches If the cache configs named in `discovery.cache` and `session.cache` do not diff --git a/docs/stdio.md b/docs/stdio.md index f5daf59..f975c47 100644 --- a/docs/stdio.md +++ b/docs/stdio.md @@ -7,6 +7,9 @@ provides a command that speaks MCP over standard input and output: bin/cake mcp server ``` +With several servers (see [Several servers](configuration.md#several-servers)), +pick one with `--server`: `bin/cake mcp server --server admin`. + ## Claude Code ```bash diff --git a/docs/testing.md b/docs/testing.md index c7adaf2..306ef10 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -135,6 +135,16 @@ $this->assertMcpToolListedFor(['id' => 1, 'role' => 'admin'], 'refund_order'); $this->assertMcpToolNotListedFor(['id' => 2, 'role' => 'user'], 'refund_order'); ``` +## Several servers + +With `Mcp.servers`, the trait talks to the `default` server. Switch with +`mcpUseServer()`: + +```php +$this->mcpUseServer('admin'); +$this->assertMcpToolListed('refund_order'); +``` + ## Replacing services The trait uses Cake's `ContainerStubTrait`, so `mockService()` replaces a diff --git a/src/Command/McpCheckCommand.php b/src/Command/McpCheckCommand.php index 948403b..4a7f0db 100644 --- a/src/Command/McpCheckCommand.php +++ b/src/Command/McpCheckCommand.php @@ -10,6 +10,7 @@ use Cake\Command\Command; use Cake\Console\Arguments; use Cake\Console\ConsoleIo; +use Cake\Console\ConsoleOptionParser; use Cake\Core\App; use Cake\Core\Configure; use Cake\Core\Container; @@ -37,6 +38,7 @@ use CakeDC\Mcp\Server\ServerFactory; use CakeDC\OAuthServer\Authenticator\TokenAuthenticator; use CakeDC\OAuthServer\OAuthServer; +use InvalidArgumentException; use Mcp\Schema\Enum\CacheScope; use ReflectionProperty; use Symfony\Component\Finder\Finder; @@ -63,6 +65,11 @@ class McpCheckCommand extends Command */ private ?array $tools = null; + /** + * The server being checked. + */ + private string $server = McpConfig::DEFAULT_SERVER; + /** * @param \CakeDC\Mcp\Server\ServerFactory|null $serverFactory Builds the server, as the endpoint does. */ @@ -92,8 +99,58 @@ public static function getDescription(): string */ public function execute(Arguments $args, ConsoleIo $io): int { + try { + $all = McpConfig::servers(); + } catch (InvalidArgumentException $e) { + $io->err(sprintf('%s', $e->getMessage())); + + return static::CODE_ERROR; + } + $only = $args->getOption('server'); + if (is_string($only) && !in_array($only, $all, true)) { + $io->err(sprintf('"Mcp.servers.%s" is not configured.', $only)); + + return static::CODE_ERROR; + } + $failed = false; - foreach ($this->checks() as $name => $probe) { + foreach (is_string($only) ? [$only] : $all as $server) { + $this->server = $server; + $this->tools = null; + if (count($all) > 1) { + $io->out(sprintf('Server %s', $server)); + } + $failed = $this->runChecks($this->checks(), $io) || $failed; + } + if (count($all) > 1 && !is_string($only)) { + $failed = $this->runChecks(['Servers' => fn(): array => $this->serversCheck($all)], $io) || $failed; + } + + return $failed ? static::CODE_ERROR : static::CODE_SUCCESS; + } + + /** + * @param \Cake\Console\ConsoleOptionParser $parser The parser. + * @return \Cake\Console\ConsoleOptionParser + */ + protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser + { + return $parser->addOption('server', [ + 'help' => 'Check only this MCP server: default, or a key of Mcp.servers. All of them by default.', + ]); + } + + /** + * Runs $checks and prints one line each. + * + * @param array $checks The checks. + * @param \Cake\Console\ConsoleIo $io The console. + * @return bool Whether one of them failed. + */ + private function runChecks(array $checks, ConsoleIo $io): bool + { + $failed = false; + foreach ($checks as $name => $probe) { try { [$status, $message] = $probe(); } catch (Throwable $e) { @@ -104,7 +161,49 @@ public function execute(Arguments $args, ConsoleIo $io): int $failed = $failed || $status === 'fail'; } - return $failed ? static::CODE_ERROR : static::CODE_SUCCESS; + return $failed; + } + + /** + * Two servers on the same route, or accepting tokens for the same resource, are one server in disguise. + * + * @param list $servers Every configured server. + * @return array{0: 'pass'|'warn'|'fail', 1: string} + */ + private function serversCheck(array $servers): array + { + $routes = []; + $resources = []; + foreach ($servers as $server) { + $route = McpConfig::get('route', $server); + if (is_string($route) && trim($route, '/') !== '') { + $routes['/' . trim($route, '/')][] = $server; + } + $settings = AuthSettings::fromConfig($server); + if ($settings->mode !== AuthSettings::HOST) { + $resources[$settings->resource][] = $server; + } + } + $problems = []; + foreach ($routes as $route => $names) { + if (count($names) > 1) { + $problems[] = sprintf('%s share the route %s', implode(' and ', $names), $route); + } + } + foreach ($resources as $resource => $names) { + if (count($names) > 1) { + $problems[] = sprintf( + '%s share the resource %s, so a token for one works on the other', + implode(' and ', $names), + $resource, + ); + } + } + if ($problems !== []) { + return ['fail', implode('; ', $problems)]; + } + + return ['pass', sprintf('%d servers: %s', count($servers), implode(', ', $servers))]; } /** @@ -138,7 +237,8 @@ protected function checks(): array */ private function factory(): ServerFactory { - return $this->serverFactory ?? new ServerFactory(new Container(), new CurrentIdentity()); + return ($this->serverFactory ?? new ServerFactory(new Container(), new CurrentIdentity())) + ->forServer($this->server); } /** @@ -195,7 +295,7 @@ private function toolsCheck(): array if ($tools !== []) { return ['pass', sprintf('%d tools: %s', count($tools), self::names($tools))]; } - $dirs = array_filter((array)McpConfig::get('discovery.scanDirs'), 'is_string'); + $dirs = array_filter((array)McpConfig::get('discovery.scanDirs', $this->server), 'is_string'); return ['warn', sprintf( 'no tool found in %s (Mcp.discovery.scanDirs). A tool is a public method with #[McpTool] in a class ' @@ -293,7 +393,7 @@ private static function matches(mixed $value, string $param): bool */ private function toolScopes(): array { - $settings = AuthSettings::fromConfig(); + $settings = AuthSettings::fromConfig($this->server); if ($settings->mode === AuthSettings::HOST) { return ['pass', 'host mode, access tokens and their scopes do not apply']; } @@ -353,7 +453,7 @@ private function logging(): array */ private function audit(): array { - $settings = AuditSettings::fromConfig(); + $settings = AuditSettings::fromConfig($this->server); if (!$settings->enabled) { return ['pass', 'off']; } @@ -409,7 +509,7 @@ private static function enginesFor(string $level, array $scopes): array */ private function endpoint(): array { - $route = McpConfig::get('route'); + $route = McpConfig::get('route', $this->server); if (!is_string($route) || $route === '') { return ['warn', 'Mcp.route is disabled: only stdio (bin/cake mcp server) is served']; } @@ -422,14 +522,14 @@ private function endpoint(): array */ private function authentication(): array { - $settings = AuthSettings::fromConfig(); + $settings = AuthSettings::fromConfig($this->server); return ['pass', match ($settings->mode) { AuthSettings::OAUTH => 'oauth mode: access tokens of cakedc/cakephp-oauth-server in this application', AuthSettings::EXTERNAL => sprintf('external mode: JWT access tokens from %s', $settings->external?->issuer), default => sprintf( 'host mode: the identity your authentication puts in the "%s" request attribute', - (string)McpConfig::get('identity.attribute'), + (string)McpConfig::get('identity.attribute', $this->server), ), }]; } @@ -439,7 +539,7 @@ private function authentication(): array */ private function resource(): array { - $settings = AuthSettings::fromConfig(); + $settings = AuthSettings::fromConfig($this->server); if ($settings->mode === AuthSettings::HOST) { return ['pass', 'not used in host mode']; } @@ -474,11 +574,11 @@ private function resource(): array */ private function metadataRoute(): array { - $settings = AuthSettings::fromConfig(); + $settings = AuthSettings::fromConfig($this->server); if ($settings->mode === AuthSettings::HOST) { return ['pass', 'not used in host mode']; } - $route = McpConfig::get('route'); + $route = McpConfig::get('route', $this->server); if (!is_string($route) || $route === '') { return ['pass', 'no HTTP endpoint']; } @@ -488,7 +588,7 @@ private function metadataRoute(): array 'controller' => 'ProtectedResource', 'action' => 'metadata', 'prefix' => false, - ]); + ] + ($this->server === McpConfig::DEFAULT_SERVER ? [] : ['server' => $this->server])); } catch (MissingRouteException) { return ['fail', 'the metadata route of the plugin is not connected: load the plugin routes']; } @@ -513,8 +613,8 @@ private function metadataRoute(): array */ private function hosts(): array { - $allowed = McpConfig::allowedHosts(); - $settings = AuthSettings::fromConfig(); + $allowed = McpConfig::allowedHosts($this->server); + $settings = AuthSettings::fromConfig($this->server); if ($settings->mode === AuthSettings::HOST) { return ['pass', implode(', ', $allowed)]; } @@ -536,7 +636,7 @@ private function hosts(): array */ private function csrf(): array { - $route = McpConfig::get('route'); + $route = McpConfig::get('route', $this->server); if (!is_string($route) || $route === '') { return ['pass', 'no HTTP endpoint']; } @@ -568,8 +668,8 @@ private function csrf(): array */ private function authenticators(): array { - $settings = AuthSettings::fromConfig(); - $route = McpConfig::get('route'); + $settings = AuthSettings::fromConfig($this->server); + $route = McpConfig::get('route', $this->server); if ($settings->mode !== AuthSettings::OAUTH || !is_string($route) || $route === '') { return ['pass', 'nothing to check outside oauth mode']; } @@ -726,7 +826,7 @@ private static function within(string $path, array $prefixes): bool */ private function cacheHints(): array { - $policy = CacheHints::fromConfig(McpConfig::get('server.cache')); + $policy = CacheHints::fromConfig(McpConfig::get('server.cache', $this->server)); if ($policy === null) { return ['pass', 'off (private, not cached)']; } @@ -774,7 +874,7 @@ protected function finderAvailable(): bool */ private function discovery(): array { - $dirs = array_values(array_filter((array)McpConfig::get('discovery.scanDirs'), 'is_string')); + $dirs = array_values(array_filter((array)McpConfig::get('discovery.scanDirs', $this->server), 'is_string')); if ($dirs === []) { return ['pass', 'off (no Mcp.discovery.scanDirs)']; } diff --git a/src/Command/McpInspectorCommand.php b/src/Command/McpInspectorCommand.php index 398c0e3..b81b732 100644 --- a/src/Command/McpInspectorCommand.php +++ b/src/Command/McpInspectorCommand.php @@ -42,6 +42,11 @@ public static function getDescription(): string return 'Open the MCP Inspector on this server, over stdio or HTTP. Needs Node.js 22.19 or later.'; } + /** + * The MCP server being inspected. + */ + private string $server = McpConfig::DEFAULT_SERVER; + /** * @inheritDoc */ @@ -65,6 +70,10 @@ protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOption 'help' => 'Environment variable passed to the stdio server, by name. The Inspector passes only ' . 'a few (PATH, HOME...), so name the ones your app reads. Repeat it for more.', ]) + ->addOption('server', [ + 'help' => 'The MCP server to inspect: default, or a key of Mcp.servers.', + 'default' => McpConfig::DEFAULT_SERVER, + ]) ->addOption('dry-run', [ 'boolean' => true, 'help' => 'Print the Inspector configuration and command without starting it.', @@ -80,6 +89,12 @@ public function execute(Arguments $args, ConsoleIo $io): int $headers = $this->listOption($args, 'header'); $env = $this->listOption($args, 'env'); $http = $args->getOption('http') === true || is_string($url); + $this->server = is_string($args->getOption('server')) ? $args->getOption('server') : McpConfig::DEFAULT_SERVER; + if (!in_array($this->server, McpConfig::servers(), true)) { + $io->error(sprintf('"Mcp.servers.%s" is not configured.', $this->server)); + + return static::CODE_ERROR; + } if ($headers !== [] && !$http) { $io->error('Headers are only sent over HTTP. Add --http or --url.'); @@ -272,7 +287,9 @@ private function stdioServer(array $env, ConsoleIo $io): ?array $server = [ 'type' => 'stdio', 'command' => PHP_BINARY, - 'args' => [$cake, 'mcp', 'server'], + 'args' => $this->server === McpConfig::DEFAULT_SERVER + ? [$cake, 'mcp', 'server'] + : [$cake, 'mcp', 'server', '--server', $this->server], 'cwd' => rtrim(ROOT, DS), ]; foreach ($env as $name) { @@ -298,7 +315,7 @@ private function stdioServer(array $env, ConsoleIo $io): ?array private function httpServer(?string $url, array $headers, ConsoleIo $io): ?array { if ($url === null) { - $route = McpConfig::get('route'); + $route = McpConfig::get('route', $this->server); if (!is_string($route) || $route === '') { $io->error('The HTTP endpoint is disabled (`Mcp.route`). Pass --url to inspect another server.'); @@ -333,7 +350,7 @@ private function httpServer(?string $url, array $headers, ConsoleIo $io): ?array */ private function serverName(): string { - return strtolower(Text::slug((string)McpConfig::get('server.name'))) ?: 'cakephp'; + return strtolower(Text::slug((string)McpConfig::get('server.name', $this->server))) ?: 'cakephp'; } /** diff --git a/src/Command/McpServerCommand.php b/src/Command/McpServerCommand.php index 5080b30..53eaffe 100644 --- a/src/Command/McpServerCommand.php +++ b/src/Command/McpServerCommand.php @@ -6,10 +6,12 @@ use Cake\Command\Command; use Cake\Console\Arguments; use Cake\Console\ConsoleIo; +use Cake\Console\ConsoleOptionParser; use CakeDC\Mcp\Identity\CurrentIdentity; use CakeDC\Mcp\Log\McpLogger; use CakeDC\Mcp\McpConfig; use CakeDC\Mcp\Server\ServerFactory; +use InvalidArgumentException; use Mcp\Server\Transport\StdioTransport; use Mcp\Server\Transport\TransportInterface; @@ -57,14 +59,36 @@ public function execute(Arguments $args, ConsoleIo $io): int // QUIET keeps only the stderr logger for errors and warnings. $io->setLoggers(ConsoleIo::QUIET); - $resolver = McpConfig::get('stdio.identity'); + $server = $args->getOption('server'); + $server = is_string($server) ? $server : McpConfig::DEFAULT_SERVER; + try { + $factory = $this->serverFactory->forServer($server); + } catch (InvalidArgumentException $exception) { + $io->err(sprintf('%s', $exception->getMessage())); + + return static::CODE_ERROR; + } + + $resolver = McpConfig::get('stdio.identity', $server); $this->identity->set(is_callable($resolver) ? $resolver() : null); - $this->serverFactory->create((bool)McpConfig::get('stdio.trusted'))->run($this->createTransport()); + $factory->create((bool)McpConfig::get('stdio.trusted', $server))->run($this->createTransport()); return static::CODE_SUCCESS; } + /** + * @param \Cake\Console\ConsoleOptionParser $parser The parser. + * @return \Cake\Console\ConsoleOptionParser + */ + protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser + { + return $parser->addOption('server', [ + 'help' => 'The MCP server to serve: default, or a key of Mcp.servers.', + 'default' => McpConfig::DEFAULT_SERVER, + ]); + } + /** * @return \Mcp\Server\Transport\TransportInterface */ diff --git a/src/TestSuite/McpTestTrait.php b/src/TestSuite/McpTestTrait.php index 3e35f18..43140c1 100644 --- a/src/TestSuite/McpTestTrait.php +++ b/src/TestSuite/McpTestTrait.php @@ -55,6 +55,11 @@ trait McpTestTrait */ protected array $_mcpClaims = []; + /** + * The MCP server the requests go to (`Mcp.servers`). + */ + protected string $_mcpServer = McpConfig::DEFAULT_SERVER; + /** * The JSON-RPC response to the last `mcpCallTool()`. * @@ -98,6 +103,17 @@ public function mcpActingAs(mixed $identity, ?array $scopes = null, array $claim $this->_mcpClaims = $claims; } + /** + * Sends the following requests to another MCP server: `default` or a key of `Mcp.servers`. + * + * @param string $server The server. + * @return void + */ + public function mcpUseServer(string $server): void + { + $this->_mcpServer = $server; + } + /** * Calls a tool and keeps the response for the `assertMcp*()` methods. * @@ -482,9 +498,10 @@ private function mcpRequest(string $method, ?array $params, bool $trusted = fals if (!$factory instanceof ServerFactory) { Assert::fail('The container has no MCP ServerFactory. Is the CakeDC/Mcp plugin loaded?'); } + $factory = $factory->forServer($this->_mcpServer); $factory->identity()->set($this->_mcpIdentity); - $scopes = McpConfig::get('identity.scopes'); + $scopes = McpConfig::get('identity.scopes', $this->_mcpServer); $token = null; if ($this->_mcpIdentity !== null) { $token = IdentityMiddleware::accessTokenFor( @@ -499,7 +516,7 @@ private function mcpRequest(string $method, ?array $params, bool $trusted = fals } } if ($token !== null && $this->_mcpScopes !== null && !$trusted) { - $settings = AuthSettings::fromConfig(); + $settings = AuthSettings::fromConfig($this->_mcpServer); $policy = $settings->mode === AuthSettings::HOST ? null : $settings->scopePolicy(); if ($policy !== null) { $required = $policy->requiredFor($request); diff --git a/tests/TestCase/Command/McpCheckCommandTest.php b/tests/TestCase/Command/McpCheckCommandTest.php index 1de8630..dace7fa 100644 --- a/tests/TestCase/Command/McpCheckCommandTest.php +++ b/tests/TestCase/Command/McpCheckCommandTest.php @@ -521,6 +521,72 @@ public function testAnAuthenticatorThatLeavesTheMcpEndpointAlonePasses(): void $this->assertOutputContains('[PASS] Authenticators'); } + public function testOneServerOutputIsUnchanged(): void + { + $this->exec('mcp check'); + + $this->assertOutputNotContains('Server default'); + $this->assertOutputNotContains('Servers:'); + } + + public function testChecksEveryServer(): void + { + Configure::write('Mcp.servers.admin', ['route' => '/mcp/admin', 'discovery' => ['scanDirs' => ['src/McpDocs']]]); + + $this->exec('mcp check'); + + $this->assertExitSuccess(); + $this->assertOutputContains('Server default'); + $this->assertOutputContains('Server admin'); + $this->assertOutputContains('[PASS] Endpoint: http://localhost/mcp/admin'); + $this->assertOutputRegExp('/\[PASS\] Tools: \d+ tools: .*find_order/'); + $this->assertOutputContains('[PASS] Servers: 2 servers: default, admin'); + } + + public function testCheckOneServer(): void + { + Configure::write('Mcp.servers.admin', ['route' => '/mcp/admin', 'discovery' => ['scanDirs' => ['src/McpDocs']]]); + + $this->exec('mcp check --server admin'); + + $this->assertExitSuccess(); + $this->assertOutputContains('Server admin'); + $this->assertOutputNotContains('Server default'); + $this->assertOutputNotContains('Servers:'); + } + + public function testUnknownServerFails(): void + { + $this->exec('mcp check --server nope'); + + $this->assertExitError(); + $this->assertErrorContains('"Mcp.servers.nope" is not configured.'); + } + + public function testSharedRouteFails(): void + { + Configure::write('Mcp.servers.copy', ['route' => '/mcp/']); + + $this->exec('mcp check'); + + $this->assertExitError(); + $this->assertOutputContains('[FAIL] Servers: default and copy share the route /mcp'); + } + + public function testSharedResourceFails(): void + { + Configure::write('Mcp.auth', OAuthTestConfig::MCP_AUTH); + Configure::write('Mcp.servers.admin', [ + 'route' => '/mcp/admin', + 'auth' => ['resource' => OAuthTestConfig::MCP] + OAuthTestConfig::MCP_AUTH, + ]); + + $this->exec('mcp check'); + + $this->assertExitError(); + $this->assertOutputContains('share the resource ' . OAuthTestConfig::MCP); + } + public function testCacheHintsOffPass(): void { $this->exec('mcp check'); diff --git a/tests/TestCase/Command/McpInspectorCommandTest.php b/tests/TestCase/Command/McpInspectorCommandTest.php index d6e6536..2e37ad2 100644 --- a/tests/TestCase/Command/McpInspectorCommandTest.php +++ b/tests/TestCase/Command/McpInspectorCommandTest.php @@ -46,6 +46,24 @@ public function testStdioStartsTheServerCommand(): void ], $this->launched[0]['config']['mcpServers']['cakephp-mcp-server'] ?? null); } + public function testNamedServerOverStdioAndHttp(): void + { + Configure::write('App.fullBaseUrl', 'https://app.example.com'); + Configure::write('Mcp.servers.admin', ['route' => '/mcp/admin', 'server' => ['name' => 'Admin MCP']]); + + $this->assertSame(0, $this->runCommand(['--server', 'admin'])); + $this->assertSame( + [rtrim(ROOT, DS) . DS . 'bin' . DS . 'cake.php', 'mcp', 'server', '--server', 'admin'], + $this->launched[0]['config']['mcpServers']['admin-mcp']['args'] ?? null, + ); + + $this->assertSame(0, $this->runCommand(['--server', 'admin', '--http'])); + $this->assertSame( + 'https://app.example.com/mcp/admin', + $this->launched[1]['config']['mcpServers']['admin-mcp']['url'] ?? null, + ); + } + public function testHttpUsesTheFullBaseUrlAndTheRoute(): void { Configure::write('App.fullBaseUrl', 'https://app.example.com/'); diff --git a/tests/TestCase/Command/McpServerCommandTest.php b/tests/TestCase/Command/McpServerCommandTest.php index 8d785e5..3e1b2ed 100644 --- a/tests/TestCase/Command/McpServerCommandTest.php +++ b/tests/TestCase/Command/McpServerCommandTest.php @@ -73,6 +73,29 @@ public function testServesToolsOverTheTransport(): void $this->assertContains('echo', array_column($command->transport?->responseFor(2)['result']['tools'] ?? [], 'name')); } + public function testServesTheNamedServer(): void + { + Configure::write('Mcp.servers.admin', ['route' => '/mcp/admin', 'discovery' => ['scanDirs' => ['src/McpDocs']]]); + $command = $this->command(); + + $code = $command->run(['--server', 'admin'], new ConsoleIo(new StubConsoleOutput(), new StubConsoleOutput(), new StubConsoleInput([]))); + + $this->assertSame(McpServerCommand::CODE_SUCCESS, $code); + $names = array_column($command->transport?->responseFor(2)['result']['tools'] ?? [], 'name'); + $this->assertContains('find_order', $names); + $this->assertNotContains('echo', $names); + } + + public function testUnknownServerFails(): void + { + $err = new StubConsoleOutput(); + + $code = $this->command()->run(['--server', 'nope'], new ConsoleIo(new StubConsoleOutput(), $err, new StubConsoleInput([]))); + + $this->assertSame(McpServerCommand::CODE_ERROR, $code); + $this->assertStringContainsString('"Mcp.servers.nope" is not configured.', $err->output()); + } + public function testIdentityComesFromTheStdioResolver(): void { Configure::write('Mcp.stdio.identity', fn(): array => ['id' => 42]); diff --git a/tests/TestCase/TestSuite/McpTestTraitTest.php b/tests/TestCase/TestSuite/McpTestTraitTest.php index ee5ea77..ead1e6a 100644 --- a/tests/TestCase/TestSuite/McpTestTraitTest.php +++ b/tests/TestCase/TestSuite/McpTestTraitTest.php @@ -99,6 +99,20 @@ public function testListedForAnotherIdentityKeepsTheTestIdentity(): void $this->assertSame(['mcp:tools'], $this->_mcpScopes); } + public function testUseServer(): void + { + Configure::write('Mcp.servers.admin', ['route' => '/mcp/admin', 'discovery' => ['scanDirs' => ['src/McpDocs']]]); + + $this->mcpUseServer('admin'); + + $this->assertMcpToolListed('find_order'); + $this->mcpCallTool('find_order', ['number' => 'A-1']); + $this->assertMcpStructuredContentPath('number', 'A-1'); + + $this->mcpUseServer('default'); + $this->assertMcpToolListed('echo'); + } + public function testAnonymousByDefault(): void { $this->mcpCallTool('whoami'); From 445563bbed5a717c11d0795d6a1a7b6022b34409 Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 20:43:58 +0100 Subject: [PATCH 025/181] #[McpWhen] registers tools, resources and prompts only when a condition holds --- CHANGELOG.md | 1 + docs/tools.md | 35 +++++ src/Attribute/McpWhen.php | 65 ++++++++ src/Command/McpCheckCommand.php | 11 ++ src/Server/Conditions.php | 107 +++++++++++++ src/Server/ServerFactory.php | 67 +++++--- .../TestCase/Command/McpCheckCommandTest.php | 11 ++ .../Server/ConditionalRegistrationTest.php | 146 ++++++++++++++++++ tests/test_app/src/McpWhen/BetaTool.php | 23 +++ .../test_app/src/McpWhen/ConditionalTools.php | 56 +++++++ tests/test_app/src/McpWhen/Flags.php | 18 +++ 11 files changed, 522 insertions(+), 18 deletions(-) create mode 100644 src/Attribute/McpWhen.php create mode 100644 src/Server/Conditions.php create mode 100644 tests/TestCase/Server/ConditionalRegistrationTest.php create mode 100644 tests/test_app/src/McpWhen/BetaTool.php create mode 100644 tests/test_app/src/McpWhen/ConditionalTools.php create mode 100644 tests/test_app/src/McpWhen/Flags.php diff --git a/CHANGELOG.md b/CHANGELOG.md index fae42fc..15ddb09 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- `#[McpWhen]` registers a tool, resource, resource template or prompt only when a config value is on or a callback (given the server name) returns true; `mcp check` lists what was skipped on a new `Conditions` line. - Several MCP servers in one application (`Mcp.servers`): each with its route, metadata route, tools, auth and authorizer; security sections are replaced whole, the rest inherited key by key. `mcp check` checks every server and fails on a shared route or resource; `mcp check`, `mcp server` and `mcp inspector` take `--server`; `McpTestTrait::mcpUseServer()`. - `bin/cake mcp check` warns, on a new `Cache hints` line, when `tools/list` is public with a per-user authorizer or `resources/read` is public. - `Mcp.schema.normalize`, off by default: when on, `tools/list` drops `"null"` from the `type` and `enum` of optional parameters whose default is `null`, and that default, for hosts that reject type arrays. Arguments are still validated against the original schema. See Input schemas in `docs/tools.md`. diff --git a/docs/tools.md b/docs/tools.md index 1158e00..5bd7cf2 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -155,6 +155,41 @@ public function summary(): CallToolResult tool error ("Invalid structured output for tool ..."), not as data. Test the tool's result with `assertMcpStructuredContent()` (see [Testing](testing.md)). +## Registering only when + +`#[McpWhen]` (`CakeDC\Mcp\Attribute\McpWhen`) registers a tool, resource, +resource template or prompt only when a condition holds. Put it next to the +SDK attribute, on the method or on an invokable class: + +```php +use CakeDC\Mcp\Attribute\McpWhen; + +#[McpWhen(config: 'Features.reports')] +#[McpTool(name: 'monthly_report')] +public function report(): array +{ + // ... +} + +#[McpWhen(callback: [Flags::class, 'beta'])] +#[McpTool(name: 'beta_search')] +class BetaSearchTool +{ + // ... +} +``` + +With `config`, the element exists when that Configure value is truthy. With +`callback`, a static method decides; it receives the name of the server being +built (see [Several servers](configuration.md#several-servers)). The condition is +read every time the server is built, so a config change applies on the next +request. A skipped element does not exist for clients: it is not listed, and a +call to it answers like a call to an unknown tool. `bin/cake mcp check` lists +what was skipped on its `Conditions` line. + +Use it for configuration and feature flags. What depends on who is calling +belongs in the authorizer (see [Authorization](authorization.md)). + ## Generating classes with bake With `cakephp/bake` installed, three bake commands create a class in diff --git a/src/Attribute/McpWhen.php b/src/Attribute/McpWhen.php new file mode 100644 index 0000000..3dd60fa --- /dev/null +++ b/src/Attribute/McpWhen.php @@ -0,0 +1,65 @@ +config !== null) { + return (bool)Configure::read($this->config); + } + if (!is_callable($this->callback)) { + throw new InvalidArgumentException(sprintf( + '#[McpWhen] callback %s is not callable: give [Class::class, \'staticMethod\'].', + json_encode($this->callback), + )); + } + + return (bool)call_user_func($this->callback, $server); + } + + /** + * @return string Why the element is not registered, for `bin/cake mcp check`. + */ + public function describe(): string + { + if ($this->config !== null) { + return sprintf('%s is off', $this->config); + } + + return sprintf('%s::%s() returned false', ...array_map('strval', (array)$this->callback)); + } +} diff --git a/src/Command/McpCheckCommand.php b/src/Command/McpCheckCommand.php index 4a7f0db..1a1bceb 100644 --- a/src/Command/McpCheckCommand.php +++ b/src/Command/McpCheckCommand.php @@ -224,6 +224,7 @@ protected function checks(): array 'Discovery' => fn(): array => $this->discovery(), 'Tools' => fn(): array => $this->toolsCheck(), 'Tool schemas' => fn(): array => $this->toolSchemas(), + 'Conditions' => fn(): array => $this->conditions(), 'Authorizer' => fn(): array => $this->authorizerCheck(), 'Tool scopes' => fn(): array => $this->toolScopes(), 'Cache hints' => fn(): array => $this->cacheHints(), @@ -259,6 +260,16 @@ private function toolNames(): array return array_map(fn(array $tool): string => (string)$tool['name'], $this->toolDefinitions()); } + /** + * @return array{0: 'pass'|'warn'|'fail', 1: string} + */ + private function conditions(): array + { + $skipped = $this->factory()->skippedElements(); + + return ['pass', $skipped === [] ? 'nothing skipped' : 'skipped: ' . implode('; ', $skipped)]; + } + /** * @return array{0: 'pass'|'warn'|'fail', 1: string} */ diff --git a/src/Server/Conditions.php b/src/Server/Conditions.php new file mode 100644 index 0000000..0259b51 --- /dev/null +++ b/src/Server/Conditions.php @@ -0,0 +1,107 @@ + What was removed: ` ()`. + * @throws \InvalidArgumentException When a condition cannot be evaluated; the message names the element. + */ + public static function prune(Registry $registry, string $server): array + { + $skipped = []; + $kinds = [ + 'tool' => [$registry->getTools(), $registry->getTool(...), $registry->unregisterTool(...)], + 'resource' => [ + $registry->getResources(), + fn(string $uri): ElementReference => $registry->getResource($uri, false), + $registry->unregisterResource(...), + ], + 'resource template' => [ + $registry->getResourceTemplates(), + $registry->getResourceTemplate(...), + $registry->unregisterResourceTemplate(...), + ], + 'prompt' => [$registry->getPrompts(), $registry->getPrompt(...), $registry->unregisterPrompt(...)], + ]; + foreach ($kinds as $kind => [$page, $get, $unregister]) { + $references = $page->references; + // By name: discovery follows the file system, and `mcp check` output should not. + ksort($references, SORT_STRING); + foreach ($references as $key => $element) { + $key = (string)$key; + $condition = self::condition($get($key)); + if ($condition === null) { + continue; + } + try { + $allowed = $condition->allows($server); + } catch (InvalidArgumentException $exception) { + throw new InvalidArgumentException(sprintf('%s %s: %s', $kind, $key, $exception->getMessage())); + } + if (!$allowed) { + $unregister($key); + $skipped[] = sprintf('%s %s (%s)', $kind, self::name($element, $key), $condition->describe()); + } + } + } + + return $skipped; + } + + /** + * The `#[McpWhen]` of an element's handler: on the method first, then on its class. Closures have none. + * + * @param \Mcp\Capability\Registry\ElementReference $reference The element. + * @return \CakeDC\Mcp\Attribute\McpWhen|null + */ + private static function condition(ElementReference $reference): ?McpWhen + { + $handler = $reference->handler; + if (is_string($handler) && class_exists($handler)) { + $handler = [$handler, '__invoke']; + } + if (!is_array($handler)) { + return null; + } + $class = is_object($handler[0]) ? $handler[0]::class : $handler[0]; + if (!class_exists($class)) { + return null; + } + try { + $attributes = (new ReflectionMethod($class, $handler[1]))->getAttributes(McpWhen::class); + if ($attributes === []) { + $attributes = (new ReflectionClass($class))->getAttributes(McpWhen::class); + } + } catch (ReflectionException) { + return null; + } + + return $attributes === [] ? null : $attributes[0]->newInstance(); + } + + /** + * @param mixed $element The definition from the registry page. + * @param string $key Its key (a name or a URI). + * @return string The element's name, for messages. + */ + private static function name(mixed $element, string $key): string + { + return is_object($element) && isset($element->name) && is_string($element->name) ? $element->name : $key; + } +} diff --git a/src/Server/ServerFactory.php b/src/Server/ServerFactory.php index ba2796e..5b1629d 100644 --- a/src/Server/ServerFactory.php +++ b/src/Server/ServerFactory.php @@ -43,6 +43,13 @@ */ final class ServerFactory { + /** + * What #[McpWhen] removed in the last build. + * + * @var list + */ + private array $skipped = []; + /** * @param \Psr\Container\ContainerInterface $container The host container. * @param \CakeDC\Mcp\Identity\CurrentIdentity $identity The shared current identity. @@ -110,13 +117,12 @@ private function build(bool $trusted, LoggerInterface $logger): Server } // The guard goes first: the SDK asks request handlers in the order they were added. $builder = Server::builder()->addRequestHandler(new ToolCallGuard($gate)); + // Our own registry, set before the host hook (which may still replace it): #[McpWhen] prunes it after + // the build, and the audit asks it whether a tool exists, to tell a denied tool from an unknown one. + $registry = new Registry($events, $logger); + $builder->setRegistry($registry); $audit = AuditSettings::fromConfig($this->server); if ($audit->enabled) { - // The audit needs to know which tools exist, to tell a denied tool from an unknown one: it keeps - // the registry. Set before the host hook, which may still replace it (the audit then falls back - // to asking the gate only). - $registry = new Registry($events, $logger); - $builder->setRegistry($registry); $listener = new AuditListener( $audit, new AuditWriter($audit), @@ -168,7 +174,10 @@ private function build(bool $trusted, LoggerInterface $logger): Server ); } - return $builder->build(); + $server = $builder->build(); + $this->skipped = Conditions::prune($registry, $this->server); + + return $server; } /** @@ -262,18 +271,7 @@ public function toolDefinitions(): array (string)json_encode(['jsonrpc' => '2.0', 'method' => 'notifications/initialized']), (string)json_encode($list), ]); - // Only warnings and worse: the SDK's info lines would land among the output of `mcp check`. - $this->build(true, new class extends AbstractLogger { - /** - * @inheritDoc - */ - public function log(mixed $level, string|Stringable $message, array $context = []): void - { - if (!in_array($level, [LogLevel::INFO, LogLevel::DEBUG, LogLevel::NOTICE], true)) { - (new McpLogger())->log($level, $message, $context); - } - } - })->run($transport); + $this->build(true, $this->quietLogger())->run($transport); $result = $transport->responseFor(2)['result'] ?? null; if (!is_array($result) || !is_array($result['tools'] ?? null)) { throw new RuntimeException( @@ -294,6 +292,39 @@ public function log(mixed $level, string|Stringable $message, array $context = [ return $tools; } + /** + * What `#[McpWhen]` leaves out of this server, as a trusted client would see it. + * + * @internal Used by `bin/cake mcp check`; not part of the public API. + * @return list ` ()`. + */ + public function skippedElements(): array + { + $this->build(true, $this->quietLogger()); + + return $this->skipped; + } + + /** + * Only warnings and worse: the SDK's info lines would land among the output of `mcp check`. + * + * @return \Psr\Log\LoggerInterface + */ + private function quietLogger(): LoggerInterface + { + return new class extends AbstractLogger { + /** + * @inheritDoc + */ + public function log(mixed $level, string|Stringable $message, array $context = []): void + { + if (!in_array($level, [LogLevel::INFO, LogLevel::DEBUG, LogLevel::NOTICE], true)) { + (new McpLogger())->log($level, $message, $context); + } + } + }; + } + /** * The configured tool authorizer (`Mcp.authorization.authorizer`), built as the server builds it. * diff --git a/tests/TestCase/Command/McpCheckCommandTest.php b/tests/TestCase/Command/McpCheckCommandTest.php index dace7fa..70063a6 100644 --- a/tests/TestCase/Command/McpCheckCommandTest.php +++ b/tests/TestCase/Command/McpCheckCommandTest.php @@ -587,6 +587,17 @@ public function testSharedResourceFails(): void $this->assertOutputContains('share the resource ' . OAuthTestConfig::MCP); } + public function testConditionsListSkippedElements(): void + { + $this->exec('mcp check'); + $this->assertOutputContains('[PASS] Conditions: nothing skipped'); + + Configure::write('Mcp.discovery.scanDirs', ['src/McpWhen']); + $this->exec('mcp check'); + $this->assertOutputContains('[PASS] Conditions: skipped: tool beta_tool ('); + $this->assertOutputContains('tool monthly_report (TestApp.reports is off)'); + } + public function testCacheHintsOffPass(): void { $this->exec('mcp check'); diff --git a/tests/TestCase/Server/ConditionalRegistrationTest.php b/tests/TestCase/Server/ConditionalRegistrationTest.php new file mode 100644 index 0000000..edfd28d --- /dev/null +++ b/tests/TestCase/Server/ConditionalRegistrationTest.php @@ -0,0 +1,146 @@ + ArrayEngine::class]); + Configure::write('Mcp.discovery.scanDirs', ['src/McpWhen']); + $container = new Container(); + $identity = new CurrentIdentity(); + $container->addShared(CurrentIdentity::class, $identity); + $this->factory = new ServerFactory($container, $identity); + } + + protected function tearDown(): void + { + Cache::drop('mcp_sessions'); + Configure::delete('TestApp'); + parent::tearDown(); + } + + public function testAToolWhoseConfigIsOffIsNotRegistered(): void + { + $transport = $this->serve([ + ['jsonrpc' => '2.0', 'id' => 2, 'method' => 'tools/list'], + ['jsonrpc' => '2.0', 'id' => 3, 'method' => 'tools/call', 'params' => [ + 'name' => 'monthly_report', + 'arguments' => new stdClass(), + ]], + ]); + + $names = array_column($transport->responseFor(2)['result']['tools'] ?? [], 'name'); + $this->assertContains('always', $names); + $this->assertNotContains('monthly_report', $names); + $this->assertStringContainsString('monthly_report', $transport->responseFor(3)['error']['message'] ?? ''); + } + + public function testConfigOnRegistersIt(): void + { + Configure::write('TestApp.reports', true); + + $transport = $this->serve([['jsonrpc' => '2.0', 'id' => 2, 'method' => 'tools/list']]); + + $this->assertContains('monthly_report', array_column($transport->responseFor(2)['result']['tools'] ?? [], 'name')); + } + + public function testCallbackGetsTheServer(): void + { + $list = [['jsonrpc' => '2.0', 'id' => 2, 'method' => 'tools/list']]; + $this->assertNotContains('beta_tool', array_column($this->serve($list)->responseFor(2)['result']['tools'] ?? [], 'name')); + + Configure::write('Mcp.servers.beta', ['route' => '/mcp/beta']); + $this->factory = $this->factory->forServer('beta'); + + $this->assertContains('beta_tool', array_column($this->serve($list)->responseFor(2)['result']['tools'] ?? [], 'name')); + } + + public function testResourcesAndPromptsAreSkippedToo(): void + { + $transport = $this->serve([ + ['jsonrpc' => '2.0', 'id' => 2, 'method' => 'resources/list'], + ['jsonrpc' => '2.0', 'id' => 3, 'method' => 'prompts/list'], + ]); + $this->assertSame([], $transport->responseFor(2)['result']['resources'] ?? null); + $this->assertSame([], $transport->responseFor(3)['result']['prompts'] ?? null); + + Configure::write('TestApp', ['guides' => true, 'prompts' => true]); + $transport = $this->serve([ + ['jsonrpc' => '2.0', 'id' => 2, 'method' => 'resources/list'], + ['jsonrpc' => '2.0', 'id' => 3, 'method' => 'prompts/list'], + ]); + $this->assertSame(['guide'], array_column($transport->responseFor(2)['result']['resources'] ?? [], 'name')); + $this->assertSame(['weekly'], array_column($transport->responseFor(3)['result']['prompts'] ?? [], 'name')); + } + + public function testSkippedElementsAreReported(): void + { + $this->assertSame([ + 'tool beta_tool (TestApp\McpWhen\Flags::onlyBeta() returned false)', + 'tool monthly_report (TestApp.reports is off)', + 'resource guide (TestApp.guides is off)', + 'prompt weekly (TestApp.prompts is off)', + ], $this->factory->skippedElements()); + } + + public function testInvalidAttributeFails(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('#[McpWhen] needs either config or callback'); + + new McpWhen(); + } + + public function testCodeRegisteredToolsAreUntouched(): void + { + Configure::write('Mcp.server.configure', function (Builder $builder): void { + $builder->addTool(fn(): string => 'ok', 'from_code'); + }); + + $transport = $this->serve([['jsonrpc' => '2.0', 'id' => 2, 'method' => 'tools/list']]); + + $this->assertContains('from_code', array_column($transport->responseFor(2)['result']['tools'] ?? [], 'name')); + } + + /** + * @param list> $requests + */ + private function serve(array $requests): RecordingTransport + { + $transport = new RecordingTransport(array_map(fn(array $message): string => (string)json_encode($message), [ + ['jsonrpc' => '2.0', 'id' => 1, 'method' => 'initialize', 'params' => [ + 'protocolVersion' => '2025-06-18', + 'capabilities' => new stdClass(), + 'clientInfo' => ['name' => 'test', 'version' => '1.0'], + ]], + ['jsonrpc' => '2.0', 'method' => 'notifications/initialized'], + ...$requests, + ])); + $this->factory->create(true)->run($transport); + + return $transport; + } +} diff --git a/tests/test_app/src/McpWhen/BetaTool.php b/tests/test_app/src/McpWhen/BetaTool.php new file mode 100644 index 0000000..5657c3d --- /dev/null +++ b/tests/test_app/src/McpWhen/BetaTool.php @@ -0,0 +1,23 @@ + + */ + #[McpWhen(config: 'TestApp.prompts')] + #[McpPrompt(name: 'weekly')] + public function weekly(): array + { + return [['role' => 'user', 'content' => 'Weekly.']]; + } +} diff --git a/tests/test_app/src/McpWhen/Flags.php b/tests/test_app/src/McpWhen/Flags.php new file mode 100644 index 0000000..3731977 --- /dev/null +++ b/tests/test_app/src/McpWhen/Flags.php @@ -0,0 +1,18 @@ + Date: Fri, 20 Nov 2026 20:46:59 +0100 Subject: [PATCH 026/181] McpTestTrait: run tools that notify, and assert their notifications --- docs/testing.md | 10 +++ src/TestSuite/McpTestTrait.php | 84 ++++++++++++++++++- src/TestSuite/RecordingTransport.php | 58 +++++++++++++ .../TestSuite/McpTestTraitProgressTest.php | 71 ++++++++++++++++ tests/test_app/src/McpProgress/SlowTools.php | 51 +++++++++++ 5 files changed, 273 insertions(+), 1 deletion(-) create mode 100644 tests/TestCase/TestSuite/McpTestTraitProgressTest.php create mode 100644 tests/test_app/src/McpProgress/SlowTools.php diff --git a/docs/testing.md b/docs/testing.md index 306ef10..2ebc9ac 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -119,6 +119,16 @@ endpoint (`IntegrationTestTrait`, a `POST` to `/mcp` with your | `assertMcpStructuredContent($expected)` | returned this `structuredContent`. Key order does not matter, value types do. | | `assertMcpStructuredContentPath($path, $expected)` | returned `$expected` at a dot path of its `structuredContent` (`order.lines.0.sku`). Value types matter, and a missing path fails. | | `assertMcpStructuredContentHas($path)` | returned a `structuredContent` with that dot path, even with a `null` value. | +| `assertMcpProgressSent(?$count)` | reported progress (`notifications/progress`): at least once, or exactly `$count` times. | +| `assertMcpNotificationSent($method)` | sent a notification of `$method`, for example `notifications/message` for a log line. | + +`mcpCallTool()` asks for progress (it sends a `progressToken`) and the test +session sets the log level to `debug`, so a tool that calls +`$client->progress()` or `$client->log()` on its `Mcp\Server\ClientGateway` +runs to the end and its notifications are kept: `mcpNotifications()` returns +them, all or those of one method. A tool that asks the client something +(`$client->sample()`, `$client->elicit()`) cannot be answered in a test, and +the call fails with a message saying so. `assertMcpToolListed($name)` and `assertMcpToolNotListed($name)` check what the current identity sees in `tools/list`. They make their own call. diff --git a/src/TestSuite/McpTestTrait.php b/src/TestSuite/McpTestTrait.php index 43140c1..bf3e1d0 100644 --- a/src/TestSuite/McpTestTrait.php +++ b/src/TestSuite/McpTestTrait.php @@ -60,6 +60,20 @@ trait McpTestTrait */ protected string $_mcpServer = McpConfig::DEFAULT_SERVER; + /** + * The notifications the server sent during the last `mcpCallTool()`. + * + * @var list> + */ + protected array $_mcpNotifications = []; + + /** + * The notifications of the last request, whatever it was. + * + * @var list> + */ + protected array $_mcpLastNotifications = []; + /** * The JSON-RPC response to the last `mcpCallTool()`. * @@ -127,7 +141,10 @@ public function mcpCallTool(string $name, array $arguments = []): array $this->_mcpResponse = $this->mcpRequest('tools/call', [ 'name' => $name, 'arguments' => $arguments === [] ? new stdClass() : $arguments, + // As clients that show progress do: the tool's progress notifications are then sent and recorded. + '_meta' => ['progressToken' => 'mcp-test'], ], log: $this->_mcpLog); + $this->_mcpNotifications = $this->_mcpLastNotifications; return $this->_mcpResponse; } @@ -411,6 +428,54 @@ private function mcpStructuredContentAt(string $path): array return [true, $value]; } + /** + * The notifications the server sent during the last `mcpCallTool()`, all of them or those of one method + * (`notifications/progress`, `notifications/message`...). + * + * @param string|null $method A notification method, or null for all. + * @return list> + */ + public function mcpNotifications(?string $method = null): array + { + return array_values(array_filter( + $this->_mcpNotifications, + fn(array $notification): bool => $method === null || ($notification['method'] ?? null) === $method, + )); + } + + /** + * Asserts that the last call sent a notification of $method. + * + * @param string $method The notification method, for example `notifications/message`. + * @param string $message The failure message. + * @return void + */ + public function assertMcpNotificationSent(string $method, string $message = ''): void + { + Assert::assertNotEmpty( + $this->mcpNotifications($method), + $message ?: sprintf('The last call sent no %s notification.', $method), + ); + } + + /** + * Asserts that the last call reported progress: at least once, or exactly $count times. + * + * @param int|null $count The expected number of progress notifications, or null for at least one. + * @param string $message The failure message. + * @return void + */ + public function assertMcpProgressSent(?int $count = null, string $message = ''): void + { + $sent = count($this->mcpNotifications('notifications/progress')); + if ($count === null) { + Assert::assertGreaterThan(0, $sent, $message ?: 'The last call reported no progress.'); + + return; + } + Assert::assertSame($count, $sent, $message ?: sprintf('The last call reported progress %d times.', $sent)); + } + /** * Asserts that the current identity sees a tool in `tools/list`. * @@ -550,6 +615,13 @@ private function mcpRequest(string $method, ?array $params, bool $trusted = fals 'clientInfo' => ['name' => 'McpTestTrait', 'version' => '1.0'], ]]), (string)json_encode(['jsonrpc' => '2.0', 'method' => 'notifications/initialized']), + // So the log notifications of a tool are sent and recorded. + (string)json_encode([ + 'jsonrpc' => '2.0', + 'id' => 'mcp-test-log-level', + 'method' => 'logging/setLevel', + 'params' => ['level' => 'debug'], + ]), (string)json_encode($request), ], $token, @@ -569,9 +641,19 @@ private function mcpRequest(string $method, ?array $params, bool $trusted = fals Log::drop($logConfig); } + $this->_mcpLastNotifications = array_values(array_filter( + $transport->sent, + fn(array $message): bool => !array_key_exists('id', $message) && isset($message['method']), + )); $response = $transport->responseFor(2); if ($response === null) { - Assert::fail(sprintf('The server sent no response to `%s`.', $method)); + Assert::fail($transport->waitsOnClient() + ? sprintf( + 'The tool asked the client something (sampling or elicitation), which McpTestTrait cannot ' + . 'answer, so `%s` got no response.', + $method, + ) + : sprintf('The server sent no response to `%s`.', $method)); } return $response; diff --git a/src/TestSuite/RecordingTransport.php b/src/TestSuite/RecordingTransport.php index 706d22e..0d0be09 100644 --- a/src/TestSuite/RecordingTransport.php +++ b/src/TestSuite/RecordingTransport.php @@ -21,6 +21,11 @@ class RecordingTransport extends InMemoryTransport */ public array $sent = []; + /** + * Set when the last handler stopped on a request to the client. + */ + private bool $waitingOnClient = false; + /** * @param list $messages The JSON-RPC messages to feed, in order. * @param \Mcp\Server\Authorization\AccessToken|null $accessToken Sent with every message, as the HTTP endpoint does. @@ -36,6 +41,59 @@ public function __construct(array $messages = [], private readonly ?AccessToken protected function handleMessage(string $payload, ?Uuid $sessionId, ?AccessToken $accessToken = null): void { parent::handleMessage($payload, $sessionId, $accessToken ?? $this->accessToken); + $this->driveFiber(); + } + + /** + * Whether the last tool stopped on a request to the client (sampling, elicitation), which nothing here answers. + * + * @return bool + */ + public function waitsOnClient(): bool + { + return $this->waitingOnClient; + } + + /** + * Runs a handler that suspended itself to notify the client, as the SDK's stdio transport does: sends what it + * queued and resumes it until it ends, then sends its result. A handler that waits on an answer from the + * client is left suspended. + * + * @return void + */ + private function driveFiber(): void + { + $this->waitingOnClient = false; + // A bound, in case a handler suspends forever without asking anything. + for ($step = 0; $step < 10000 && $this->sessionFiber !== null; $step++) { + $fiber = $this->sessionFiber; + $this->flushOutgoing(); + if ($fiber->isTerminated()) { + $this->sessionFiber = null; + $this->send((string)json_encode($fiber->getReturn()), []); + + return; + } + if (!$fiber->isSuspended()) { + return; + } + if ($this->getPendingRequests($this->sessionId, $fiber) !== []) { + $this->waitingOnClient = true; + + return; + } + $this->handleFiberYield($fiber->resume(), $this->sessionId, $fiber); + } + } + + /** + * @return void + */ + private function flushOutgoing(): void + { + foreach ($this->getOutgoingMessages($this->sessionId) as $message) { + $this->send($message['message'], $message['context']); + } } /** diff --git a/tests/TestCase/TestSuite/McpTestTraitProgressTest.php b/tests/TestCase/TestSuite/McpTestTraitProgressTest.php new file mode 100644 index 0000000..cb6169e --- /dev/null +++ b/tests/TestCase/TestSuite/McpTestTraitProgressTest.php @@ -0,0 +1,71 @@ + ArrayEngine::class]); + Configure::write('Mcp.discovery.scanDirs', ['src/McpProgress']); + } + + protected function tearDown(): void + { + Cache::drop('mcp_sessions'); + parent::tearDown(); + } + + public function testProgressAndLogsAreRecorded(): void + { + $this->mcpCallTool('import_orders'); + + $this->assertMcpToolSucceeded(); + $this->assertSame('Imported 10 orders.', $this->mcpResultText()); + $this->assertMcpProgressSent(2); + $this->assertSame( + ['Read the file', 'Saved the orders'], + array_column(array_column($this->mcpNotifications('notifications/progress'), 'params'), 'message'), + ); + $this->assertMcpNotificationSent('notifications/message'); + } + + public function testAToolWithoutNotificationsRecordsNone(): void + { + $this->mcpCallTool('quick'); + + $this->assertMcpToolSucceeded(); + $this->assertSame([], $this->mcpNotifications()); + } + + public function testProgressAssertionFailsWithoutProgress(): void + { + $this->mcpCallTool('quick'); + + $this->expectException(AssertionFailedError::class); + $this->assertMcpProgressSent(); + } + + public function testAToolThatAsksTheClientFailsInsteadOfHanging(): void + { + $this->expectException(AssertionFailedError::class); + $this->expectExceptionMessage('The tool asked the client something (sampling or elicitation)'); + + $this->mcpCallTool('summarize_orders'); + } +} diff --git a/tests/test_app/src/McpProgress/SlowTools.php b/tests/test_app/src/McpProgress/SlowTools.php new file mode 100644 index 0000000..3325a40 --- /dev/null +++ b/tests/test_app/src/McpProgress/SlowTools.php @@ -0,0 +1,51 @@ +progress(1, 2, 'Read the file'); + $client->log(LoggingLevel::Info, 'Imported 10 orders'); + $client->progress(2, 2, 'Saved the orders'); + + return 'Imported 10 orders.'; + } + + /** + * Asks the client's model to summarize the orders (sampling). + * + * @param \Mcp\Server\ClientGateway $client The client. + */ + #[McpTool(name: 'summarize_orders')] + public function summarize(ClientGateway $client): string + { + $result = $client->sample('Summarize the open orders.'); + + return (string)json_encode($result); + } + + /** + * Returns without notifying. + */ + #[McpTool(name: 'quick')] + public function quick(): string + { + return 'done'; + } +} From c9a298ad2b1252ac6c849c228866d64dc7ed098d Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 20:48:14 +0100 Subject: [PATCH 027/181] Docs and tests for progress over HTTP --- CHANGELOG.md | 2 + docs/tools.md | 37 +++++ docs/troubleshooting.md | 12 +- tests/TestCase/Controller/McpProgressTest.php | 149 ++++++++++++++++++ 4 files changed, 198 insertions(+), 2 deletions(-) create mode 100644 tests/TestCase/Controller/McpProgressTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 15ddb09..cc99adc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +- `McpTestTrait` runs tools that report progress or log through the SDK's `ClientGateway` (they used to get no response in tests) and records their notifications: `mcpNotifications()`, `assertMcpProgressSent()`, `assertMcpNotificationSent()`. A tool that asks the client something fails with a clear message. +- Docs: progress and logs from a tool, and what buffers server-sent events (PHP output buffering, compression, proxies). - `#[McpWhen]` registers a tool, resource, resource template or prompt only when a config value is on or a callback (given the server name) returns true; `mcp check` lists what was skipped on a new `Conditions` line. - Several MCP servers in one application (`Mcp.servers`): each with its route, metadata route, tools, auth and authorizer; security sections are replaced whole, the rest inherited key by key. `mcp check` checks every server and fails on a shared route or resource; `mcp check`, `mcp server` and `mcp inspector` take `--server`; `McpTestTrait::mcpUseServer()`. - `bin/cake mcp check` warns, on a new `Cache hints` line, when `tools/list` is public with a per-user authorizer or `resources/read` is public. diff --git a/docs/tools.md b/docs/tools.md index 5bd7cf2..2847707 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -155,6 +155,43 @@ public function summary(): CallToolResult tool error ("Invalid structured output for tool ..."), not as data. Test the tool's result with `assertMcpStructuredContent()` (see [Testing](testing.md)). +## Progress and logs + +A long tool can tell the client how far it got. Take the SDK's +`Mcp\Server\ClientGateway` as a parameter (the SDK fills it in, it is not +part of the input schema) and call `progress()` as the work advances: + +```php +use Mcp\Schema\Enum\LoggingLevel; +use Mcp\Server\ClientGateway; + +#[McpTool(name: 'import_orders')] +public function import(ClientGateway $client, string $file): string +{ + $rows = $this->reader->rows($file); + foreach (array_chunk($rows, 100) as $i => $chunk) { + $this->importer->save($chunk); + $client->progress(($i + 1) * 100, count($rows), 'Saved ' . (($i + 1) * 100) . ' orders'); + } + $client->log(LoggingLevel::Info, sprintf('Imported %d orders from %s', count($rows), $file)); + + return sprintf('Imported %d orders.', count($rows)); +} +``` + +Progress is sent only when the client asked for it (its call carries a +`progressToken`); otherwise `progress()` does nothing. Log lines are sent at +the level the client chose with `logging/setLevel`. Over HTTP the endpoint then +answers with server-sent events: the notifications as they happen, then the +result. If they arrive all at once at the end, something buffers the response +(see [Troubleshooting](troubleshooting.md#server-sent-events-stall-behind-nginx)). +In tests, `assertMcpProgressSent()` and `assertMcpNotificationSent()` check +them (see [Testing](testing.md)). + +`ClientGateway` can also ask the client's model (`sample()`) or the user +(`elicit()`) something. Those need a client that supports them, and they +cannot be answered in `McpTestTrait` tests. + ## Registering only when `#[McpWhen]` (`CakeDC\Mcp\Attribute\McpWhen`) registers a tool, resource, diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index aecac9c..8cb6bb6 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -86,8 +86,16 @@ authorization service on the MCP route. ## Server-sent events stall behind nginx The plugin sends `X-Accel-Buffering: no` on event streams so nginx does not -buffer them. If a stream still stalls, a proxy or CDN in front is ignoring the -header. Disable response buffering for the MCP path there. +buffer them. If a stream still stalls, or progress arrives all at once at the +end of a call, something between the tool and the client is buffering: + +- PHP: `output_buffering` and `zlib.output_compression` hold the output until + the request ends. Turn them off for the MCP route (for example in a + `.user.ini` or the FPM pool). +- Apache: `mod_deflate` compresses, and so buffers, `text/event-stream`; + exclude that type. +- A proxy or CDN in front that ignores the header: disable response buffering + for the MCP path there. ## The session is lost between requests diff --git a/tests/TestCase/Controller/McpProgressTest.php b/tests/TestCase/Controller/McpProgressTest.php new file mode 100644 index 0000000..116d257 --- /dev/null +++ b/tests/TestCase/Controller/McpProgressTest.php @@ -0,0 +1,149 @@ +modernCall(['progressToken' => 'p1']); + + $this->assertResponseOk(); + $this->assertSame('text/event-stream', $this->_response->getHeaderLine('Content-Type')); + $events = $this->events(); + $this->assertSame(['notifications/progress', 'notifications/progress'], array_column(array_slice($events, 0, 2), 'method')); + $this->assertSame(['p1', 'p1'], array_column(array_column(array_slice($events, 0, 2), 'params'), 'progressToken')); + $this->assertSame('Imported 10 orders.', $events[2]['result']['content'][0]['text'] ?? null); + } + + public function testHandshakeCallStreamsProgressThenTheResult(): void + { + $headers = $this->session(); + $this->post('/mcp', (string)json_encode(['jsonrpc' => '2.0', 'id' => 2, 'method' => 'tools/call', 'params' => [ + 'name' => 'import_orders', + 'arguments' => new stdClass(), + '_meta' => ['progressToken' => 'p2'], + ]])); + + $this->assertResponseOk(); + $events = $this->events(); + $this->assertSame([2, 2], array_column(array_column(array_slice($events, 0, 2), 'params'), 'total')); + $this->assertSame(2, $events[2]['id'] ?? null); + $this->assertNotSame([], $headers); + } + + public function testNoProgressTokenNoProgress(): void + { + $this->modernCall([]); + + $this->assertResponseOk(); + $methods = array_column($this->events(), 'method'); + $this->assertNotContains('notifications/progress', $methods); + } + + /** + * @param array $meta + */ + private function modernCall(array $meta): void + { + $this->configRequest(['headers' => $this->headers() + [ + 'MCP-Protocol-Version' => '2026-07-28', + 'Mcp-Method' => 'tools/call', + 'Mcp-Name' => 'import_orders', + ]]); + $this->post('/mcp', (string)json_encode(['jsonrpc' => '2.0', 'id' => 5, 'method' => 'tools/call', 'params' => [ + 'name' => 'import_orders', + 'arguments' => new stdClass(), + '_meta' => $meta + [ + 'io.modelcontextprotocol/protocolVersion' => '2026-07-28', + 'io.modelcontextprotocol/clientCapabilities' => new stdClass(), + ], + ]])); + } + + /** + * Opens a 2025-06-18 session and leaves its headers configured for the next request. + * + * @return array + */ + private function session(): array + { + $this->configRequest(['headers' => $this->headers()]); + $this->post('/mcp', (string)json_encode(['jsonrpc' => '2.0', 'id' => 1, 'method' => 'initialize', 'params' => [ + 'protocolVersion' => '2025-06-18', + 'capabilities' => new stdClass(), + 'clientInfo' => ['name' => 'test', 'version' => '1.0'], + ]])); + $headers = $this->headers() + [ + 'Mcp-Session-Id' => $this->_response->getHeaderLine('Mcp-Session-Id'), + 'MCP-Protocol-Version' => '2025-06-18', + ]; + $this->configRequest(['headers' => $headers]); + $this->post('/mcp', (string)json_encode(['jsonrpc' => '2.0', 'method' => 'notifications/initialized'])); + $this->configRequest(['headers' => $headers]); + + return $headers; + } + + /** + * @return array + */ + private function headers(): array + { + return [ + 'Host' => 'localhost', + 'Accept' => 'application/json, text/event-stream', + 'Content-Type' => 'application/json', + 'Authorization' => 'Bearer ' . TestTokens::EDITOR, + ]; + } + + /** + * The JSON messages of the response, from its `data:` lines (or the body when it is plain JSON). + * + * @return list> + */ + private function events(): array + { + // An event stream echoes and flushes as it is read, the way it reaches a real client: a buffer with a + // callback keeps every flushed chunk. + $captured = ''; + ob_start(function (string $chunk) use (&$captured): string { + $captured .= $chunk; + + return ''; + }); + $returned = (string)$this->_response->getBody(); + ob_end_clean(); + $body = $captured . $returned; + if (!str_contains($body, 'data:')) { + return [json_decode($body, true)]; + } + $events = []; + foreach (explode("\n", $body) as $line) { + if (str_starts_with($line, 'data:')) { + $events[] = json_decode(trim(substr($line, 5)), true); + } + } + + return $events; + } +} From 4b773c40b76a93875b442f50913bff71886af377 Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 20:49:25 +0100 Subject: [PATCH 028/181] Named servers: fail closed on empty security sections, slug names, McpConfig::for() --- src/McpConfig.php | 37 ++++++++++++++++++++++++++++---- tests/TestCase/McpConfigTest.php | 33 ++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 4 deletions(-) diff --git a/src/McpConfig.php b/src/McpConfig.php index 852b749..040aa73 100644 --- a/src/McpConfig.php +++ b/src/McpConfig.php @@ -100,6 +100,18 @@ public static function get(?string $path = null, string $server = self::DEFAULT_ return $path === null ? $config : Hash::get($config, $path); } + /** + * The resolved config of a server, as `get(null, $server)`. + * + * @param string $server The server: `default` or a key of `Mcp.servers`. + * @return array + * @throws \InvalidArgumentException When the server is not configured or its config is invalid. + */ + public static function for(string $server): array + { + return self::resolve($server); + } + /** * The configured servers: `default` first, then the keys of `Mcp.servers` in order. * @@ -153,11 +165,22 @@ private static function resolve(string $server): array throw new InvalidArgumentException(sprintf('"Mcp.servers.%s" is not configured.', $server)); } $config = $default; + unset($named['servers']); foreach (self::REPLACED_SECTIONS as $section) { - if (array_key_exists($section, $named)) { - $config[$section] = self::merge(self::DEFAULTS[$section], (array)$named[$section]); - unset($named[$section]); + if (!array_key_exists($section, $named)) { + continue; } + // A null (an unset env() value, say) or an empty array is a misconfiguration, never a request for the + // plugin's permissive defaults: fail closed, as the default server does. + if (!is_array($named[$section]) || $named[$section] === []) { + throw new InvalidArgumentException(sprintf( + '"Mcp.servers.%s.%s" must be a non-empty array; leave it out to use the default server\'s.', + $server, + $section, + )); + } + $config[$section] = self::merge(self::DEFAULTS[$section], $named[$section]); + unset($named[$section]); } $hasConfigure = is_array($named['server'] ?? null) && array_key_exists('configure', $named['server']); if ($hasConfigure) { @@ -178,9 +201,15 @@ private static function named(): array throw new InvalidArgumentException('"Mcp.servers" must be an array of server name => config.'); } foreach ($servers as $name => $config) { - if (!is_string($name) || $name === '' || !is_array($config)) { + if (!is_string($name) || !is_array($config)) { throw new InvalidArgumentException('"Mcp.servers" must be an array of server name => config.'); } + if (preg_match('/^[A-Za-z0-9_-]+$/', $name) !== 1) { + throw new InvalidArgumentException(sprintf( + 'The server name "%s" in "Mcp.servers" may only have letters, digits, "-" and "_".', + $name, + )); + } if ($name === self::DEFAULT_SERVER) { throw new InvalidArgumentException( '"Mcp.servers.default" is not allowed: the top-level "Mcp" config is the default server.', diff --git a/tests/TestCase/McpConfigTest.php b/tests/TestCase/McpConfigTest.php index 249aceb..aa8062b 100644 --- a/tests/TestCase/McpConfigTest.php +++ b/tests/TestCase/McpConfigTest.php @@ -219,6 +219,39 @@ public function testServerConfigureIsReplacedOnlyWhenSet(): void $this->assertNull(McpConfig::get('server.configure', 'none')); } + public function testANullOrEmptySecuritySectionFailsClosed(): void + { + foreach (['auth', 'authorization', 'discovery'] as $section) { + foreach ([null, [], 'yes'] as $value) { + Configure::write('Mcp.servers', ['admin' => ['route' => '/mcp/admin', $section => $value]]); + try { + McpConfig::get('route', 'admin'); + $this->fail(sprintf('Accepted %s => %s', $section, var_export($value, true))); + } catch (InvalidArgumentException $e) { + $this->assertStringContainsString(sprintf('"Mcp.servers.admin.%s"', $section), $e->getMessage()); + } + } + } + } + + public function testServerNamesAreSlugs(): void + { + Configure::write('Mcp.servers', ['back office' => ['route' => '/mcp/bo']]); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('letters, digits, "-" and "_"'); + + McpConfig::servers(); + } + + public function testForReturnsTheResolvedConfig(): void + { + Configure::write('Mcp.servers.admin', ['route' => '/mcp/admin', 'servers' => ['nested' => ['route' => '/x']]]); + + $this->assertSame(McpConfig::get(null, 'admin'), McpConfig::for('admin')); + $this->assertArrayNotHasKey('servers', McpConfig::for('admin')); + } + public function testUnknownServerFails(): void { $this->expectException(InvalidArgumentException::class); From 5f5be8784093b75bf6d6b46ada7110df056b97c3 Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 20:50:09 +0100 Subject: [PATCH 029/181] Named servers: reverse routing reaches them, mcp check fails on a shared external audience --- src/Command/McpCheckCommand.php | 18 +++++++++++ src/McpPlugin.php | 4 ++- .../TestCase/Command/McpCheckCommandTest.php | 30 +++++++++++++++++++ tests/TestCase/McpPluginTest.php | 16 ++++++++++ 4 files changed, 67 insertions(+), 1 deletion(-) diff --git a/src/Command/McpCheckCommand.php b/src/Command/McpCheckCommand.php index 1a1bceb..e64932f 100644 --- a/src/Command/McpCheckCommand.php +++ b/src/Command/McpCheckCommand.php @@ -174,6 +174,7 @@ private function serversCheck(array $servers): array { $routes = []; $resources = []; + $audiences = []; foreach ($servers as $server) { $route = McpConfig::get('route', $server); if (is_string($route) && trim($route, '/') !== '') { @@ -183,6 +184,10 @@ private function serversCheck(array $servers): array if ($settings->mode !== AuthSettings::HOST) { $resources[$settings->resource][] = $server; } + // An external authorization server's tokens are accepted by audience, not by resource. + foreach ($settings->external->audiences ?? [] as $audience) { + $audiences[$settings->external?->issuer . ' ' . $audience][] = $server; + } } $problems = []; foreach ($routes as $route => $names) { @@ -199,6 +204,19 @@ private function serversCheck(array $servers): array ); } } + foreach ($audiences as $key => $names) { + $names = array_values(array_unique($names)); + if (count($names) > 1) { + [$issuer, $audience] = explode(' ', $key, 2); + $problems[] = sprintf( + '%s accept the audience %s from %s, so a token for one works on the other: give each server ' + . 'its own auth.external.audience', + implode(' and ', $names), + $audience, + $issuer, + ); + } + } if ($problems !== []) { return ['fail', implode('; ', $problems)]; } diff --git a/src/McpPlugin.php b/src/McpPlugin.php index bb2d223..0b50624 100644 --- a/src/McpPlugin.php +++ b/src/McpPlugin.php @@ -64,7 +64,9 @@ public function bootstrap(PluginApplicationInterface $app): void */ public function routes(RouteBuilder $routes): void { - foreach (McpConfig::servers() as $server) { + // Named servers first: the default server's routes carry no `server` param, so connected first they would + // also match reverse routing to a named server. + foreach (array_reverse(McpConfig::servers()) as $server) { $path = McpConfig::get('route', $server); if (!is_string($path) || $path === '') { continue; diff --git a/tests/TestCase/Command/McpCheckCommandTest.php b/tests/TestCase/Command/McpCheckCommandTest.php index 70063a6..13e2c3c 100644 --- a/tests/TestCase/Command/McpCheckCommandTest.php +++ b/tests/TestCase/Command/McpCheckCommandTest.php @@ -435,6 +435,36 @@ public function testSubdirectoryInstallWarnsAboutTheWellKnownRewrite(): void $this->assertOutputContains('rewrite'); } + public function testNamedExternalServerHasItsOwnMetadataRoute(): void + { + Cache::setConfig('mcp_check_cache', ['className' => ArrayEngine::class]); + Configure::write('Mcp.servers.admin', ['route' => '/mcp/admin', 'auth' => ['mode' => 'external', 'external' => [ + 'issuer' => 'https://issuer.example', + 'cache' => 'mcp_check_cache', + ]]]); + + $this->exec('mcp check --server admin'); + + $this->assertOutputContains('[PASS] Metadata route'); + $this->assertOutputNotContains('advertised URL path'); + } + + public function testSharedExternalAudienceFails(): void + { + Cache::setConfig('mcp_check_cache', ['className' => ArrayEngine::class]); + Configure::write('Mcp.auth', ['mode' => 'external', 'external' => [ + 'issuer' => 'https://issuer.example', + 'audience' => 'api://mcp', + 'cache' => 'mcp_check_cache', + ]]); + Configure::write('Mcp.servers.admin', ['route' => '/mcp/admin']); + + $this->exec('mcp check'); + + $this->assertExitError(); + $this->assertOutputContains('default and admin accept the audience api://mcp'); + } + public function testExternalModeReportsTheAudiences(): void { Configure::write('Mcp.auth', ['mode' => 'external', 'resource' => 'http://localhost/mcp', 'external' => [ diff --git a/tests/TestCase/McpPluginTest.php b/tests/TestCase/McpPluginTest.php index 133cf86..336965a 100644 --- a/tests/TestCase/McpPluginTest.php +++ b/tests/TestCase/McpPluginTest.php @@ -9,6 +9,7 @@ use Cake\Core\Configure; use Cake\Routing\RouteBuilder; use Cake\Routing\RouteCollection; +use Cake\Routing\Router; use Cake\TestSuite\TestCase; use CakeDC\Mcp\McpPlugin; use TestApp\Application; @@ -87,6 +88,21 @@ public function testBootstrapDefinesTheExternalCacheOnlyInExternalMode(): void } } + public function testReverseRoutingReachesEachServer(): void + { + Configure::write('Mcp.servers.admin', ['route' => '/mcp/admin']); + Router::reload(); + (new McpPlugin())->routes(Router::createRouteBuilder('/')); + + $endpoint = ['plugin' => 'CakeDC/Mcp', 'controller' => 'Mcp', 'action' => 'handle', 'prefix' => false]; + $metadata = ['plugin' => 'CakeDC/Mcp', 'controller' => 'ProtectedResource', 'action' => 'metadata', 'prefix' => false]; + $this->assertSame('/mcp', Router::url($endpoint)); + $this->assertSame('/mcp/admin', Router::url($endpoint + ['server' => 'admin'])); + $this->assertSame('/.well-known/oauth-protected-resource/mcp', Router::url($metadata)); + $this->assertSame('/.well-known/oauth-protected-resource/mcp/admin', Router::url($metadata + ['server' => 'admin'])); + Router::reload(); + } + public function testRoutesConnectTheEndpointAtTheConfiguredPath(): void { Configure::write('Mcp.route', '/ai/mcp'); From 6a2c27b07ca2b6971e89919ec0dc360181d9d7ed Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 20:51:21 +0100 Subject: [PATCH 030/181] mcp check: warn about partial security sections; named-server security tests and docs --- CHANGELOG.md | 3 +- docs/configuration.md | 26 ++++++- src/Command/McpCheckCommand.php | 18 +++++ .../TestCase/Command/McpCheckCommandTest.php | 22 ++++++ tests/TestCase/Controller/McpServersTest.php | 75 +++++++++++++++++++ 5 files changed, 140 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cc99adc..81ecaf0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,8 @@ - `McpTestTrait` runs tools that report progress or log through the SDK's `ClientGateway` (they used to get no response in tests) and records their notifications: `mcpNotifications()`, `assertMcpProgressSent()`, `assertMcpNotificationSent()`. A tool that asks the client something fails with a clear message. - Docs: progress and logs from a tool, and what buffers server-sent events (PHP output buffering, compression, proxies). - `#[McpWhen]` registers a tool, resource, resource template or prompt only when a config value is on or a callback (given the server name) returns true; `mcp check` lists what was skipped on a new `Conditions` line. -- Several MCP servers in one application (`Mcp.servers`): each with its route, metadata route, tools, auth and authorizer; security sections are replaced whole, the rest inherited key by key. `mcp check` checks every server and fails on a shared route or resource; `mcp check`, `mcp server` and `mcp inspector` take `--server`; `McpTestTrait::mcpUseServer()`. +- `bin/cake mcp check` warns when `authorization.rbac` has rules but another authorizer is set, and when `auth.scopes` is set in host mode. +- Several MCP servers in one application (`Mcp.servers`): each with its route, metadata route, tools, auth and authorizer; security sections are replaced whole, the rest inherited key by key. `mcp check` checks every server and fails on a shared route, resource or external audience; a `null` or empty security section and a server name that is not a slug fail; `mcp check`, `mcp server` and `mcp inspector` take `--server`; `McpTestTrait::mcpUseServer()`. - `bin/cake mcp check` warns, on a new `Cache hints` line, when `tools/list` is public with a per-user authorizer or `resources/read` is public. - `Mcp.schema.normalize`, off by default: when on, `tools/list` drops `"null"` from the `type` and `enum` of optional parameters whose default is `null`, and that default, for hosts that reject type arrays. Arguments are still validated against the original schema. See Input schemas in `docs/tools.md`. - `bin/cake mcp check` warns, on a new `Tool schemas` line, about type arrays, arrays without an item type and optional parameters without a description. diff --git a/docs/configuration.md b/docs/configuration.md index 7d48db5..3605b83 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -183,11 +183,31 @@ server, in two ways: `audit`, `schema`) is merged key by key, so `'server' => ['name' => ...]` keeps the default server's version and instructions. +Because a replaced section starts again from the plugin's defaults, set every +key that matters in it. `'authorization' => ['rbac' => $rules]` alone leaves the +default `AllowAllToolAuthorizer`, and `'auth' => ['scopes' => ...]` alone leaves +host mode, where scopes are not checked: set `authorizer` and `mode` too. +`bin/cake mcp check` warns about both. A named server whose security section is +`null` or `[]` (an unset `env()` value, for example) fails instead of falling +back to the defaults. + Every server gets its endpoint and, in `oauth` and `external` modes, its protected resource metadata at `/.well-known/oauth-protected-resource` plus its -route. Its resource defaults to its own URL, so a token issued for one server is -not accepted by another. Sessions are kept apart, and audit records of a named -server carry a `server` field (`server=admin` on the log line). +route. Its resource defaults to its own URL; in `oauth` mode declare that URL in +`OAuthServer.resources` as well. Keep tokens apart: + +- In `oauth` mode the authorization server issues each token for one resource, + so a token for one server is not accepted by another, unless two servers set + the same `auth.resource`. +- In `external` mode tokens are accepted by audience. A named server that does + not set `auth` inherits the default server's, `external.audience` included, + and then accepts its tokens. Give each server its own audience. + +`bin/cake mcp check` fails on a shared route, resource or external audience. +Sessions are kept apart, and audit records of a named server carry a `server` +field (`server=admin` on the log line). A server nested under another's route +(`/mcp/admin` under `/mcp`) is also under any authenticator that covers the +outer path; `bin/cake mcp check` reports such authenticators. `bin/cake mcp check` checks every server and fails when two share a route or a resource. `mcp check`, `mcp server` and `mcp inspector` take diff --git a/src/Command/McpCheckCommand.php b/src/Command/McpCheckCommand.php index e64932f..8ba62ef 100644 --- a/src/Command/McpCheckCommand.php +++ b/src/Command/McpCheckCommand.php @@ -40,6 +40,7 @@ use CakeDC\OAuthServer\OAuthServer; use InvalidArgumentException; use Mcp\Schema\Enum\CacheScope; +use ReflectionClass; use ReflectionProperty; use Symfony\Component\Finder\Finder; use Throwable; @@ -340,6 +341,16 @@ private function toolsCheck(): array private function authorizerCheck(): array { $authorizer = $this->factory()->authorizer(); + $rbac = McpConfig::get('authorization.rbac', $this->server); + if (is_array($rbac) && $rbac !== [] && !$authorizer instanceof RbacToolAuthorizer) { + return ['warn', sprintf( + 'authorization.rbac has rules, but the authorizer is %s, so they are ignored. Set ' + . 'authorization.authorizer to RbacToolAuthorizer (a server that sets authorization replaces the ' + . 'whole section), see %s', + (new ReflectionClass($authorizer))->getShortName(), + self::DOCS . 'configuration.md#several-servers', + )]; + } if ($authorizer instanceof AllowAllToolAuthorizer) { return ['pass', 'AllowAllToolAuthorizer: every identified caller may call every tool']; } @@ -424,6 +435,13 @@ private function toolScopes(): array { $settings = AuthSettings::fromConfig($this->server); if ($settings->mode === AuthSettings::HOST) { + $scopes = (array)McpConfig::get('auth.scopes', $this->server); + if (array_filter($scopes, fn(mixed $value): bool => $value !== []) !== []) { + return ['warn', 'auth.scopes is set, but host mode does not check scopes. Set auth.mode to oauth or ' + . 'external (a server that sets auth replaces the whole section), see ' + . self::DOCS . 'configuration.md#several-servers']; + } + return ['pass', 'host mode, access tokens and their scopes do not apply']; } $tools = $this->toolNames(); diff --git a/tests/TestCase/Command/McpCheckCommandTest.php b/tests/TestCase/Command/McpCheckCommandTest.php index 13e2c3c..2554658 100644 --- a/tests/TestCase/Command/McpCheckCommandTest.php +++ b/tests/TestCase/Command/McpCheckCommandTest.php @@ -449,6 +449,28 @@ public function testNamedExternalServerHasItsOwnMetadataRoute(): void $this->assertOutputNotContains('advertised URL path'); } + public function testRbacRulesWithoutTheRbacAuthorizerWarn(): void + { + // Replaced whole: setting only the rules leaves the default AllowAllToolAuthorizer. + Configure::write('Mcp.servers.admin', [ + 'route' => '/mcp/admin', + 'authorization' => ['rbac' => ['permissions' => [['role' => 'admin']]]], + ]); + + $this->exec('mcp check --server admin'); + + $this->assertOutputContains('[WARN] Authorizer: authorization.rbac has rules, but the authorizer is'); + } + + public function testScopesInHostModeWarn(): void + { + Configure::write('Mcp.servers.admin', ['route' => '/mcp/admin', 'auth' => ['scopes' => ['default' => ['admin']]]]); + + $this->exec('mcp check --server admin'); + + $this->assertOutputContains('[WARN] Tool scopes: auth.scopes is set, but host mode does not check scopes'); + } + public function testSharedExternalAudienceFails(): void { Cache::setConfig('mcp_check_cache', ['className' => ArrayEngine::class]); diff --git a/tests/TestCase/Controller/McpServersTest.php b/tests/TestCase/Controller/McpServersTest.php index 9a491be..fd24a7b 100644 --- a/tests/TestCase/Controller/McpServersTest.php +++ b/tests/TestCase/Controller/McpServersTest.php @@ -6,6 +6,8 @@ use Cake\Cache\Cache; use Cake\Cache\Engine\ArrayEngine; use Cake\Core\Configure; +use Cake\Log\Engine\ArrayLog; +use Cake\Log\Log; use Cake\Routing\Router; use Cake\TestSuite\IntegrationTestTrait; use Cake\TestSuite\TestCase; @@ -94,6 +96,53 @@ public function testEachServerHasItsMetadataRoute(): void $this->assertResponseCode(404); } + public function testANamedServerChecksItsOwnScopes(): void + { + Configure::write('Mcp.servers.admin.auth', [ + 'mode' => 'external', + 'scopes' => ['tools' => ['find_order' => ['orders:read']]], + 'external' => ['issuer' => TestJwt::ISSUER, 'cache' => 'mcp_oauth_test', 'httpClient' => TestJwt::client()], + ]); + $token = TestJwt::token(['aud' => 'http://localhost/mcp/admin']); + + $this->modernCall('/mcp/admin', 'find_order', ['number' => 'A-1'], $token); + $this->assertResponseCode(403); + $header = $this->_response->getHeaderLine('WWW-Authenticate'); + $this->assertStringContainsString('error="insufficient_scope"', $header); + $this->assertStringContainsString( + 'resource_metadata="http://localhost/.well-known/oauth-protected-resource/mcp/admin"', + $header, + ); + + $this->modernCall('/mcp/admin', 'find_order', ['number' => 'A-1'], TestJwt::token([ + 'aud' => 'http://localhost/mcp/admin', + 'scope' => 'orders:read', + ])); + $this->assertResponseOk(); + + // A token for the default server's resource is not one for the admin server. + $this->modernCall('/mcp/admin', 'find_order', ['number' => 'A-1'], TestJwt::token(['scope' => 'orders:read'])); + $this->assertResponseCode(401); + } + + public function testANamedServerAuditsWithItsName(): void + { + Log::setConfig('audit_servers', ['className' => ArrayLog::class, 'scopes' => ['mcp_audit']]); + Configure::write('Mcp.servers.admin.audit', ['enabled' => true]); + try { + $headers = $this->session('/mcp/admin'); + $this->mcp('/mcp/admin', $this->call(3, 'find_order', ['number' => 'A-1']), $headers); + + $engine = Log::engine('audit_servers'); + $lines = $engine instanceof ArrayLog ? $engine->read() : []; + $this->assertCount(1, $lines); + $this->assertStringContainsString('MCP tools/call find_order ok', (string)$lines[0]); + $this->assertStringContainsString(' server=admin', (string)$lines[0]); + } finally { + Log::drop('audit_servers'); + } + } + public function testA21ConfigStillServesMcp(): void { Configure::delete('Mcp.servers'); @@ -105,6 +154,32 @@ public function testA21ConfigStillServesMcp(): void $this->assertArrayNotHasKey('jsonrpc', $this->json()); } + /** + * A stateless 2026-07-28 tools/call with a bearer token. + * + * @param array $arguments + */ + private function modernCall(string $path, string $tool, array $arguments, string $token): void + { + $this->configRequest(['headers' => [ + 'Host' => 'localhost', + 'Accept' => 'application/json, text/event-stream', + 'Content-Type' => 'application/json', + 'Authorization' => 'Bearer ' . $token, + 'MCP-Protocol-Version' => '2026-07-28', + 'Mcp-Method' => 'tools/call', + 'Mcp-Name' => $tool, + ]]); + $this->post($path, (string)json_encode(['jsonrpc' => '2.0', 'id' => 1, 'method' => 'tools/call', 'params' => [ + 'name' => $tool, + 'arguments' => $arguments, + '_meta' => [ + 'io.modelcontextprotocol/protocolVersion' => '2026-07-28', + 'io.modelcontextprotocol/clientCapabilities' => new stdClass(), + ], + ]])); + } + /** * @return list */ From e9718f7d4a88cc315a31ae6e2228848704f48845 Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 20:55:42 +0100 Subject: [PATCH 031/181] Searchable tool catalog: find_tools and call_tools --- src/Authorization/ToolGate.php | 6 +- src/Catalog/CatalogPatterns.php | 29 +++ src/Catalog/ToolCatalog.php | 266 +++++++++++++++++++++ src/Event/ToolListFilter.php | 7 +- src/McpConfig.php | 1 + src/Server/ServerFactory.php | 73 +++++- tests/TestCase/Catalog/ToolCatalogTest.php | 160 +++++++++++++ 7 files changed, 537 insertions(+), 5 deletions(-) create mode 100644 src/Catalog/CatalogPatterns.php create mode 100644 src/Catalog/ToolCatalog.php create mode 100644 tests/TestCase/Catalog/ToolCatalogTest.php diff --git a/src/Authorization/ToolGate.php b/src/Authorization/ToolGate.php index ffeb88c..2df2176 100644 --- a/src/Authorization/ToolGate.php +++ b/src/Authorization/ToolGate.php @@ -15,11 +15,13 @@ final class ToolGate * @param \CakeDC\Mcp\Authorization\ToolAuthorizerInterface $authorizer The configured authorizer. * @param \CakeDC\Mcp\Identity\CurrentIdentity $identity The current caller. * @param bool $trusted Skip the authorizer (stdio started by the developer). + * @param list $alwaysAllowed Tools allowed whatever the authorizer says (the tool catalog's own tools). */ public function __construct( private readonly ToolAuthorizerInterface $authorizer, private readonly CurrentIdentity $identity, private readonly bool $trusted = false, + private readonly array $alwaysAllowed = [], ) { } @@ -29,6 +31,8 @@ public function __construct( */ public function allows(string $tool): bool { - return $this->trusted || $this->authorizer->canCall($this->identity->get(), $tool); + return $this->trusted + || in_array($tool, $this->alwaysAllowed, true) + || $this->authorizer->canCall($this->identity->get(), $tool); } } diff --git a/src/Catalog/CatalogPatterns.php b/src/Catalog/CatalogPatterns.php new file mode 100644 index 0000000..748e5cc --- /dev/null +++ b/src/Catalog/CatalogPatterns.php @@ -0,0 +1,29 @@ + $patterns Tool names or `fnmatch()` patterns (`order_*`). + * @param string $tool A tool name. + * @return bool Whether the tool is in the catalog. The catalog's own tools never are. + */ + public static function matches(array $patterns, string $tool): bool + { + if ($tool === ToolCatalog::FIND || $tool === ToolCatalog::CALL) { + return false; + } + foreach ($patterns as $pattern) { + if (fnmatch($pattern, $tool)) { + return true; + } + } + + return false; + } +} diff --git a/src/Catalog/ToolCatalog.php b/src/Catalog/ToolCatalog.php new file mode 100644 index 0000000..91e8cb9 --- /dev/null +++ b/src/Catalog/ToolCatalog.php @@ -0,0 +1,266 @@ + $patterns `Mcp.catalog.tools`. + * @param int $maxCalls `Mcp.catalog.maxCalls`. + * @param \Mcp\Capability\Registry\ReferenceHandlerInterface $references Runs the tools, with the plugin container. + * @param \Psr\Log\LoggerInterface $logger The server's logger. + */ + public function __construct( + private readonly Registry $registry, + private readonly ToolGate $gate, + private readonly array $patterns, + private readonly int $maxCalls, + private readonly ReferenceHandlerInterface $references, + private readonly LoggerInterface $logger, + ) { + } + + /** + * Whether $tool is in the catalog of this server. + * + * @param string $tool A tool name. + * @return bool + */ + public function has(string $tool): bool + { + return CatalogPatterns::matches($this->patterns, $tool) && $this->registry->hasTool($tool); + } + + /** + * Finds catalogued tools the caller may call, best matches first. + * + * @param \Mcp\Server\RequestContext $context The call (injected by the SDK). + * @param string $query Words to look for in the tool names, titles and descriptions. Empty: every tool. + * @param int $limit How many tools, 1 to 50. + * @return array{tools: list}>} + */ + public function find(RequestContext $context, string $query = '', int $limit = 10): array + { + $terms = preg_split('/[^a-z0-9]+/', strtolower($query), -1, PREG_SPLIT_NO_EMPTY) ?: []; + $ranked = []; + foreach ($this->registry->getTools()->references as $name => $tool) { + $name = (string)$name; + if (!$this->callable($name)) { + continue; + } + $score = $terms === [] ? 1 : $this->score($tool, $terms); + if ($score > 0) { + $ranked[] = [$score, $tool]; + } + } + usort($ranked, fn(array $a, array $b): int => [$b[0], $a[1]->name] <=> [$a[0], $b[1]->name]); + $tools = []; + foreach (array_slice($ranked, 0, max(1, min(50, $limit))) as [, $tool]) { + $tools[] = [ + 'name' => $tool->name, + 'title' => $tool->title, + 'description' => $tool->description, + 'inputSchema' => $tool->inputSchema, + ]; + } + + return ['tools' => $tools]; + } + + /** + * Runs catalogued tools in order, stopping at the first error. + * + * @param \Mcp\Server\RequestContext $context The call (injected by the SDK). + * @param array $calls The tools to run: `{name, arguments}` objects from the client. + * @return \Mcp\Schema\Result\CallToolResult + * @throws \Mcp\Exception\ToolCallException With more calls than `Mcp.catalog.maxCalls`. + */ + public function call(RequestContext $context, array $calls): CallToolResult + { + if (count($calls) > $this->maxCalls) { + throw new ToolCallException(sprintf('At most %d calls at a time.', $this->maxCalls)); + } + $handler = new CallToolHandler($this->registry, $this->references, $this->logger); + $parent = $context->getRequest(); + $results = []; + $failed = false; + foreach (array_values($calls) as $index => $call) { + $name = is_array($call) && is_string($call['name'] ?? null) ? $call['name'] : ''; + $arguments = is_array($call) ? $call['arguments'] ?? [] : null; + $result = is_array($arguments) + ? $this->runOne($handler, $context, $parent->getId() . '.' . $index, $name, $arguments) + : $this->error($name, sprintf('The arguments of %s must be an object.', $name)); + $results[] = $result; + if ($result['isError']) { + $failed = true; + break; + } + } + $data = ['results' => $results]; + + return new CallToolResult( + [new TextContent((string)json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE))], + $failed, + $data, + ); + } + + /** + * The JSON schemas of the two tools. + * + * @return array> + */ + public function inputSchemas(): array + { + return [ + self::FIND => [ + 'type' => 'object', + 'properties' => [ + 'query' => [ + 'type' => 'string', + 'description' => 'Words to look for in tool names and descriptions. ' + . 'Leave it out for all tools.', + ], + 'limit' => [ + 'type' => 'integer', + 'minimum' => 1, + 'maximum' => 50, + 'description' => 'How many tools to return, 1 to 50. Default 10.', + ], + ], + ], + self::CALL => [ + 'type' => 'object', + 'properties' => [ + 'calls' => [ + 'type' => 'array', + 'minItems' => 1, + 'maxItems' => $this->maxCalls, + 'description' => 'The tools to run, in order, with the names and arguments find_tools gave. ' + . 'The run stops at the first error.', + 'items' => [ + 'type' => 'object', + 'properties' => [ + 'name' => ['type' => 'string', 'description' => 'A tool name from find_tools.'], + // No type: the SDK decodes an empty JSON object as an empty PHP array, which a + // `type: object` check refuses. The inner tool validates its own arguments. + 'arguments' => [ + 'description' => 'An object with the arguments, as the tool\'s input schema ' + . 'describes them. {} for none.', + ], + ], + 'required' => ['name'], + ], + ], + ], + 'required' => ['calls'], + ], + ]; + } + + /** + * Whether the caller may call $tool through the catalog. + * + * @param string $tool A tool name. + * @return bool + */ + private function callable(string $tool): bool + { + return $this->has($tool) && $this->gate->allows($tool); + } + + /** + * @param \Mcp\Server\Handler\Request\CallToolHandler $handler The SDK handler. + * @param \Mcp\Server\RequestContext $context The outer call. + * @param string $id The inner request id. + * @param string $name The tool. + * @param array $arguments Its arguments. + * @return array{name: string, isError: bool, content: array, structuredContent?: mixed} + */ + private function runOne( + CallToolHandler $handler, + RequestContext $context, + string $id, + string $name, + array $arguments, + ): array { + if (!$this->callable($name)) { + // Like a direct call: a denied tool answers as an unknown one. + return $this->error($name, sprintf('Tool not found: "%s".', $name)); + } + $request = (new CallToolRequest($name, $arguments))->withId($id)->withMeta($context->getRequest()->getMeta()); + $response = $handler->handle($request, $context->getSession()); + if ($response instanceof Error) { + return $this->error($name, $response->message); + } + $result = $response->result; + if (!$result instanceof CallToolResult) { + return $this->error($name, 'The tool returned no result.'); + } + $entry = [ + 'name' => $name, + 'isError' => $result->isError, + 'content' => array_map( + fn(mixed $item): mixed => json_decode((string)json_encode($item), true), + $result->content, + ), + ]; + if ($result->structuredContent !== null) { + $entry['structuredContent'] = $result->structuredContent; + } + + return $entry; + } + + /** + * @param string $name The tool. + * @param string $message The error. + * @return array{name: string, isError: true, content: list} + */ + private function error(string $name, string $message): array + { + return ['name' => $name, 'isError' => true, 'content' => [['type' => 'text', 'text' => $message]]]; + } + + /** + * @param \Mcp\Schema\Tool $tool A tool. + * @param list $terms Lowercase query words. + * @return int Name matches count 3, title 2, description 1. + */ + private function score(Tool $tool, array $terms): int + { + $score = 0; + foreach ($terms as $term) { + $score += str_contains(strtolower($tool->name), $term) ? 3 : 0; + $score += str_contains(strtolower((string)$tool->title), $term) ? 2 : 0; + $score += str_contains(strtolower((string)$tool->description), $term) ? 1 : 0; + } + + return $score; + } +} diff --git a/src/Event/ToolListFilter.php b/src/Event/ToolListFilter.php index 9b601d9..75df9fd 100644 --- a/src/Event/ToolListFilter.php +++ b/src/Event/ToolListFilter.php @@ -4,6 +4,7 @@ namespace CakeDC\Mcp\Event; use CakeDC\Mcp\Authorization\ToolGate; +use Closure; use Mcp\Event\ResponseEvent; use Mcp\Schema\JsonRpc\Response; use Mcp\Schema\Result\ListToolsResult; @@ -16,8 +17,9 @@ final class ToolListFilter { /** * @param \CakeDC\Mcp\Authorization\ToolGate $gate The gate. + * @param \Closure(string): bool|null $hidden Tools to leave out of the list even when allowed (the catalog's). */ - public function __construct(private readonly ToolGate $gate) + public function __construct(private readonly ToolGate $gate, private readonly ?Closure $hidden = null) { } @@ -35,7 +37,8 @@ public function __invoke(ResponseEvent $event): void $tools = array_values(array_filter( $result->tools, - fn(Tool $tool): bool => $this->gate->allows($tool->name), + fn(Tool $tool): bool => $this->gate->allows($tool->name) + && ($this->hidden === null || !($this->hidden)($tool->name)), )); $event->setResponse(new Response($response->getId(), new ListToolsResult($tools, $result->nextCursor))); } diff --git a/src/McpConfig.php b/src/McpConfig.php index 040aa73..3fe5c92 100644 --- a/src/McpConfig.php +++ b/src/McpConfig.php @@ -41,6 +41,7 @@ final class McpConfig ], 'discovery' => ['scanDirs' => ['src/Mcp'], 'excludeDirs' => [], 'cache' => '_cake_mcp_'], 'schema' => ['normalize' => false], + 'catalog' => ['enabled' => false, 'tools' => [], 'maxCalls' => 5], 'session' => ['cache' => 'mcp_sessions', 'ttl' => 3600], 'http' => ['allowedHosts' => null, 'allowedOrigins' => [], 'maxBodyBytes' => 4 * 1024 * 1024], 'identity' => ['required' => true, 'attribute' => 'identity', 'scopes' => null], diff --git a/src/Server/ServerFactory.php b/src/Server/ServerFactory.php index 5b1629d..1f45f19 100644 --- a/src/Server/ServerFactory.php +++ b/src/Server/ServerFactory.php @@ -10,6 +10,8 @@ use CakeDC\Mcp\Authorization\ToolAuthorizerInterface; use CakeDC\Mcp\Authorization\ToolCallGuard; use CakeDC\Mcp\Authorization\ToolGate; +use CakeDC\Mcp\Catalog\CatalogPatterns; +use CakeDC\Mcp\Catalog\ToolCatalog; use CakeDC\Mcp\Container\ContainerBridge; use CakeDC\Mcp\Event\AuditListener; use CakeDC\Mcp\Event\EventDispatcher; @@ -21,10 +23,12 @@ use CakeDC\Mcp\TestSuite\RecordingTransport; use InvalidArgumentException; use Mcp\Capability\Registry; +use Mcp\Capability\Registry\ReferenceHandler; use Mcp\Event\ErrorEvent; use Mcp\Event\RequestEvent; use Mcp\Event\ResponseEvent; use Mcp\Schema\Enum\ProtocolVersion; +use Mcp\Schema\ToolAnnotations; use Mcp\Server; use Mcp\Server\Builder; use Mcp\Server\Session\Psr16SessionStore; @@ -108,9 +112,21 @@ public function create(bool $trusted = false): Server */ private function build(bool $trusted, LoggerInterface $logger): Server { - $gate = new ToolGate($this->authorizer(), $this->identity, $trusted); + $catalog = (array)McpConfig::get('catalog', $this->server); + $catalogOn = ($catalog['enabled'] ?? false) === true; + $patterns = array_values(array_filter((array)($catalog['tools'] ?? []), 'is_string')); + // The catalog's own tools are always allowed: each tool they run goes through the gate instead. + $gate = new ToolGate( + $this->authorizer(), + $this->identity, + $trusted, + $catalogOn ? [ToolCatalog::FIND, ToolCatalog::CALL] : [], + ); $events = new EventDispatcher(); - $events->listen(ResponseEvent::class, new ToolListFilter($gate)); + $events->listen(ResponseEvent::class, new ToolListFilter( + $gate, + $catalogOn ? fn(string $tool): bool => CatalogPatterns::matches($patterns, $tool) : null, + )); if (McpConfig::get('schema.normalize', $this->server) === true) { // After the filter, on the tools the caller may see. $events->listen(ResponseEvent::class, new ToolSchemaNormalizer()); @@ -121,6 +137,16 @@ private function build(bool $trusted, LoggerInterface $logger): Server // the build, and the audit asks it whether a tool exists, to tell a denied tool from an unknown one. $registry = new Registry($events, $logger); $builder->setRegistry($registry); + if ($catalogOn) { + $this->addCatalog($builder, new ToolCatalog( + $registry, + $gate, + $patterns, + $this->maxCalls($catalog['maxCalls'] ?? 5), + new ReferenceHandler(new ContainerBridge($this->container)), + $logger, + )); + } $audit = AuditSettings::fromConfig($this->server); if ($audit->enabled) { $listener = new AuditListener( @@ -292,6 +318,49 @@ public function toolDefinitions(): array return $tools; } + /** + * Registers `find_tools` and `call_tools`. + * + * @param \Mcp\Server\Builder $builder The builder. + * @param \CakeDC\Mcp\Catalog\ToolCatalog $catalog The catalog. + * @return void + */ + private function addCatalog(Builder $builder, ToolCatalog $catalog): void + { + $schemas = $catalog->inputSchemas(); + $builder->addTool( + [$catalog, 'find'], + ToolCatalog::FIND, + 'Find tools', + 'Finds more tools of this server by what they do. Returns their names, descriptions and input schemas; ' + . 'run them with call_tools.', + new ToolAnnotations(readOnlyHint: true, openWorldHint: false), + $schemas[ToolCatalog::FIND], + ); + $builder->addTool( + [$catalog, 'call'], + ToolCatalog::CALL, + 'Call tools', + 'Runs tools found with find_tools, in order, and returns each result. Stops at the first error.', + null, + $schemas[ToolCatalog::CALL], + ); + } + + /** + * @param mixed $value `Mcp.catalog.maxCalls`. + * @return int + * @throws \InvalidArgumentException When it is not a positive integer. + */ + private function maxCalls(mixed $value): int + { + if (!is_int($value) || $value < 1) { + throw new InvalidArgumentException('"Mcp.catalog.maxCalls" must be a positive integer.'); + } + + return $value; + } + /** * What `#[McpWhen]` leaves out of this server, as a trusted client would see it. * diff --git a/tests/TestCase/Catalog/ToolCatalogTest.php b/tests/TestCase/Catalog/ToolCatalogTest.php new file mode 100644 index 0000000..aa4206d --- /dev/null +++ b/tests/TestCase/Catalog/ToolCatalogTest.php @@ -0,0 +1,160 @@ + ArrayEngine::class]); + Configure::write('Mcp.discovery.scanDirs', ['src/McpDocs']); + Configure::write('Mcp.catalog', ['enabled' => true, 'tools' => ['order_*', 'find_order', 'list_orders']]); + } + + protected function tearDown(): void + { + Cache::drop('mcp_sessions'); + parent::tearDown(); + } + + public function testCataloguedToolsLeaveTheListButStayCallable(): void + { + $names = array_column($this->mcpListTools(), 'name'); + + $this->assertContains('find_tools', $names); + $this->assertContains('call_tools', $names); + $this->assertContains('orders_compact', $names); + $this->assertNotContains('order_status', $names); + $this->assertNotContains('find_order', $names); + + $this->mcpCallTool('order_status', ['number' => 'A-1']); + $this->assertMcpToolSucceeded(); + } + + public function testFindToolsRanksByNameTitleAndDescription(): void + { + $this->mcpCallTool('find_tools', ['query' => 'status']); + + $this->assertMcpToolSucceeded(); + $tools = $this->mcpResult()['structuredContent']['tools']; + $this->assertSame('order_status', $tools[0]['name']); + $this->assertSame(['number'], $tools[0]['inputSchema']['required']); + $this->assertNotContains('orders_compact', array_column($tools, 'name')); + } + + public function testFindToolsWithAnEmptyQuery(): void + { + $this->mcpCallTool('find_tools', ['limit' => 3]); + + $this->assertMcpToolSucceeded(); + $this->assertCount(3, $this->mcpResult()['structuredContent']['tools']); + } + + public function testFindToolsHidesToolsTheCallerCannotCall(): void + { + Configure::write('Mcp.authorization.authorizer', $this->denying('order_status')); + + $this->mcpCallTool('find_tools', ['query' => 'status']); + + $this->assertMcpToolSucceeded(); + $this->assertNotContains('order_status', array_column($this->mcpResult()['structuredContent']['tools'], 'name')); + } + + public function testCallToolsRunsInOrderAndStopsAtTheFirstError(): void + { + $this->mcpCallTool('call_tools', ['calls' => [ + ['name' => 'order_status', 'arguments' => ['number' => 'A-1']], + ['name' => 'find_order', 'arguments' => ['number' => 7]], + ['name' => 'order_numbers', 'arguments' => new stdClass()], + ]]); + + $this->assertMcpToolError(); + $results = $this->mcpResult()['structuredContent']['results']; + $this->assertCount(2, $results); + $this->assertSame(['order_status', 'find_order'], array_column($results, 'name')); + $this->assertFalse($results[0]['isError']); + $this->assertSame('open', $results[0]['content'][0]['text']); + $this->assertTrue($results[1]['isError']); + $this->assertStringContainsString("Invalid parameters for tool 'find_order'", $results[1]['content'][0]['text']); + } + + public function testCallToolsDeniesLikeAnUnknownTool(): void + { + Configure::write('Mcp.authorization.authorizer', $this->denying('order_status')); + + $this->mcpCallTool('call_tools', ['calls' => [['name' => 'order_status', 'arguments' => ['number' => 'A-1']]]]); + + $this->assertMcpToolError(); + $result = $this->mcpResult()['structuredContent']['results'][0]; + $this->assertSame('Tool not found: "order_status".', $result['content'][0]['text']); + } + + public function testCallToolsRefusesToolsOutsideTheCatalogAndItself(): void + { + foreach (['orders_compact', 'call_tools', 'find_tools', 'no_such_tool'] as $name) { + $this->mcpCallTool('call_tools', ['calls' => [['name' => $name, 'arguments' => new stdClass()]]]); + + $this->assertMcpToolError(); + $result = $this->mcpResult()['structuredContent']['results'][0]; + $this->assertSame(sprintf('Tool not found: "%s".', $name), $result['content'][0]['text'], $name); + } + } + + public function testArgumentsThatAreNotAnObjectAreAnError(): void + { + $this->mcpCallTool('call_tools', ['calls' => [['name' => 'order_numbers', 'arguments' => 'all']]]); + + $this->assertMcpToolError(); + $result = $this->mcpResult()['structuredContent']['results'][0]; + $this->assertSame('The arguments of order_numbers must be an object.', $result['content'][0]['text']); + } + + public function testCallToolsRespectsMaxCalls(): void + { + $call = ['name' => 'order_numbers', 'arguments' => new stdClass()]; + + $this->mcpCallTool('call_tools', ['calls' => array_fill(0, 6, $call)]); + + $this->assertMcpJsonRpcError(-32602); + } + + public function testCatalogOffChangesNothing(): void + { + Configure::write('Mcp.catalog.enabled', false); + + $names = array_column($this->mcpListTools(), 'name'); + + $this->assertContains('order_status', $names); + $this->assertNotContains('find_tools', $names); + } + + private function denying(string $denied): ToolAuthorizerInterface + { + return new class ($denied) implements ToolAuthorizerInterface { + public function __construct(private readonly string $denied) + { + } + + public function canCall(mixed $identity, string $tool): bool + { + return $tool !== $this->denied; + } + }; + } +} From e960a934eec71c6ab65a317de62d8d9e1b454a26 Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 20:58:18 +0100 Subject: [PATCH 032/181] Tool catalog: inner calls need their scopes, over HTTP and in tests --- src/Catalog/CatalogScopes.php | 45 +++++++ src/Catalog/ToolCatalog.php | 24 +++- src/Controller/McpController.php | 37 ++++++ src/Middleware/CatalogScopeMiddleware.php | 86 +++++++++++++ src/Server/ServerFactory.php | 13 ++ src/TestSuite/McpTestTrait.php | 7 +- tests/TestCase/Catalog/CatalogScopesTest.php | 77 +++++++++++ tests/TestCase/Catalog/ToolCatalogTest.php | 67 ++++++++++ .../Controller/McpCatalogScopeTest.php | 121 ++++++++++++++++++ 9 files changed, 472 insertions(+), 5 deletions(-) create mode 100644 src/Catalog/CatalogScopes.php create mode 100644 src/Middleware/CatalogScopeMiddleware.php create mode 100644 tests/TestCase/Catalog/CatalogScopesTest.php create mode 100644 tests/TestCase/Controller/McpCatalogScopeTest.php diff --git a/src/Catalog/CatalogScopes.php b/src/Catalog/CatalogScopes.php new file mode 100644 index 0000000..57da75b --- /dev/null +++ b/src/Catalog/CatalogScopes.php @@ -0,0 +1,45 @@ + $patterns `Mcp.catalog.tools`: names outside the catalog add nothing (they are refused). + * @return list Sorted. + */ + public static function required(ScopePolicy $policy, mixed $payload, array $patterns): array + { + $messages = is_array($payload) && array_is_list($payload) ? $payload : [$payload]; + $inner = []; + foreach ($messages as $message) { + if ( + !is_array($message) + || ($message['method'] ?? null) !== 'tools/call' + || ($message['params']['name'] ?? null) !== ToolCatalog::CALL + || !is_array($message['params']['arguments']['calls'] ?? null) + ) { + continue; + } + foreach ($message['params']['arguments']['calls'] as $call) { + $name = is_array($call) ? $call['name'] ?? null : null; + if (is_string($name) && CatalogPatterns::matches($patterns, $name)) { + $inner[] = ['jsonrpc' => '2.0', 'method' => 'tools/call', 'params' => ['name' => $name]]; + } + } + } + $required = $policy->requiredFor($inner === [] ? $payload : [...$messages, ...$inner]); + sort($required); + + return array_values(array_unique($required)); + } +} diff --git a/src/Catalog/ToolCatalog.php b/src/Catalog/ToolCatalog.php index 91e8cb9..4ba332f 100644 --- a/src/Catalog/ToolCatalog.php +++ b/src/Catalog/ToolCatalog.php @@ -14,6 +14,7 @@ use Mcp\Schema\Tool; use Mcp\Server\Handler\Request\CallToolHandler; use Mcp\Server\RequestContext; +use Mcp\Server\Transport\Http\OAuth\ScopePolicy; use Psr\Log\LoggerInterface; /** @@ -34,6 +35,8 @@ final class ToolCatalog * @param int $maxCalls `Mcp.catalog.maxCalls`. * @param \Mcp\Capability\Registry\ReferenceHandlerInterface $references Runs the tools, with the plugin container. * @param \Psr\Log\LoggerInterface $logger The server's logger. + * @param \Mcp\Server\Transport\Http\OAuth\ScopePolicy|null $policy The scope policy, null when tokens are not + * checked (host mode). */ public function __construct( private readonly Registry $registry, @@ -42,6 +45,7 @@ public function __construct( private readonly int $maxCalls, private readonly ReferenceHandlerInterface $references, private readonly LoggerInterface $logger, + private readonly ?ScopePolicy $policy = null, ) { } @@ -70,7 +74,7 @@ public function find(RequestContext $context, string $query = '', int $limit = 1 $ranked = []; foreach ($this->registry->getTools()->references as $name => $tool) { $name = (string)$name; - if (!$this->callable($name)) { + if (!$this->callable($name, $context)) { continue; } $score = $terms === [] ? 1 : $this->score($tool, $terms); @@ -187,11 +191,23 @@ public function inputSchemas(): array * Whether the caller may call $tool through the catalog. * * @param string $tool A tool name. + * @param \Mcp\Server\RequestContext $context The call, for its access token. * @return bool */ - private function callable(string $tool): bool + private function callable(string $tool, RequestContext $context): bool { - return $this->has($tool) && $this->gate->allows($tool); + if (!$this->has($tool) || !$this->gate->allows($tool)) { + return false; + } + $token = $context->getAccessToken(); + if ($this->policy === null || $token === null) { + return true; + } + // The HTTP step already refused a call_tools whose token lacks these; this check stands behind it, and + // keeps find_tools from offering tools the token cannot call. + $required = $this->policy->requiredFor(['method' => 'tools/call', 'params' => ['name' => $tool]]); + + return array_diff($required, $token->getScopes()) === []; } /** @@ -209,7 +225,7 @@ private function runOne( string $name, array $arguments, ): array { - if (!$this->callable($name)) { + if (!$this->callable($name, $context)) { // Like a direct call: a denied tool answers as an unknown one. return $this->error($name, sprintf('Tool not found: "%s".', $name)); } diff --git a/src/Controller/McpController.php b/src/Controller/McpController.php index fbcd65e..ab66196 100644 --- a/src/Controller/McpController.php +++ b/src/Controller/McpController.php @@ -16,6 +16,7 @@ use CakeDC\Mcp\McpConfig; use CakeDC\Mcp\Middleware\AuditRefusalMiddleware; use CakeDC\Mcp\Middleware\BodyLimitMiddleware; +use CakeDC\Mcp\Middleware\CatalogScopeMiddleware; use CakeDC\Mcp\Middleware\IdentityMiddleware; use CakeDC\Mcp\OAuth\AuthSettings; use CakeDC\Mcp\OAuth\ResourceServer; @@ -78,6 +79,10 @@ public function handle(ServerFactory $factory, CurrentIdentity $identity): Respo $middleware[] = new AuditRefusalMiddleware($audit, new AuditWriter($audit), $identity); } $middleware[] = $this->authentication($server, $identity, $responseFactory, $streamFactory, $maxBodyBytes); + $catalog = $this->catalogScopes($server, $responseFactory, $streamFactory, $maxBodyBytes); + if ($catalog !== null) { + $middleware[] = $catalog; + } $transport = new StreamableHttpTransport( $this->request, $responseFactory, @@ -96,6 +101,38 @@ public function handle(ServerFactory $factory, CurrentIdentity $identity): Respo return $this->toCakeResponse($response); } + /** + * With the tool catalog on and access tokens checked, the step that requires the scopes of the tools a + * `call_tools` runs. Null otherwise. + * + * @param string $server The MCP server. + * @param \Cake\Http\ResponseFactory $responseFactory For its 403. + * @param \Cake\Http\StreamFactory $streamFactory For the body it hands on. + * @param int $maxBodyBytes The largest body it reads. + * @return \CakeDC\Mcp\Middleware\CatalogScopeMiddleware|null + */ + private function catalogScopes( + string $server, + ResponseFactory $responseFactory, + StreamFactory $streamFactory, + int $maxBodyBytes, + ): ?CatalogScopeMiddleware { + $settings = AuthSettings::fromConfig($server); + $policy = $settings->mode === AuthSettings::HOST ? null : $settings->scopePolicy(); + if ($policy === null || McpConfig::get('catalog.enabled', $server) !== true) { + return null; + } + + return new CatalogScopeMiddleware( + $policy, + (new ResourceServer($settings))->metadata(), + array_values(array_filter((array)McpConfig::get('catalog.tools', $server), 'is_string')), + $responseFactory, + $streamFactory, + $maxBodyBytes, + ); + } + /** * The middleware that identifies the caller: the host's identity in host mode, an OAuth access * token otherwise. Invalid settings throw, so the endpoint fails closed. diff --git a/src/Middleware/CatalogScopeMiddleware.php b/src/Middleware/CatalogScopeMiddleware.php new file mode 100644 index 0000000..9050380 --- /dev/null +++ b/src/Middleware/CatalogScopeMiddleware.php @@ -0,0 +1,86 @@ + $patterns `Mcp.catalog.tools`. + * @param \Psr\Http\Message\ResponseFactoryInterface $responses For the 403. + * @param \Psr\Http\Message\StreamFactoryInterface $streams To hand the body on. + * @param int $maxBodyBytes The largest body read. + */ + public function __construct( + private readonly ScopePolicy $policy, + private readonly ProtectedResourceMetadata $metadata, + private readonly array $patterns, + private readonly ResponseFactoryInterface $responses, + private readonly StreamFactoryInterface $streams, + private readonly int $maxBodyBytes, + ) { + } + + /** + * @inheritDoc + */ + public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface + { + $token = $request->getAttribute(AccessToken::class); + if ($request->getMethod() !== 'POST' || !$token instanceof AccessToken) { + return $handler->handle($request); + } + $body = $this->readBoundedBody($request->getBody(), $this->maxBodyBytes); + if ($body === null) { + // The body limit before authentication already answered an oversized body. + return $handler->handle($request); + } + // Handed on byte for byte: the transport reads the body again. + $request = $request->withBody($this->streams->createStream($body)); + $required = CatalogScopes::required($this->policy, json_decode($body, true), $this->patterns); + // The token already holds the scopes the policy implies (the SDK middleware expanded them). + if (array_diff($required, $token->getScopes()) === []) { + return $handler->handle($request); + } + + return $this->responses->createResponse(403)->withHeader('WWW-Authenticate', 'Bearer ' . implode(', ', [ + sprintf('resource_metadata="%s"', $this->escape($this->metadata->getMetadataUrl())), + sprintf('scope="%s"', $this->escape(implode(' ', $required))), + 'error="insufficient_scope"', + 'error_description="The access token lacks a required scope."', + ])); + } + + /** + * As the SDK escapes challenge values. + * + * @param string $value A value. + * @return string + */ + private function escape(string $value): string + { + return str_replace(['\\', '"'], ['\\\\', '\\"'], preg_replace('/[\x00-\x1F\x7F]/', '', $value) ?? ''); + } +} diff --git a/src/Server/ServerFactory.php b/src/Server/ServerFactory.php index 1f45f19..72b5530 100644 --- a/src/Server/ServerFactory.php +++ b/src/Server/ServerFactory.php @@ -20,6 +20,7 @@ use CakeDC\Mcp\Identity\CurrentIdentity; use CakeDC\Mcp\Log\McpLogger; use CakeDC\Mcp\McpConfig; +use CakeDC\Mcp\OAuth\AuthSettings; use CakeDC\Mcp\TestSuite\RecordingTransport; use InvalidArgumentException; use Mcp\Capability\Registry; @@ -32,6 +33,7 @@ use Mcp\Server; use Mcp\Server\Builder; use Mcp\Server\Session\Psr16SessionStore; +use Mcp\Server\Transport\Http\OAuth\ScopePolicy; use Psr\Container\ContainerInterface; use Psr\Log\AbstractLogger; use Psr\Log\LoggerInterface; @@ -145,6 +147,7 @@ private function build(bool $trusted, LoggerInterface $logger): Server $this->maxCalls($catalog['maxCalls'] ?? 5), new ReferenceHandler(new ContainerBridge($this->container)), $logger, + $this->scopePolicy(), )); } $audit = AuditSettings::fromConfig($this->server); @@ -347,6 +350,16 @@ private function addCatalog(Builder $builder, ToolCatalog $catalog): void ); } + /** + * @return \Mcp\Server\Transport\Http\OAuth\ScopePolicy|null The server's scope policy; null in host mode. + */ + private function scopePolicy(): ?ScopePolicy + { + $settings = AuthSettings::fromConfig($this->server); + + return $settings->mode === AuthSettings::HOST ? null : $settings->scopePolicy(); + } + /** * @param mixed $value `Mcp.catalog.maxCalls`. * @return int diff --git a/src/TestSuite/McpTestTrait.php b/src/TestSuite/McpTestTrait.php index bf3e1d0..66a6115 100644 --- a/src/TestSuite/McpTestTrait.php +++ b/src/TestSuite/McpTestTrait.php @@ -11,6 +11,7 @@ use Cake\Log\Log; use Cake\Routing\Router; use Cake\Routing\RoutingApplicationInterface; +use CakeDC\Mcp\Catalog\CatalogScopes; use CakeDC\Mcp\Log\McpLogger; use CakeDC\Mcp\McpConfig; use CakeDC\Mcp\Middleware\IdentityMiddleware; @@ -584,7 +585,11 @@ private function mcpRequest(string $method, ?array $params, bool $trusted = fals $settings = AuthSettings::fromConfig($this->_mcpServer); $policy = $settings->mode === AuthSettings::HOST ? null : $settings->scopePolicy(); if ($policy !== null) { - $required = $policy->requiredFor($request); + $catalog = McpConfig::get('catalog.enabled', $this->_mcpServer) === true + ? array_values(array_filter((array)McpConfig::get('catalog.tools', $this->_mcpServer), 'is_string')) + : []; + // call_tools needs the scopes of the catalogued tools it runs, as the endpoint requires. + $required = CatalogScopes::required($policy, $request, $catalog); // In oauth mode the authorization server expands the token's scopes with the `implies` of // the declared resource before the policy sees them; the policy then adds its own `implies`. $granted = $policy->expand((new ResourceServer($settings))->grantedScopes($token->getScopes())); diff --git a/tests/TestCase/Catalog/CatalogScopesTest.php b/tests/TestCase/Catalog/CatalogScopesTest.php new file mode 100644 index 0000000..b0e0c99 --- /dev/null +++ b/tests/TestCase/Catalog/CatalogScopesTest.php @@ -0,0 +1,77 @@ +assertSame(['mcp', 'orders:write'], CatalogScopes::required($this->policy(), $this->call('order_cancel'), self::PATTERNS)); + } + + public function testCallToolsAddsTheScopesOfItsInnerCalls(): void + { + $payload = $this->call('call_tools', ['calls' => [ + ['name' => 'order_status', 'arguments' => []], + ['name' => 'order_cancel', 'arguments' => []], + ]]); + + $this->assertSame(['mcp', 'orders:read', 'orders:write'], CatalogScopes::required($this->policy(), $payload, self::PATTERNS)); + } + + public function testToolsOutsideTheCatalogAddNothing(): void + { + $payload = $this->call('call_tools', ['calls' => [['name' => 'admin_reset', 'arguments' => []]]]); + + $this->assertSame(['mcp'], CatalogScopes::required($this->policy(), $payload, self::PATTERNS)); + } + + public function testABatchAddsUpEveryMessage(): void + { + $payload = [ + $this->call('call_tools', ['calls' => [['name' => 'order_status']]]), + $this->call('call_tools', ['calls' => [['name' => 'order_cancel']]]), + ]; + + $this->assertSame(['mcp', 'orders:read', 'orders:write'], CatalogScopes::required($this->policy(), $payload, self::PATTERNS)); + } + + public function testMalformedCallsAreIgnored(): void + { + $payload = $this->call('call_tools', ['calls' => 'all']); + + $this->assertSame(['mcp'], CatalogScopes::required($this->policy(), $payload, self::PATTERNS)); + $this->assertSame([], CatalogScopes::required(new ScopePolicy(), null, self::PATTERNS)); + } + + private function policy(): ScopePolicy + { + return new ScopePolicy( + default: ['mcp'], + tools: [ + 'order_status' => ['orders:read'], + 'order_cancel' => ['orders:write'], + 'admin_reset' => ['admin'], + ], + ); + } + + /** + * @param array $arguments + * @return array + */ + private function call(string $tool, array $arguments = []): array + { + return ['jsonrpc' => '2.0', 'id' => 1, 'method' => 'tools/call', 'params' => [ + 'name' => $tool, + 'arguments' => $arguments, + ]]; + } +} diff --git a/tests/TestCase/Catalog/ToolCatalogTest.php b/tests/TestCase/Catalog/ToolCatalogTest.php index aa4206d..af92302 100644 --- a/tests/TestCase/Catalog/ToolCatalogTest.php +++ b/tests/TestCase/Catalog/ToolCatalogTest.php @@ -6,9 +6,14 @@ use Cake\Cache\Cache; use Cake\Cache\Engine\ArrayEngine; use Cake\Core\Configure; +use Cake\Core\Container; use Cake\TestSuite\TestCase; use CakeDC\Mcp\Authorization\ToolAuthorizerInterface; +use CakeDC\Mcp\Identity\CurrentIdentity; +use CakeDC\Mcp\Server\ServerFactory; use CakeDC\Mcp\TestSuite\McpTestTrait; +use CakeDC\Mcp\TestSuite\RecordingTransport; +use Mcp\Server\Authorization\AccessToken; use stdClass; /** @@ -30,6 +35,7 @@ protected function setUp(): void protected function tearDown(): void { Cache::drop('mcp_sessions'); + Cache::drop('mcp_oauth_test'); parent::tearDown(); } @@ -134,6 +140,57 @@ public function testCallToolsRespectsMaxCalls(): void $this->assertMcpJsonRpcError(-32602); } + public function testScopeSimulationCoversInnerCalls(): void + { + $this->scoped(); + $this->mcpActingAs(['id' => 1], ['notes:read']); + + $this->mcpCallTool('call_tools', ['calls' => [['name' => 'order_status', 'arguments' => ['number' => 'A-1']]]]); + + $this->assertMcpInsufficientScope(['orders:read']); + } + + public function testFindToolsHidesToolsTheTokenCannotCall(): void + { + $this->scoped(); + $this->mcpActingAs(['id' => 1], ['notes:read']); + + $this->mcpCallTool('find_tools', ['query' => 'order']); + + $this->assertMcpToolSucceeded(); + $names = array_column($this->mcpResult()['structuredContent']['tools'], 'name'); + $this->assertNotContains('order_status', $names); + $this->assertContains('order_numbers', $names); + } + + public function testEachInnerCallChecksItsScopesInTheServer(): void + { + // Straight to the server, past the HTTP step and the trait's simulation: only the server's own check stands. + $this->scoped(); + $container = new Container(); + $identity = new CurrentIdentity(); + $container->addShared(CurrentIdentity::class, $identity); + $identity->set(['id' => 1]); + $transport = new RecordingTransport(array_map(fn(array $message): string => (string)json_encode($message), [ + ['jsonrpc' => '2.0', 'id' => 1, 'method' => 'initialize', 'params' => [ + 'protocolVersion' => '2025-06-18', + 'capabilities' => new stdClass(), + 'clientInfo' => ['name' => 'test', 'version' => '1.0'], + ]], + ['jsonrpc' => '2.0', 'method' => 'notifications/initialized'], + ['jsonrpc' => '2.0', 'id' => 2, 'method' => 'tools/call', 'params' => [ + 'name' => 'call_tools', + 'arguments' => ['calls' => [['name' => 'order_status', 'arguments' => ['number' => 'A-1']]]], + ]], + ]), new AccessToken(['notes:read'], ['sub' => '1'])); + + (new ServerFactory($container, $identity))->create()->run($transport); + + $result = $transport->responseFor(2)['result']['structuredContent']['results'][0] ?? []; + $this->assertTrue($result['isError'] ?? false); + $this->assertSame('Tool not found: "order_status".', $result['content'][0]['text'] ?? null); + } + public function testCatalogOffChangesNothing(): void { Configure::write('Mcp.catalog.enabled', false); @@ -144,6 +201,16 @@ public function testCatalogOffChangesNothing(): void $this->assertNotContains('find_tools', $names); } + private function scoped(): void + { + Cache::setConfig('mcp_oauth_test', ['className' => ArrayEngine::class]); + Configure::write('Mcp.auth', [ + 'mode' => 'external', + 'scopes' => ['tools' => ['order_status' => ['orders:read']]], + 'external' => ['issuer' => 'https://issuer.example', 'cache' => 'mcp_oauth_test'], + ]); + } + private function denying(string $denied): ToolAuthorizerInterface { return new class ($denied) implements ToolAuthorizerInterface { diff --git a/tests/TestCase/Controller/McpCatalogScopeTest.php b/tests/TestCase/Controller/McpCatalogScopeTest.php new file mode 100644 index 0000000..bb5f4de --- /dev/null +++ b/tests/TestCase/Controller/McpCatalogScopeTest.php @@ -0,0 +1,121 @@ + ArrayEngine::class]); + Configure::write('Mcp.discovery.scanDirs', ['src/McpDocs']); + Configure::write('Mcp.catalog', ['enabled' => true, 'tools' => ['order_*', 'find_order']]); + Configure::write('Mcp.auth', [ + 'mode' => 'external', + 'scopes' => [ + 'tools' => ['order_status' => ['orders:read'], 'find_order' => ['orders:admin']], + 'implies' => ['orders:admin' => ['orders:read']], + ], + 'external' => ['issuer' => TestJwt::ISSUER, 'cache' => 'mcp_oauth_test', 'httpClient' => TestJwt::client()], + ]); + } + + protected function tearDown(): void + { + Cache::drop('mcp_oauth_test'); + parent::tearDown(); + } + + public function testAnInnerToolScopeIsRequiredOverHttp(): void + { + $this->callTools([['name' => 'order_status', 'arguments' => ['number' => 'A-1']]], 'notes:read'); + + $this->assertResponseCode(403); + $header = $this->_response->getHeaderLine('WWW-Authenticate'); + $this->assertStringContainsString('resource_metadata="http://localhost/.well-known/oauth-protected-resource/mcp"', $header); + $this->assertStringContainsString('scope="orders:read"', $header); + $this->assertStringContainsString('error="insufficient_scope"', $header); + + $this->callTools([['name' => 'order_status', 'arguments' => ['number' => 'A-1']]], 'orders:read'); + $this->assertResponseOk(); + } + + public function testImpliedScopesSatisfyInnerCalls(): void + { + $this->callTools([ + ['name' => 'order_status', 'arguments' => ['number' => 'A-1']], + ['name' => 'find_order', 'arguments' => ['number' => 'A-1']], + ], 'orders:admin'); + + $this->assertResponseOk(); + } + + public function testBatchAddsUpInnerScopes(): void + { + // A token that covers only the first call. + $this->configRequest(['headers' => $this->headers('orders:read')]); + $this->post('/mcp', (string)json_encode([ + $this->message(1, [['name' => 'order_status', 'arguments' => ['number' => 'A-1']]]), + $this->message(2, [['name' => 'find_order', 'arguments' => ['number' => 'A-1']]]), + ])); + + $this->assertResponseCode(403); + $this->assertStringContainsString('scope="orders:admin orders:read"', $this->_response->getHeaderLine('WWW-Authenticate')); + } + + /** + * @param list> $calls + */ + private function callTools(array $calls, string $scope): void + { + $this->configRequest(['headers' => $this->headers($scope) + [ + 'MCP-Protocol-Version' => '2026-07-28', + 'Mcp-Method' => 'tools/call', + 'Mcp-Name' => 'call_tools', + ]]); + $this->post('/mcp', (string)json_encode($this->message(1, $calls))); + } + + /** + * @param list> $calls + * @return array + */ + private function message(int $id, array $calls): array + { + return ['jsonrpc' => '2.0', 'id' => $id, 'method' => 'tools/call', 'params' => [ + 'name' => 'call_tools', + 'arguments' => ['calls' => $calls], + '_meta' => [ + 'io.modelcontextprotocol/protocolVersion' => '2026-07-28', + 'io.modelcontextprotocol/clientCapabilities' => new stdClass(), + ], + ]]; + } + + /** + * @return array + */ + private function headers(string $scope): array + { + return [ + 'Host' => 'localhost', + 'Accept' => 'application/json, text/event-stream', + 'Content-Type' => 'application/json', + 'Authorization' => 'Bearer ' . TestJwt::token(['scope' => $scope]), + ]; + } +} From 6c9769047f74727125606f850cdd879f69e8fc8f Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 21:00:49 +0100 Subject: [PATCH 033/181] Tool catalog: audit inner calls, mcp check, docs --- CHANGELOG.md | 1 + docs/configuration.md | 3 ++ docs/tools.md | 36 ++++++++++++++++ src/Audit/AuditRecord.php | 4 +- src/Audit/AuditWriter.php | 3 ++ src/Catalog/ToolCatalog.php | 32 ++++++++++++-- src/Command/McpCheckCommand.php | 43 ++++++++++++++++++- src/Event/AuditListener.php | 15 +++++++ src/Server/ServerFactory.php | 35 +++++++++++++++ tests/TestCase/Audit/AuditWriterTest.php | 8 ++++ tests/TestCase/Catalog/ToolCatalogTest.php | 40 +++++++++++++++++ .../TestCase/Command/McpCheckCommandTest.php | 25 +++++++++++ 12 files changed, 239 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 81ecaf0..8fc58d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- Tool catalog (`Mcp.catalog`): chosen tools leave `tools/list` and are reached with `find_tools` and `call_tools`; every inner call goes through the authorizer, the tool scopes (a `403 insufficient_scope` over HTTP), the input schema and the audit (`via=call_tools`). `mcp check` reports it on a new `Catalog` line, and its `Tool schemas` line covers catalogued tools. - `McpTestTrait` runs tools that report progress or log through the SDK's `ClientGateway` (they used to get no response in tests) and records their notifications: `mcpNotifications()`, `assertMcpProgressSent()`, `assertMcpNotificationSent()`. A tool that asks the client something fails with a clear message. - Docs: progress and logs from a tool, and what buffers server-sent events (PHP output buffering, compression, proxies). - `#[McpWhen]` registers a tool, resource, resource template or prompt only when a config value is on or a callback (given the server name) returns true; `mcp check` lists what was skipped on a new `Conditions` line. diff --git a/docs/configuration.md b/docs/configuration.md index 3605b83..a629b52 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -50,6 +50,9 @@ want to change; everything else keeps its default. These are the defaults - `server.title`, `server.description`, `server.websiteUrl`: optional, also reported to clients. `null` sends none. - `server.instructions`: optional text telling the client's model how to use your server. `null` sends none. - `server.cache`: the cache hints of the 2026-07-28 protocol revision, which tell a client how long it may keep a result of `server/discover`, `tools/list`, `prompts/list`, `resources/list`, `resources/templates/list` and `resources/read`. `null` (the default) marks them private and not to be cached. Otherwise an array: `ttl` in milliseconds (default `0`), `scope` `'private'` (one user, the default) or `'public'` (any user, only for results that are the same for everyone), and `methods` to set them per method, for example `['ttl' => 60000, 'methods' => ['tools/list' => ['ttl' => 300000]]]`. Clients of the older revisions get no hints. A top-level `scope` applies to all six methods, so use `'public'` only per method, for results that are the same for every user: keep `tools/list` private when the authorizer gives users different tools, and `resources/read` private when a resource depends on who reads it. `bin/cake mcp check` warns, on its `Cache hints` line, when either is public. +- `catalog.enabled`: `true` turns on the tool catalog for this server (see [Tool catalog](tools.md#tool-catalog)). Default `false`. +- `catalog.tools`: the tools behind the catalog, as names or `fnmatch()` patterns (`report_*`). They leave `tools/list` and are reached with `find_tools` and `call_tools`. +- `catalog.maxCalls`: how many tools one `call_tools` may run, a positive integer. Default `5`. - `server.configure`: optional callable that receives the SDK `Mcp\Server\Builder` before the server is built. See [Using the SDK builder](#using-the-sdk-builder). - `discovery.scanDirs`: directories (relative to `ROOT`) scanned for attributes. Missing directories are skipped. - `discovery.excludeDirs`: directories to skip while scanning. diff --git a/docs/tools.md b/docs/tools.md index 2847707..81398e9 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -192,6 +192,42 @@ them (see [Testing](testing.md)). (`elicit()`) something. Those need a client that supports them, and they cannot be answered in `McpTestTrait` tests. +## Tool catalog + +A server with many tools sends every schema to the model on every turn. The tool +catalog keeps chosen tools out of `tools/list` and gives the model two tools to +reach them instead: + +```php +'Mcp' => [ + 'catalog' => [ + 'enabled' => true, + 'tools' => ['report_*', 'export_orders'], // names or fnmatch() patterns + 'maxCalls' => 5, // tools one call_tools may run + ], +], +``` + +- `find_tools` takes a `query` (words to look for) and a `limit` (1 to 50, + default 10), and returns the matching tools with their descriptions and input + schemas, best matches first. It only returns tools the caller may call. +- `call_tools` takes `calls`, a list of `{"name": ..., "arguments": {...}}`, runs + them in order and returns each result. It stops at the first error. + +Each tool `call_tools` runs is checked like a direct `tools/call`: the +authorizer (a denied tool answers like an unknown one), the scopes of +`Mcp.auth.scopes.tools`, and the tool's input schema. Over HTTP, a `call_tools` +whose token lacks the scope of a tool it runs gets the same `403 +insufficient_scope` as a direct call, naming the missing scopes, so the client +can ask for them. Each inner call writes its own audit record under its own +name, with `via=call_tools`. `find_tools` and `call_tools` themselves are never +refused by the authorizer: what they run is. + +Catalogued tools can still be called directly by name, so clients that already +know them keep working. `bin/cake mcp check` lists the catalogued tools on its +`Catalog` line, warns about patterns that match no tool, and checks their +schemas on its `Tool schemas` line. + ## Registering only when `#[McpWhen]` (`CakeDC\Mcp\Attribute\McpWhen`) registers a tool, resource, diff --git a/src/Audit/AuditRecord.php b/src/Audit/AuditRecord.php index 0fe6555..a18ecab 100644 --- a/src/Audit/AuditRecord.php +++ b/src/Audit/AuditRecord.php @@ -38,6 +38,7 @@ final class AuditRecord * @param array $arguments Arguments, already redacted and truncated. * @param string|null $error Error message, for the outcomes that are not `ok`. * @param int|null $durationMs Duration, null when it is not known. + * @param string|null $via The plugin tool that made the call (`call_tools`), null for a direct call. */ public function __construct( public readonly string $method, @@ -50,6 +51,7 @@ public function __construct( public readonly array $arguments, public readonly ?string $error, public readonly ?int $durationMs, + public readonly ?string $via = null, ) { } @@ -80,6 +82,6 @@ public function toArray(): array 'arguments' => $this->arguments, 'error' => $this->error, 'durationMs' => $this->durationMs, - ]; + ] + ($this->via === null ? [] : ['via' => $this->via]); } } diff --git a/src/Audit/AuditWriter.php b/src/Audit/AuditWriter.php index 8e91569..66d3531 100644 --- a/src/Audit/AuditWriter.php +++ b/src/Audit/AuditWriter.php @@ -126,6 +126,9 @@ private function line(AuditRecord $record): string if ($this->settings->server !== McpConfig::DEFAULT_SERVER) { $line .= ' server=' . $this->field($this->settings->server); } + if ($record->via !== null) { + $line .= ' via=' . $this->field($record->via); + } if ($this->settings->arguments) { $line .= ' args=' . json_encode((object)$record->arguments, self::JSON_FLAGS); } diff --git a/src/Catalog/ToolCatalog.php b/src/Catalog/ToolCatalog.php index 4ba332f..4d54239 100644 --- a/src/Catalog/ToolCatalog.php +++ b/src/Catalog/ToolCatalog.php @@ -4,8 +4,12 @@ namespace CakeDC\Mcp\Catalog; use CakeDC\Mcp\Authorization\ToolGate; +use CakeDC\Mcp\Schema\SchemaNormalizer; use Mcp\Capability\Registry; use Mcp\Capability\Registry\ReferenceHandlerInterface; +use Mcp\Event\ErrorEvent; +use Mcp\Event\RequestEvent; +use Mcp\Event\ResponseEvent; use Mcp\Exception\ToolCallException; use Mcp\Schema\Content\TextContent; use Mcp\Schema\JsonRpc\Error; @@ -15,6 +19,7 @@ use Mcp\Server\Handler\Request\CallToolHandler; use Mcp\Server\RequestContext; use Mcp\Server\Transport\Http\OAuth\ScopePolicy; +use Psr\EventDispatcher\EventDispatcherInterface; use Psr\Log\LoggerInterface; /** @@ -28,6 +33,11 @@ final class ToolCatalog public const FIND = 'find_tools'; public const CALL = 'call_tools'; + /** + * Meta key of the calls the catalog makes, read by the audit (`via=call_tools`). + */ + public const VIA_META = 'io.cakedc.mcp/via'; + /** * @param \Mcp\Capability\Registry $registry The server's registry. * @param \CakeDC\Mcp\Authorization\ToolGate $gate The server's gate. @@ -37,6 +47,9 @@ final class ToolCatalog * @param \Psr\Log\LoggerInterface $logger The server's logger. * @param \Mcp\Server\Transport\Http\OAuth\ScopePolicy|null $policy The scope policy, null when tokens are not * checked (host mode). + * @param \Psr\EventDispatcher\EventDispatcherInterface|null $events The server's events: each inner call is + * announced like a direct one, so the audit records it. + * @param bool $normalize `Mcp.schema.normalize`: the schemas find_tools returns follow it, as tools/list does. */ public function __construct( private readonly Registry $registry, @@ -46,6 +59,8 @@ public function __construct( private readonly ReferenceHandlerInterface $references, private readonly LoggerInterface $logger, private readonly ?ScopePolicy $policy = null, + private readonly ?EventDispatcherInterface $events = null, + private readonly bool $normalize = false, ) { } @@ -89,7 +104,9 @@ public function find(RequestContext $context, string $query = '', int $limit = 1 'name' => $tool->name, 'title' => $tool->title, 'description' => $tool->description, - 'inputSchema' => $tool->inputSchema, + 'inputSchema' => $this->normalize + ? SchemaNormalizer::normalize($tool->inputSchema) + : $tool->inputSchema, ]; } @@ -225,15 +242,22 @@ private function runOne( string $name, array $arguments, ): array { + $meta = [self::VIA_META => self::CALL] + ($context->getRequest()->getMeta() ?? []); + $request = (new CallToolRequest($name, $arguments))->withId($id)->withMeta($meta); + $session = $context->getSession(); + $this->events?->dispatch(new RequestEvent($request, $session)); if (!$this->callable($name, $context)) { // Like a direct call: a denied tool answers as an unknown one. - return $this->error($name, sprintf('Tool not found: "%s".', $name)); + $response = Error::forInvalidParams(sprintf('Tool not found: "%s".', $name), $id); + } else { + $response = $handler->handle($request, $session); } - $request = (new CallToolRequest($name, $arguments))->withId($id)->withMeta($context->getRequest()->getMeta()); - $response = $handler->handle($request, $context->getSession()); if ($response instanceof Error) { + $this->events?->dispatch(new ErrorEvent($response, $request, $session, null)); + return $this->error($name, $response->message); } + $this->events?->dispatch(new ResponseEvent($response, $request, $session)); $result = $response->result; if (!$result instanceof CallToolResult) { return $this->error($name, 'The tool returned no result.'); diff --git a/src/Command/McpCheckCommand.php b/src/Command/McpCheckCommand.php index 8ba62ef..c954ac4 100644 --- a/src/Command/McpCheckCommand.php +++ b/src/Command/McpCheckCommand.php @@ -28,6 +28,8 @@ use CakeDC\Mcp\Audit\AuditWriter; use CakeDC\Mcp\Authorization\AllowAllToolAuthorizer; use CakeDC\Mcp\Authorization\RbacToolAuthorizer; +use CakeDC\Mcp\Catalog\CatalogPatterns; +use CakeDC\Mcp\Catalog\ToolCatalog; use CakeDC\Mcp\Identity\CurrentIdentity; use CakeDC\Mcp\Log\McpLogger; use CakeDC\Mcp\McpConfig; @@ -244,6 +246,7 @@ protected function checks(): array 'Tools' => fn(): array => $this->toolsCheck(), 'Tool schemas' => fn(): array => $this->toolSchemas(), 'Conditions' => fn(): array => $this->conditions(), + 'Catalog' => fn(): array => $this->catalog(), 'Authorizer' => fn(): array => $this->authorizerCheck(), 'Tool scopes' => fn(): array => $this->toolScopes(), 'Cache hints' => fn(): array => $this->cacheHints(), @@ -279,6 +282,43 @@ private function toolNames(): array return array_map(fn(array $tool): string => (string)$tool['name'], $this->toolDefinitions()); } + /** + * @return array{0: 'pass'|'warn'|'fail', 1: string} + */ + private function catalog(): array + { + if (McpConfig::get('catalog.enabled', $this->server) !== true) { + return ['pass', 'off']; + } + $patterns = array_values(array_filter((array)McpConfig::get('catalog.tools', $this->server), 'is_string')); + $tools = array_diff( + array_column($this->factory()->registeredToolDefinitions(), 'name'), + [ToolCatalog::FIND, ToolCatalog::CALL], + ); + $catalogued = array_values(array_filter($tools, fn(string $tool): bool => CatalogPatterns::matches( + $patterns, + $tool, + ))); + sort($catalogued); + $unused = array_values(array_filter($patterns, fn(string $pattern): bool => array_filter( + $tools, + fn(string $tool): bool => fnmatch($pattern, $tool), + ) === [])); + if ($unused !== []) { + return ['warn', sprintf( + '%s matches no tool (Mcp.catalog.tools), see %s', + implode(', ', $unused), + self::DOCS . 'tools.md#tool-catalog', + )]; + } + + return ['pass', sprintf( + '%d tools behind find_tools and call_tools: %s', + count($catalogued), + self::names($catalogued), + )]; + } + /** * @return array{0: 'pass'|'warn'|'fail', 1: string} */ @@ -294,7 +334,8 @@ private function conditions(): array */ private function toolSchemas(): array { - $tools = $this->toolDefinitions(); + // Registered tools, catalogued ones included: find_tools hands their schemas to the model too. + $tools = $this->factory()->registeredToolDefinitions(); if ($tools === []) { return ['pass', 'no tools to check']; } diff --git a/src/Event/AuditListener.php b/src/Event/AuditListener.php index df9d384..c1b11e0 100644 --- a/src/Event/AuditListener.php +++ b/src/Event/AuditListener.php @@ -8,6 +8,7 @@ use CakeDC\Mcp\Audit\AuditSettings; use CakeDC\Mcp\Audit\AuditWriter; use CakeDC\Mcp\Authorization\ToolGate; +use CakeDC\Mcp\Catalog\ToolCatalog; use CakeDC\Mcp\Identity\CurrentIdentity; use CakeDC\Mcp\Log\McpLogger; use Closure; @@ -228,9 +229,23 @@ private function record(Request $request, SessionInterface $session, string $out $this->writer->arguments($arguments), $error === null ? null : mb_substr($error, 0, self::MAX_ERROR_LENGTH), $start === null ? null : (int)round((($this->clock)() - $start) * 1000), + self::viaOf($request), )); } + /** + * The plugin tool that made this call (the tool catalog marks the calls it makes), or null. + * + * @param \Mcp\Schema\JsonRpc\Request $request The request. + * @return string|null + */ + private static function viaOf(Request $request): ?string + { + $via = $request->getMeta()[ToolCatalog::VIA_META] ?? null; + + return is_string($via) ? $via : null; + } + /** * Whether the gate refused an existing tool (an unknown tool is not a denial). * diff --git a/src/Server/ServerFactory.php b/src/Server/ServerFactory.php index 72b5530..0aed873 100644 --- a/src/Server/ServerFactory.php +++ b/src/Server/ServerFactory.php @@ -21,6 +21,7 @@ use CakeDC\Mcp\Log\McpLogger; use CakeDC\Mcp\McpConfig; use CakeDC\Mcp\OAuth\AuthSettings; +use CakeDC\Mcp\Schema\SchemaNormalizer; use CakeDC\Mcp\TestSuite\RecordingTransport; use InvalidArgumentException; use Mcp\Capability\Registry; @@ -56,6 +57,11 @@ final class ServerFactory */ private array $skipped = []; + /** + * The registry of the last build. + */ + private ?Registry $lastRegistry = null; + /** * @param \Psr\Container\ContainerInterface $container The host container. * @param \CakeDC\Mcp\Identity\CurrentIdentity $identity The shared current identity. @@ -148,6 +154,8 @@ private function build(bool $trusted, LoggerInterface $logger): Server new ReferenceHandler(new ContainerBridge($this->container)), $logger, $this->scopePolicy(), + $events, + McpConfig::get('schema.normalize', $this->server) === true, )); } $audit = AuditSettings::fromConfig($this->server); @@ -205,6 +213,7 @@ private function build(bool $trusted, LoggerInterface $logger): Server $server = $builder->build(); $this->skipped = Conditions::prune($registry, $this->server); + $this->lastRegistry = $registry; return $server; } @@ -374,6 +383,32 @@ private function maxCalls(mixed $value): int return $value; } + /** + * Every tool registered on this server, including those the tool catalog keeps out of `tools/list`, as a + * trusted client would see them (schemas normalized when `schema.normalize` is on), decoded from JSON. + * + * @internal Used by `bin/cake mcp check`; not part of the public API. + * @return list> Each tool has a string `name`. + */ + public function registeredToolDefinitions(): array + { + $this->build(true, $this->quietLogger()); + $normalize = McpConfig::get('schema.normalize', $this->server) === true; + $tools = []; + foreach ($this->lastRegistry?->getTools()->references ?? [] as $tool) { + $definition = json_decode((string)json_encode($tool), true); + if (!is_array($definition) || !is_string($definition['name'] ?? null)) { + continue; + } + if ($normalize && is_array($definition['inputSchema'] ?? null)) { + $definition['inputSchema'] = SchemaNormalizer::normalize($definition['inputSchema']); + } + $tools[] = $definition; + } + + return $tools; + } + /** * What `#[McpWhen]` leaves out of this server, as a trusted client would see it. * diff --git a/tests/TestCase/Audit/AuditWriterTest.php b/tests/TestCase/Audit/AuditWriterTest.php index 2919944..aaf3fa6 100644 --- a/tests/TestCase/Audit/AuditWriterTest.php +++ b/tests/TestCase/Audit/AuditWriterTest.php @@ -110,6 +110,14 @@ public function testNamedServerRecordsCarryTheServer(): void $this->assertSame('admin', $this->events[0]->getData()['server'] ?? null); } + public function testViaIsWrittenWhenSet(): void + { + $this->writer()->write($this->record(['via' => 'call_tools'])); + + $this->assertStringContainsString(' request=2 via=call_tools args=', $this->lines()[0]); + $this->assertSame('call_tools', $this->events[0]->getData()['via'] ?? null); + } + public function testDefaultServerRecordsHaveNoServerField(): void { $this->writer()->write($this->record()); diff --git a/tests/TestCase/Catalog/ToolCatalogTest.php b/tests/TestCase/Catalog/ToolCatalogTest.php index af92302..80d4350 100644 --- a/tests/TestCase/Catalog/ToolCatalogTest.php +++ b/tests/TestCase/Catalog/ToolCatalogTest.php @@ -7,6 +7,8 @@ use Cake\Cache\Engine\ArrayEngine; use Cake\Core\Configure; use Cake\Core\Container; +use Cake\Log\Engine\ArrayLog; +use Cake\Log\Log; use Cake\TestSuite\TestCase; use CakeDC\Mcp\Authorization\ToolAuthorizerInterface; use CakeDC\Mcp\Identity\CurrentIdentity; @@ -64,6 +66,19 @@ public function testFindToolsRanksByNameTitleAndDescription(): void $this->assertNotContains('orders_compact', array_column($tools, 'name')); } + public function testFindToolsFollowsTheSchemaNormalizer(): void + { + Configure::write('Mcp.discovery.scanDirs', ['src/McpSchema']); + Configure::write('Mcp.catalog.tools', ['report']); + Configure::write('Mcp.schema.normalize', true); + + $this->mcpCallTool('find_tools', ['query' => 'report']); + + $this->assertMcpToolSucceeded(); + $schema = $this->mcpResult()['structuredContent']['tools'][0]['inputSchema']; + $this->assertSame('string', $schema['properties']['date_from']['type']); + } + public function testFindToolsWithAnEmptyQuery(): void { $this->mcpCallTool('find_tools', ['limit' => 3]); @@ -191,6 +206,31 @@ public function testEachInnerCallChecksItsScopesInTheServer(): void $this->assertSame('Tool not found: "order_status".', $result['content'][0]['text'] ?? null); } + public function testInnerCallsAreAuditedUnderTheirOwnName(): void + { + Log::setConfig('audit_catalog', ['className' => ArrayLog::class, 'scopes' => ['mcp_audit']]); + Configure::write('Mcp.audit.enabled', true); + Configure::write('Mcp.authorization.authorizer', $this->denying('find_order')); + try { + $this->mcpCallTool('call_tools', ['calls' => [ + ['name' => 'order_status', 'arguments' => ['number' => 'A-1']], + ['name' => 'find_order', 'arguments' => ['number' => 'A-1']], + ]]); + + $engine = Log::engine('audit_catalog'); + $lines = array_map('strval', $engine instanceof ArrayLog ? $engine->read() : []); + $this->assertCount(3, $lines); + $this->assertStringContainsString('MCP tools/call order_status ok', $lines[0]); + $this->assertStringContainsString(' via=call_tools', $lines[0]); + $this->assertStringContainsString('MCP tools/call find_order denied', $lines[1]); + $this->assertStringContainsString(' via=call_tools', $lines[1]); + $this->assertStringContainsString('MCP tools/call call_tools tool_error', $lines[2]); + $this->assertStringNotContainsString('via=', $lines[2]); + } finally { + Log::drop('audit_catalog'); + } + } + public function testCatalogOffChangesNothing(): void { Configure::write('Mcp.catalog.enabled', false); diff --git a/tests/TestCase/Command/McpCheckCommandTest.php b/tests/TestCase/Command/McpCheckCommandTest.php index 2554658..bdf029e 100644 --- a/tests/TestCase/Command/McpCheckCommandTest.php +++ b/tests/TestCase/Command/McpCheckCommandTest.php @@ -639,6 +639,31 @@ public function testSharedResourceFails(): void $this->assertOutputContains('share the resource ' . OAuthTestConfig::MCP); } + public function testToolSchemasCoverCataloguedTools(): void + { + Configure::write('Mcp.discovery.scanDirs', ['src/McpSchema']); + Configure::write('Mcp.catalog', ['enabled' => true, 'tools' => ['report']]); + + $this->exec('mcp check'); + + $this->assertOutputContains('[WARN] Tool schemas: report.date_from: type union null|string'); + } + + public function testCatalogLine(): void + { + $this->exec('mcp check'); + $this->assertOutputContains('[PASS] Catalog: off'); + + Configure::write('Mcp.discovery.scanDirs', ['src/McpDocs']); + Configure::write('Mcp.catalog', ['enabled' => true, 'tools' => ['order_*', 'find_order']]); + $this->exec('mcp check'); + $this->assertOutputContains('[PASS] Catalog: 4 tools behind find_tools and call_tools: find_order, order_numbers'); + + Configure::write('Mcp.catalog.tools', ['order_*', 'nope_*']); + $this->exec('mcp check'); + $this->assertOutputContains('[WARN] Catalog: nope_* matches no tool'); + } + public function testConditionsListSkippedElements(): void { $this->exec('mcp check'); From 97e2dd40fa58530c3312da5c5646facf08f7d4f7 Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 21:05:20 +0100 Subject: [PATCH 034/181] MCP Apps: extension, bridge and app resources from Cake views --- resources/ext-apps/LICENSE | 216 ++++++++++++++++++++ resources/ext-apps/README.md | 23 +++ resources/ext-apps/app-with-deps-2.0.4.js | 104 ++++++++++ src/App/AppBridge.php | 50 +++++ src/App/AppView.php | 44 ++++ src/McpConfig.php | 1 + src/Server/ServerFactory.php | 4 + templates/layout/app.php | 22 ++ tests/TestCase/App/AppBridgeTest.php | 29 +++ tests/TestCase/App/McpAppsTest.php | 103 ++++++++++ tests/test_app/src/McpApps/InboxApp.php | 40 ++++ tests/test_app/templates/McpApps/broken.php | 7 + tests/test_app/templates/McpApps/inbox.php | 13 ++ 13 files changed, 656 insertions(+) create mode 100644 resources/ext-apps/LICENSE create mode 100644 resources/ext-apps/README.md create mode 100644 resources/ext-apps/app-with-deps-2.0.4.js create mode 100644 src/App/AppBridge.php create mode 100644 src/App/AppView.php create mode 100644 templates/layout/app.php create mode 100644 tests/TestCase/App/AppBridgeTest.php create mode 100644 tests/TestCase/App/McpAppsTest.php create mode 100644 tests/test_app/src/McpApps/InboxApp.php create mode 100644 tests/test_app/templates/McpApps/broken.php create mode 100644 tests/test_app/templates/McpApps/inbox.php diff --git a/resources/ext-apps/LICENSE b/resources/ext-apps/LICENSE new file mode 100644 index 0000000..4a93985 --- /dev/null +++ b/resources/ext-apps/LICENSE @@ -0,0 +1,216 @@ +The MCP project is undergoing a licensing transition from the MIT License to the Apache License, Version 2.0 ("Apache-2.0"). All new code and specification contributions to the project are licensed under Apache-2.0. Documentation contributions (excluding specifications) are licensed under CC-BY-4.0. + +Contributions for which relicensing consent has been obtained are licensed under Apache-2.0. Contributions made by authors who originally licensed their work under the MIT License and who have not yet granted explicit permission to relicense remain licensed under the MIT License. + +No rights beyond those granted by the applicable original license are conveyed for such contributions. + +--- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to the Licensor for inclusion in the Work by the copyright + owner or by an individual or Legal Entity authorized to submit on behalf + of the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + +--- + +MIT License + +Copyright (c) 2024-2025 Model Context Protocol a Series of LF Projects, LLC. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +Creative Commons Attribution 4.0 International (CC-BY-4.0) + +Documentation in this project (excluding specifications) is licensed under +CC-BY-4.0. See https://creativecommons.org/licenses/by/4.0/legalcode for +the full license text. diff --git a/resources/ext-apps/README.md b/resources/ext-apps/README.md new file mode 100644 index 0000000..cf0d165 --- /dev/null +++ b/resources/ext-apps/README.md @@ -0,0 +1,23 @@ +# MCP Apps client (vendored) + +`app-with-deps-2.0.4.js` is `dist/src/app-with-deps.js` of the npm package +`@modelcontextprotocol/ext-apps` 2.0.4, the official MCP Apps client of the +Model Context Protocol project, unchanged. `LICENSE` is the package's license. + +- Package tarball integrity (npm): `sha512-B+PcbuGiaf0e5I3uy4iO5tS3Abo+5w8JvZFzHMzQdq9yVwP836zJkw2+KCGOQ0r4TM1fuQi4JdnbuWjkS4aBvg==` +- SHA-512 of `app-with-deps-2.0.4.js` (base64): `wbn1NozhekXAEbh+3h8/n1udATIrngdzSuQynu9d4EywxFfbiE5Q/Wh+GOf6WD88jzX9Nrb3dMg+HzVEDhMC1Q==` + +`CakeDC\Mcp\App\AppBridge` inlines it in the `CakeDC/Mcp.app` layout, turning +its final `export{...}` into `globalThis.McpApps = {...}` at render time, so the +file stays as published and the app's script uses `McpApps.App`. + +## Updating + +1. Download the new version's tarball from npm and check its integrity against + `npm view @modelcontextprotocol/ext-apps@ dist.integrity`. +2. Copy `package/dist/src/app-with-deps.js` here as `app-with-deps-.js`, + and `package/LICENSE` over `LICENSE`. +3. Update `AppBridge::FILE`, the two values above, and the version in + `tests/TestCase/App/AppBridgeTest.php`. +4. Run the test suite: `AppBridgeTest` checks that the file still ends with the + `export{...}` the bridge rewrites. diff --git a/resources/ext-apps/app-with-deps-2.0.4.js b/resources/ext-apps/app-with-deps-2.0.4.js new file mode 100644 index 0000000..027325e --- /dev/null +++ b/resources/ext-apps/app-with-deps-2.0.4.js @@ -0,0 +1,104 @@ +var TB=Object.defineProperty;var SB=($)=>$;function AB($,v){this[$]=SB.bind(null,v)}var zv=($,v)=>{for(var D in v)TB($,D,{get:v[D],enumerable:!0,configurable:!0,set:AB.bind(v,D)})};var{create:ZB,defineProperty:Vg,getOwnPropertyDescriptor:LB,getOwnPropertyNames:EB,getPrototypeOf:VB}=Object,kB=Object.prototype.hasOwnProperty,L9=($,v)=>()=>(v||$((v={exports:{}}).exports,v),v.exports),E9=($,v)=>{let D={};for(var g in $)Vg(D,g,{get:$[g],enumerable:!0});if(v)Vg(D,Symbol.toStringTag,{value:"Module"});return D},RB=($,v,D,g)=>{if(v&&typeof v==="object"||typeof v==="function"){for(var I=EB(v),_=0,N=I.length,b;_v[U]).bind(null,b),enumerable:!(g=LB(v,b))||g.enumerable})}return $},V9=($,v,D)=>(D=$!=null?ZB(VB($)):{},RB(v||!$||!$.__esModule?Vg(D,"default",{value:$,enumerable:!0}):D,$));var CB=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]);function k9($){return typeof $==="string"&&CB.has($.replace(/#$/,""))}var Q={};zv(Q,{xor:()=>n8,xid:()=>W8,withParser:()=>MN,void:()=>y8,validateAsync:()=>R_,validate:()=>k_,uuidv7:()=>D8,uuidv6:()=>_8,uuidv4:()=>I8,uuid:()=>v8,util:()=>w,url:()=>t4,uppercase:()=>V4,unknown:()=>x,union:()=>E,undefined:()=>f8,ulid:()=>X8,uint64:()=>C8,uint32:()=>V8,tuple:()=>WQ,trim:()=>u4,treeifyError:()=>LU,transform:()=>Zb,toZod:()=>H_,toUpperCase:()=>l4,toLowerCase:()=>i4,toJSONSchema:()=>Z6,templateLiteral:()=>$G,symbol:()=>x8,superRefine:()=>xQ,success:()=>o8,stringbool:()=>UG,stringFormat:()=>q8,string:()=>X,strictObject:()=>l8,startsWith:()=>R4,slugify:()=>n4,size:()=>M6,setErrorMap:()=>_z,set:()=>d8,safeParseAsync:()=>lW,safeParse:()=>JD,safeEncodeAsync:()=>cW,safeEncode:()=>dW,safeDecodeAsync:()=>tW,safeDecode:()=>pW,registry:()=>qN,regexes:()=>d$,regex:()=>L4,refine:()=>CQ,record:()=>L,readonly:()=>LQ,property:()=>sN,properties:()=>x4,promise:()=>vG,prettifyError:()=>EU,preprocess:()=>Pv,prefault:()=>PQ,positive:()=>tN,pipe:()=>Nb,partialRecord:()=>m8,parseAsync:()=>iW,parse:()=>uW,overwrite:()=>a$,output:()=>OG,optional:()=>C,object:()=>G,number:()=>S,nullish:()=>t8,nullable:()=>XD,null:()=>Jv,normalize:()=>y4,nonpositive:()=>aN,nonoptional:()=>wQ,nonnegative:()=>eN,never:()=>Ab,negative:()=>oN,nativeEnum:()=>p8,nanoid:()=>b8,nan:()=>a8,multipleOf:()=>yv,minSize:()=>bv,minLength:()=>Hv,mime:()=>f4,meta:()=>NG,memoizer:()=>o_,maxSize:()=>uv,maxLength:()=>T6,map:()=>r8,mac:()=>G8,lte:()=>u$,lt:()=>gv,lowercase:()=>E4,looseRecord:()=>h8,looseObject:()=>u,locales:()=>vD,literal:()=>P,length:()=>S6,lazy:()=>cv,ksuid:()=>Q8,keyof:()=>i8,jwt:()=>w8,json:()=>JG,iso:()=>p$,ipv6:()=>B8,ipv4:()=>Y8,invertCodec:()=>s8,intersection:()=>e$,int64:()=>R8,int32:()=>E8,int:()=>gb,instanceof:()=>bG,input:()=>KG,includes:()=>k4,iban:()=>P8,httpUrl:()=>g8,hostname:()=>M8,hex:()=>T8,hash:()=>A8,guid:()=>$8,gte:()=>i$,gt:()=>Nv,globalRegistry:()=>j$,getErrorMap:()=>Dz,getDiscriminatedOption:()=>M0,function:()=>IG,fromJSONSchema:()=>GG,formatError:()=>V_,float64:()=>L8,float32:()=>Z8,flattenError:()=>E_,file:()=>c8,exactOptional:()=>zQ,enum:()=>l,endsWith:()=>C4,encodeAsync:()=>hW,encode:()=>nW,emoji:()=>N8,email:()=>Jb,e164:()=>H8,discriminatedUnion:()=>pv,describe:()=>gG,deepPartial:()=>jG,decodeAsync:()=>rW,decode:()=>mW,date:()=>u8,custom:()=>DG,currencyCode:()=>S8,cuid2:()=>J8,cuid:()=>U8,creditCard:()=>F8,core:()=>Fv,config:()=>N$,compile:()=>X2,coerce:()=>FD,codec:()=>e8,clone:()=>a,cidrv6:()=>z8,cidrv4:()=>j8,check:()=>_G,catch:()=>TQ,boolean:()=>k,bigint:()=>k8,base64url:()=>O8,base64:()=>K8,array:()=>H,any:()=>Sb,_function:()=>IG,_default:()=>HQ,_ZodString:()=>bb,ZodXor:()=>bQ,ZodXID:()=>jb,ZodVoid:()=>gQ,ZodUnknown:()=>_Q,ZodUnion:()=>GD,ZodUndefined:()=>$Q,ZodUUID:()=>Uv,ZodURL:()=>WD,ZodULID:()=>Bb,ZodType:()=>h,ZodTuple:()=>XQ,ZodTransform:()=>jQ,ZodTemplateLiteral:()=>EQ,ZodSymbol:()=>sW,ZodSuccess:()=>qQ,ZodStringFormat:()=>$$,ZodString:()=>c4,ZodSet:()=>YQ,ZodRecord:()=>d4,ZodRealError:()=>R$,ZodReadonly:()=>ZQ,ZodPromise:()=>kQ,ZodPreprocess:()=>AQ,ZodPrefault:()=>FQ,ZodPipe:()=>jD,ZodOptional:()=>BD,ZodObject:()=>YD,ZodNumberFormat:()=>V6,ZodNumber:()=>o4,ZodNullable:()=>KQ,ZodNull:()=>vQ,ZodNonOptional:()=>Eb,ZodNever:()=>DQ,ZodNanoID:()=>Qb,ZodNaN:()=>SQ,ZodMap:()=>QQ,ZodMAC:()=>oW,ZodLiteral:()=>GQ,ZodLazy:()=>VQ,ZodKSUID:()=>zb,ZodJWT:()=>Mb,ZodIssueCode:()=>uQ,ZodIntersection:()=>JQ,ZodInstanceOf:()=>fQ,ZodISOTime:()=>rv,ZodISODuration:()=>dv,ZodISODateTime:()=>mv,ZodISODate:()=>hv,ZodIPv6:()=>Ob,ZodIPv4:()=>Kb,ZodIBAN:()=>eW,ZodGUID:()=>Xb,ZodFunction:()=>RQ,ZodFirstPartyTypeKind:()=>yQ,ZodFile:()=>BQ,ZodExactOptional:()=>Lb,ZodError:()=>$z,ZodEnum:()=>p4,ZodEmoji:()=>Wb,ZodEmail:()=>Ub,ZodE164:()=>qb,ZodDiscriminatedUnion:()=>UQ,ZodDefault:()=>OQ,ZodDate:()=>QD,ZodCustomStringFormat:()=>E6,ZodCustom:()=>KD,ZodCreditCard:()=>aW,ZodCompileUnsupportedError:()=>c,ZodCompileAsyncError:()=>Dv,ZodCodec:()=>zD,ZodCatch:()=>MQ,ZodCUID2:()=>Gb,ZodCUID:()=>Yb,ZodCIDRv6:()=>Fb,ZodCIDRv4:()=>Hb,ZodBoolean:()=>a4,ZodBigIntFormat:()=>Tb,ZodBigInt:()=>e4,ZodBase64URL:()=>wb,ZodBase64:()=>Pb,ZodArray:()=>NQ,ZodAny:()=>IQ,TimePrecision:()=>K2,NEVER:()=>L_,INVALID:()=>T$,$output:()=>D2,$input:()=>g2,$brand:()=>TU});var Fv={};zv(Fv,{withParser:()=>MN,version:()=>RJ,validateURL:()=>gN,validateAsync:()=>R_,validate:()=>k_,util:()=>w,urlProtocolOk:()=>bN,urlHostnameOk:()=>NN,treeifyError:()=>LU,toZod:()=>H_,toJSONSchema:()=>Z6,toDotPath:()=>d9,stripTabAndNewline:()=>i_,standardProps:()=>DN,safeParseAsync:()=>F5,safeParse:()=>H5,safeEncodeAsync:()=>E5,safeEncode:()=>Z5,safeDecodeAsync:()=>V5,safeDecode:()=>L5,registry:()=>qN,regexes:()=>d$,processSchema:()=>s,process:()=>s,prettifyError:()=>EU,parseURLObject:()=>YY,parseAsync:()=>ug,parse:()=>yg,meta:()=>c2,mergeValues:()=>T4,memoizer:()=>o_,locales:()=>vD,isValidJWT:()=>YN,isValidIPv6:()=>l_,isValidIBAN:()=>QN,isValidCreditCard:()=>WN,isValidCIDRv6:()=>UN,isValidBase64URL:()=>XN,isValidBase64:()=>n_,isRecursiveSchema:()=>PN,isBackEdge:()=>wN,initializeContext:()=>iv,handleUnrepresentable:()=>J$,globalRegistry:()=>j$,globalConfig:()=>Q$,getDiscriminatedOption:()=>M0,formatError:()=>V_,flattenError:()=>E_,finalize:()=>nv,extractDefs:()=>lv,encodeAsync:()=>S5,encode:()=>M5,describe:()=>p2,decodeAsync:()=>A5,decode:()=>T5,createToJSONSchemaMethod:()=>a2,createStandardJSONSchemaMethod:()=>m4,config:()=>N$,compileFn:()=>TN,compile:()=>X2,clone:()=>a,canParseURL:()=>iJ,base64urlCharset:()=>m_,base64Charset:()=>JN,_xor:()=>Tj,_xid:()=>uN,_void:()=>y2,_uuidv7:()=>kN,_uuidv6:()=>VN,_uuidv4:()=>EN,_uuid:()=>LN,_url:()=>ID,_uppercase:()=>V4,_unknown:()=>x2,_union:()=>Mj,_undefined:()=>k2,_ulid:()=>yN,_uint64:()=>E2,_uint32:()=>M2,_tuple:()=>Zj,_trim:()=>u4,_transform:()=>xj,_toUpperCase:()=>l4,_toLowerCase:()=>i4,_templateLiteral:()=>rj,_symbol:()=>V2,_superRefine:()=>d2,_success:()=>lj,_stringbool:()=>t2,_stringFormat:()=>A6,_string:()=>Y2,_startsWith:()=>R4,_slugify:()=>n4,_size:()=>M6,_set:()=>Vj,_safeParseAsync:()=>w4,_safeParse:()=>P4,_safeEncodeAsync:()=>dg,_safeEncode:()=>hg,_safeDecodeAsync:()=>pg,_safeDecode:()=>rg,_regex:()=>L4,_refine:()=>r2,_record:()=>Lj,_readonly:()=>hj,_property:()=>sN,_properties:()=>x4,_promise:()=>pj,_positive:()=>tN,_pipe:()=>mj,_parseAsync:()=>F4,_parse:()=>H4,_overwrite:()=>a$,_optional:()=>fj,_number:()=>O2,_nullable:()=>yj,_null:()=>R2,_normalize:()=>y4,_nonpositive:()=>aN,_nonoptional:()=>ij,_nonnegative:()=>eN,_never:()=>f2,_negative:()=>oN,_nativeEnum:()=>Rj,_nanoid:()=>CN,_nan:()=>l2,_multipleOf:()=>yv,_minSize:()=>bv,_minLength:()=>Hv,_min:()=>i$,_mime:()=>f4,_maxSize:()=>uv,_maxLength:()=>T6,_max:()=>u$,_map:()=>Ej,_mac:()=>B2,_lte:()=>u$,_lt:()=>gv,_lowercase:()=>E4,_literal:()=>Cj,_length:()=>S6,_lazy:()=>dj,_ksuid:()=>iN,_jwt:()=>cN,_isoTime:()=>gD,_isoDuration:()=>ND,_isoDateTime:()=>_D,_isoDate:()=>DD,_ipv6:()=>nN,_ipv4:()=>lN,_intersection:()=>Aj,_int64:()=>L2,_int32:()=>q2,_int:()=>F2,_includes:()=>k4,_iban:()=>z2,_guid:()=>ZN,_gte:()=>i$,_gt:()=>Nv,_float64:()=>w2,_float32:()=>P2,_file:()=>m2,_enum:()=>kj,_endsWith:()=>C4,_encodeAsync:()=>ng,_encode:()=>ig,_emoji:()=>RN,_email:()=>AN,_e164:()=>pN,_discriminatedUnion:()=>Sj,_default:()=>uj,_decodeAsync:()=>mg,_decode:()=>lg,_date:()=>u2,_custom:()=>h2,_cuid2:()=>fN,_cuid:()=>xN,_creditCard:()=>j2,_coercedString:()=>G2,_coercedNumber:()=>H2,_coercedDate:()=>i2,_coercedBoolean:()=>S2,_coercedBigint:()=>Z2,_cidrv6:()=>hN,_cidrv4:()=>mN,_check:()=>CY,_catch:()=>nj,_boolean:()=>T2,_bigint:()=>A2,_base64url:()=>dN,_base64:()=>rN,_array:()=>n2,_any:()=>C2,ZodCompileUnsupportedError:()=>c,ZodCompileAsyncError:()=>Dv,URL_UNPARSEABLE:()=>u_,URL_BAD_FORMAT:()=>uJ,TimePrecision:()=>K2,NEVER:()=>L_,JSONSchemaGenerator:()=>yW,JSONSchema:()=>aY,INVALID:()=>T$,Doc:()=>M4,$output:()=>D2,$input:()=>g2,$constructor:()=>z,$brand:()=>TU,$ZodXor:()=>q0,$ZodXID:()=>pJ,$ZodVoid:()=>O0,$ZodUnknown:()=>z0,$ZodUnion:()=>r_,$ZodUndefined:()=>G0,$ZodUUID:()=>fJ,$ZodURL:()=>lJ,$ZodULID:()=>dJ,$ZodType:()=>m,$ZodTuple:()=>jN,$ZodTransform:()=>R0,$ZodTemplateLiteral:()=>r0,$ZodSymbol:()=>Y0,$ZodSuccess:()=>i0,$ZodStringFormat:()=>e,$ZodString:()=>F6,$ZodSet:()=>L0,$ZodRegistry:()=>N2,$ZodRecord:()=>A0,$ZodRealError:()=>k$,$ZodReadonly:()=>h0,$ZodPromise:()=>p0,$ZodPreprocess:()=>m0,$ZodPrefault:()=>y0,$ZodPipe:()=>KN,$ZodOptional:()=>zN,$ZodObjectJIT:()=>w0,$ZodObject:()=>jY,$ZodNumberFormat:()=>W0,$ZodNumber:()=>GN,$ZodNullable:()=>x0,$ZodNull:()=>B0,$ZodNonOptional:()=>u0,$ZodNever:()=>K0,$ZodNanoID:()=>mJ,$ZodNaN:()=>n0,$ZodMap:()=>Z0,$ZodMAC:()=>v0,$ZodLiteral:()=>V0,$ZodLazy:()=>p_,$ZodKSUID:()=>cJ,$ZodJWT:()=>J0,$ZodIntersection:()=>S0,$ZodISOTime:()=>aJ,$ZodISODuration:()=>eJ,$ZodISODateTime:()=>tJ,$ZodISODate:()=>oJ,$ZodIPv6:()=>$0,$ZodIPv4:()=>sJ,$ZodIBAN:()=>U0,$ZodGUID:()=>xJ,$ZodFunction:()=>d0,$ZodFile:()=>k0,$ZodExactOptional:()=>C0,$ZodError:()=>ZU,$ZodEnum:()=>E0,$ZodEncodeError:()=>O6,$ZodEmoji:()=>nJ,$ZodEmail:()=>yJ,$ZodE164:()=>N0,$ZodDiscriminatedUnion:()=>T0,$ZodDefault:()=>f0,$ZodDate:()=>H0,$ZodCyclicError:()=>a0,$ZodCustomStringFormat:()=>X0,$ZodCustom:()=>c0,$ZodCreditCard:()=>b0,$ZodCodec:()=>d_,$ZodCheckUpperCase:()=>TJ,$ZodCheckStringFormat:()=>q4,$ZodCheckStartsWith:()=>AJ,$ZodCheckSizeEquals:()=>HJ,$ZodCheckRegex:()=>qJ,$ZodCheckProperty:()=>LJ,$ZodCheckProperties:()=>EJ,$ZodCheckOverwrite:()=>kJ,$ZodCheckNumberFormat:()=>jJ,$ZodCheckMultipleOf:()=>BJ,$ZodCheckMinSize:()=>OJ,$ZodCheckMinLength:()=>PJ,$ZodCheckMimeType:()=>VJ,$ZodCheckMaxSize:()=>KJ,$ZodCheckMaxLength:()=>FJ,$ZodCheckLowerCase:()=>MJ,$ZodCheckLessThan:()=>eg,$ZodCheckLengthEquals:()=>wJ,$ZodCheckIncludes:()=>SJ,$ZodCheckGreaterThan:()=>sg,$ZodCheckEndsWith:()=>ZJ,$ZodCheckBigIntFormat:()=>zJ,$ZodCheck:()=>v$,$ZodCatch:()=>l0,$ZodCUID2:()=>rJ,$ZodCUID:()=>hJ,$ZodCIDRv6:()=>_0,$ZodCIDRv4:()=>I0,$ZodBoolean:()=>h_,$ZodBigIntFormat:()=>Q0,$ZodBigInt:()=>BN,$ZodBase64URL:()=>g0,$ZodBase64:()=>D0,$ZodAsyncError:()=>y$,$ZodArray:()=>P0,$ZodAny:()=>j0});var w={};zv(w,{unwrapMessage:()=>Y4,uint8ArrayToHex:()=>U5,uint8ArrayToBase64url:()=>N5,uint8ArrayToBase64:()=>i9,toZod:()=>H_,stringifyPrimitive:()=>q,slugify:()=>KU,sizeCaps:()=>K4,shallowClone:()=>P_,safeExtend:()=>sB,required:()=>I5,rawShape:()=>z4,randomString:()=>dB,propertyKeyTypes:()=>w_,promiseAllObject:()=>rB,primitiveTypes:()=>HU,prefixIssues:()=>E$,pick:()=>oB,partial:()=>v5,parsedType:()=>M,own:()=>xv,optionalKeys:()=>FU,omit:()=>aB,objectClone:()=>lB,numKeys:()=>pB,nullish:()=>kg,normalizeParams:()=>A,mergeDefs:()=>o$,merge:()=>$5,members:()=>wU,jsonStringifyReplacer:()=>B4,joinValues:()=>O,issue:()=>O4,isPlainObject:()=>h$,isObject:()=>z6,installLazyProp:()=>Y5,hide:()=>Z_,hexToUint8Array:()=>b5,getSizableOrigin:()=>S_,getParsedType:()=>cB,getLengthableOrigin:()=>A_,getEnumValues:()=>G4,getElementAtPath:()=>hB,floatSafeRemainder:()=>F_,finalizeIssue:()=>V$,extend:()=>eB,explicitlyAborted:()=>PU,escapeRegex:()=>r$,esc:()=>q$,derived:()=>J5,defineLazyInternal:()=>d,defineLazy:()=>zU,createTransparentProxy:()=>tB,constantCatch:()=>qU,codePointLength:()=>K6,cloneDef:()=>mB,clone:()=>a,cleanRegex:()=>Ov,cleanEnum:()=>D5,captureStackTrace:()=>Rg,cached:()=>j4,base64urlToUint8Array:()=>g5,base64ToUint8Array:()=>u9,attachSchema:()=>T_,assignProp:()=>B$,assertNotEqual:()=>fB,assertNever:()=>uB,assertIs:()=>yB,assertEqual:()=>xB,assert:()=>iB,allowsEval:()=>OU,aborted:()=>M$,NUMBER_FORMAT_RANGES:()=>q_,Class:()=>l9,CONSTANT_CATCH:()=>xg,BIGINT_FORMAT_RANGES:()=>M_});function xB($){return $}function fB($){return $}function H_(){return($)=>$}function yB($){}function uB($){throw Error("Unexpected value in exhaustive check")}function iB($){}function G4($){let v=Object.values($).filter((g)=>typeof g==="number");return Object.entries($).filter(([g,I])=>v.indexOf(+g)===-1).map(([g,I])=>I)}function O($,v="|"){return $.map((D)=>q(D)).join(v)}function B4($,v){if(typeof v==="bigint")return v.toString();return v}class C9{constructor($){this._getter=$,this._value=void 0}get value(){let $=this._getter;if($!==void 0)this._value=$(),this._getter=void 0;return this._value}}function j4($){return new C9($)}function kg($){return $===null||$===void 0}function Ov($){let v=$.startsWith("^")?1:0,D=$.endsWith("$")?$.length-1:$.length;return $.slice(v,D)}function F_($,v){let D=$/v,g=Math.round(D),I=4*Number.EPSILON*Math.max(Math.abs(D),1);if(Math.abs(D-g){let b=v._zod.def.shape[_];return g?g(b,_):b});else f9($,_,g?g(N.value,_):N.value)}}function nB($,v){for(let D of Reflect.ownKeys(v)){let g=Object.getOwnPropertyDescriptor(v,D);if(!g.enumerable)continue;if(g.get)x9($,D,()=>v[D]);else f9($,D,g.value)}}function o$(...$){let v={};for(let D of $){let g=Object.getOwnPropertyDescriptors(D);Object.assign(v,g)}return Object.defineProperties({},v)}function mB($){return o$($._zod.def)}function hB($,v){if(!v)return $;return v.reduce((D,g)=>D?.[g],$)}function rB($){let v=Object.keys($),D=v.map((g)=>$[g]);return Promise.all(D).then((g)=>{let I={};for(let _=0;_{};function z6($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var OU=j4(()=>{if(Q$.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch($){return!1}});function h$($){if(z6($)===!1)return!1;let v=$.constructor;if(v===void 0)return!0;if(typeof v!=="function")return!0;let D=v.prototype;if(z6(D)===!1)return!1;if(Object.prototype.hasOwnProperty.call(D,"isPrototypeOf")===!1)return!1;return!0}function P_($){if(h$($))return{...$};if(Array.isArray($))return[...$];if($ instanceof Map)return new Map($);if($ instanceof Set)return new Set($);return $}function pB($){let v=0;for(let D in $)if(Object.prototype.hasOwnProperty.call($,D))v++;return v}var cB=($)=>{let v=typeof $;switch(v){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN($)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray($))return"array";if($===null)return"null";if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return"promise";if(typeof Map<"u"&&$ instanceof Map)return"map";if(typeof Set<"u"&&$ instanceof Set)return"set";if(typeof Date<"u"&&$ instanceof Date)return"date";if(typeof File<"u"&&$ instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${v}`)}},w_=new Set(["string","number","symbol"]),HU=new Set(["string","number","bigint","boolean","symbol","undefined"]);function r$($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function a($,v,D){let g=new $._zod.constr(v??$._zod.def);if(!v||D?.parent)g._zod.parent=$;return g}function A($){let v=$;if(!v)return{};if(typeof v==="string")return{error:()=>v};if(v?.message!==void 0){if(v?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");v.error=v.message}if(delete v.message,typeof v.error==="string")return{...v,error:()=>v.error};return v}function tB($){let v;return new Proxy({},{get(D,g,I){return v??(v=$()),Reflect.get(v,g,I)},set(D,g,I,_){return v??(v=$()),Reflect.set(v,g,I,_)},has(D,g){return v??(v=$()),Reflect.has(v,g)},deleteProperty(D,g){return v??(v=$()),Reflect.deleteProperty(v,g)},ownKeys(D){return v??(v=$()),Reflect.ownKeys(v)},getOwnPropertyDescriptor(D,g){return v??(v=$()),Reflect.getOwnPropertyDescriptor(v,g)},defineProperty(D,g,I){return v??(v=$()),Reflect.defineProperty(v,g,I)}})}function q($){if(typeof $==="bigint")return $.toString()+"n";if(typeof $==="string")return`"${$}"`;return`${$}`}function FU($){return Object.keys($).filter((v)=>{return $[v]._zod.optin!==void 0&&$[v]._zod.optout==="optional"})}var q_=(()=>({safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]}))(),M_={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function oB($,v){let D=$._zod.def,g=D.checks;if(g&&g.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let _={};return j6(_,$,Cg($,v)),a($,o$(D,{shape:_,checks:[]}))}function Cg($,v){let D=Kv($),g=[];for(let I of Reflect.ownKeys(v)){if(!Object.getOwnPropertyDescriptor(D,I)?.enumerable)throw Error(`Unrecognized key: "${String(I)}"`);if(v[I])g.push(I)}return g}function aB($,v){let D=$._zod.def,g=D.checks;if(g&&g.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let _=new Set(Cg($,v)),N={};return j6(N,$,Reflect.ownKeys(Kv($)).filter((b)=>!_.has(b))),a($,o$(D,{shape:N,checks:[]}))}function eB($,v){if(!h$(v))throw Error("Invalid input to extend: expected a plain object");let D=$._zod.def.checks;if(D&&D.length>0){let I=Kv($);for(let _ of Reflect.ownKeys(v))if(Object.getOwnPropertyDescriptor(I,_)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return a($,o$($._zod.def,{shape:y9($,v)}))}function y9($,v){let D={};return j6(D,$,Reflect.ownKeys(Kv($))),nB(D,v),D}function sB($,v){if(!h$(v))throw Error("Invalid input to safeExtend: expected a plain object");return a($,o$($._zod.def,{shape:y9($,v)}))}function $5($,v){if(!v?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if($._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let D={};j6(D,$,Reflect.ownKeys(Kv($))),j6(D,v,Reflect.ownKeys(Kv(v)));let g=o$($._zod.def,{shape:D,get catchall(){return v._zod.def.catchall},checks:v._zod.def.checks??[]});return a($,g)}function v5($,v,D,g="partial"){let _=v._zod.def.checks;if(_&&_.length>0)throw Error(`.${g}() cannot be used on object schemas containing refinements`);let b=D?new Set(Cg(v,D)):void 0,U={};return j6(U,v,Reflect.ownKeys(Kv(v)),$&&((J,W)=>b&&!b.has(W)?J:new $({type:"optional",innerType:J}))),a(v,o$(v._zod.def,{shape:U,checks:[]}))}function I5($,v,D){let g=D?new Set(Cg(v,D)):void 0,I={};return j6(I,v,Reflect.ownKeys(Kv(v)),(_,N)=>g&&!g.has(N)?_:new $({type:"nonoptional",innerType:_})),a(v,o$(v._zod.def,{shape:I}))}function M$($,v=0){if($.aborted===!0)return!0;for(let D=v;D<$.issues.length;D++)if($.issues[D]?.continue!==!0)return!0;return!1}function PU($,v=0){if($.aborted===!0)return!0;for(let D=v;D<$.issues.length;D++)if($.issues[D]?.continue===!1)return!0;return!1}function E$($,v){return v.map((D)=>{var g;return(g=D).path??(g.path=[]),D.path.unshift($),D})}function Y4($){return typeof $==="string"?$:$?.message}function K4($){let v=[];for(let D of $??[]){let g=D._zod.def;if(!/_(length|size)$|_equals$/.test(g.check))break;let I=g.maximum??g.length??g.size;if(I>=0)v.push([I,D])}return v}function T_($,v,D){var g;for(let I=v;I<$.length;I++)(g=$[I]).schema??(g.schema=D)}function V$($,v,D){var g;let I=$.inst?._zod?.traits;if(I?.has("$ZodType"))if(I.has("$ZodCheck"))(g=$).schema??(g.schema=$.inst);else $.schema=$.inst;let _=$.schema!==$.inst?$.schema?._zod.def?.error:void 0,N=$.message?$.message:Y4($.inst?._zod.def?.error?.($))??Y4(_?.($))??Y4(v?.error?.($))??Y4(D.customError?.($))??Y4(D.localeError?.($))??"Invalid input",b={};for(let U of Object.keys($)){if(U==="inst"||U==="schema"||U==="continue"||U==="input"||U==="__proto__")continue;b[U]=$[U]}if(b.path??(b.path=[]),b.message=N,v?.reportInput)b.input=$.input;return b}function S_($){if($ instanceof Set)return"set";if($ instanceof Map)return"map";if($ instanceof File)return"file";return"unknown"}var _5=/[\uD800-\uDBFF]/;function K6($){let v=$.length;if(!_5.test($))return v;let D=v;for(let g=0;g{return Number.isNaN(Number.parseInt(v,10))}).map((v)=>v[1])}function u9($){let v=atob($),D=new Uint8Array(v.length);for(let g=0;gv.toString(16).padStart(2,"0")).join("")}class l9{constructor(...$){}}function wU($,v){for(let D in v){let g=Object.getOwnPropertyDescriptor(v,D);if(g.get)Object.defineProperty($,D,{...g,enumerable:!1});else X5($,D,g.value)}}function xv($,v,D,g=!0){return Object.defineProperty($,v,{configurable:!0,writable:!0,enumerable:g,value:D}),D}function Z_($,v,D){return xv($,v,D,!1)}function J5($,v){for(let D in $){let g=$[D];Object.defineProperty(v,D,{configurable:!0,enumerable:!0,get(){return xv(this,D,g(this))},set(I){xv(this,D,I)}})}return v}function X5($,v,D){Object.defineProperty($,v,{configurable:!0,get(){return this==null?D:xv(this,v,D.bind(this))},set(g){xv(this,v,g)}})}function W5($,v){let D=Object.getPrototypeOf($);return v in D?void 0:D}var jU,Cv=!1,Q5={configurable:!0,get(){Cv=!0;return}};function d($,v,D){let g=Object.getPrototypeOf($._zod);if(v in g&&jU!==$._zod){jU=void 0;return}jU=$._zod,Object.defineProperty(g,v,{configurable:!0,get(){Object.defineProperty(this,v,Q5);let I=Cv;Cv=!1;try{let _=D(this);if(Cv)delete this[v];else Object.defineProperty(this,v,{configurable:!0,writable:!0,value:_});return Cv=Cv||I,_}catch(_){throw delete this[v],Cv=Cv||I,_}},set(I){Object.defineProperty(this,v,{configurable:!0,writable:!0,value:I})}})}function Y5($,v,D,g){let I=W5($,v);if(!I)return;Object.defineProperty(I,v,{configurable:!0,get(){let _={configurable:!0,writable:!0,enumerable:g,value:void 0};return Object.defineProperty(this,v,_),_.value=D(this),Object.defineProperty(this,v,_),_.value},set(_){Object.defineProperty(this,v,{configurable:!0,writable:!0,enumerable:g,value:_})}})}var xg="~constantCatch";function qU($){let v=()=>$;return v[xg]=!0,v}var n9,L_=Object.freeze({status:"aborted"}),MU={value:void 0,enumerable:!1},m9="captureStackTrace"in Error?Error:null;function G5($){let v=m9;if(v){let D=v.stackTraceLimit;if(typeof D==="number"){try{v.stackTraceLimit=0}catch{return m9=null,new $}try{return new $}finally{v.stackTraceLimit=D}}}return new $}function z($,v,D,g){let I={};function _(B){this.def=B,this.constr=Y,this.traits=new Set}_.prototype=I;let N=D,b=N&&new WeakSet;function U(B,j){if(!B._zod){MU.value=new _(j);try{Object.defineProperty(B,"_zod",MU)}finally{MU.value=void 0}}else if(B._zod.traits.has($))return;if(B._zod.traits.add($),v(B,j),b){let F=Object.getPrototypeOf(B),T=B._zod.constr.prototype,V=F;while(V&&V!==T)V=Object.getPrototypeOf(V);let Z=V??F;if(!b.has(Z))b.add(Z),wU(Z,N)}let K=Y.prototype;for(let F in K){if(!Object.prototype.hasOwnProperty.call(K,F))continue;if(!(F in B))B[F]=K[F].bind(B)}}let J=g?.Parent??Object;class W extends J{}Object.defineProperty(W,"name",{value:$});function Y(B){let j=g?.Parent?G5(W):this;U(j,B);let K=j._zod.deferred;if(K){for(let T of K)T();j._zod.deferred=void 0}let F=globalThis.__zod_globalConfig?.postProcessor;if(F)F(j);return j}return Object.defineProperty(Y,"init",{value:U}),Object.defineProperty(Y,Symbol.hasInstance,{value:(B)=>{if(g?.Parent&&B instanceof g.Parent)return!0;return B?._zod?.traits?.has($)}}),Object.defineProperty(Y,"name",{value:$}),Y}var TU=Symbol("zod_brand");class y$ extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class O6 extends Error{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}}(n9=globalThis).__zod_globalConfig??(n9.__zod_globalConfig={});var Q$=globalThis.__zod_globalConfig;function N$($){if($)Object.assign(Q$,$);return Q$}function B5(){let $=this._zod;return $.message??($.message=JSON.stringify($.def,B4,2)),$.message}function j5($){this._zod.message=$}var z5={get:B5,set:j5,enumerable:!0,configurable:!0},AU={value:void 0,enumerable:!1},h9=new WeakSet([Object.prototype,Error.prototype]),r9=($,v)=>{$.name="$ZodError",AU.value=v,Object.defineProperty($,"issues",AU),AU.value=void 0,Object.defineProperty($,"message",z5);let D=Object.getPrototypeOf($);if(!h9.has(D))h9.add(D),Object.defineProperty(D,"toString",{configurable:!0,enumerable:!1,get(){let g=()=>this.message;return Object.defineProperty(this,"toString",{value:g,configurable:!0,writable:!0}),g},set(g){Object.defineProperty(this,"toString",{value:g,configurable:!0,writable:!0})}})},ZU=z("$ZodError",r9),k$=z("$ZodError",r9,void 0,{Parent:Error});function K5($,v,D){if(!Object.prototype.hasOwnProperty.call($,v))if(v==="__proto__")Object.defineProperty($,v,{value:D(),writable:!0,enumerable:!0,configurable:!0});else $[v]=D();return $[v]}function E_($,v=(D)=>D.message){let D={},g=[];for(let I of $.issues)if(I.path.length>0)K5(D,I.path[0],()=>[]).push(v(I));else g.push(v(I));return{formErrors:g,fieldErrors:D}}function V_($,v=(D)=>D.message){let D={_errors:[]},g=(I,_=[])=>{for(let N of I.issues)if(N.code==="invalid_union"&&N.errors.length)N.errors.map((b)=>g({issues:b},[..._,...N.path]));else if(N.code==="invalid_key")g({issues:N.issues},[..._,...N.path]);else if(N.code==="invalid_element")g({issues:N.issues},[..._,...N.path]);else{let b=[..._,...N.path];if(b.length===0)D._errors.push(v(N));else{let U=D,J=0;while(JD.message){let D={errors:[]},g=(I,_=[])=>{var N;for(let b of I.issues)if(b.code==="invalid_union"&&b.errors.length)b.errors.map((U)=>g({issues:U},[..._,...b.path]));else if(b.code==="invalid_key")g({issues:b.issues},[..._,...b.path]);else if(b.code==="invalid_element")g({issues:b.issues},[..._,...b.path]);else{let U=[..._,...b.path];if(U.length===0){D.errors.push(v(b));continue}let J=D,W=0;while(Wtypeof g==="object"?g.key:g);for(let g of D)if(typeof g==="number")v.push(`[${g}]`);else if(typeof g==="symbol")v.push(`[${JSON.stringify(String(g))}]`);else if(/[^\w$]/.test(g))v.push(`[${JSON.stringify(g)}]`);else{if(v.length)v.push(".");v.push(g)}return v.join("")}function EU($){let v=[],D=[...$.issues].sort((g,I)=>(g.path??[]).length-(I.path??[]).length);for(let g of D)if(v.push(`✖ ${g.message}`),g.path?.length)v.push(` → at ${d9(g.path)}`);return v.join(` +`)}function fg($,v){return{callee:v?.callee??$,Err:v?.Err}}var H4=($)=>{let v=(D,g,I,_)=>{let N=I?{...I,async:!1}:{async:!1},b=D._zod.run({value:g,issues:[]},N);if(b instanceof Promise)throw new y$;if(b.issues.length){let U=new(_?.Err??$)(b.issues.map((J)=>V$(J,N,N$())));throw Rg(U,_?.callee??v),U}return b.value};return v},yg=H4(k$),F4=($)=>{let v=async(D,g,I,_)=>{let N=I?{...I,async:!0}:{async:!0},b=D._zod.run({value:g,issues:[]},N);if(b instanceof Promise)b=await b;if(b.issues.length){let U=new(_?.Err??$)(b.issues.map((J)=>V$(J,N,N$())));throw Rg(U,_?.callee??v),U}return b.value};return v},ug=F4(k$),P4=($)=>(v,D,g)=>{let I=g?{...g,async:!1}:{async:!1},_=v._zod.run({value:D,issues:[]},I);if(_ instanceof Promise)throw new y$;return _.issues.length?p9($,_.issues,I):{success:!0,data:_.value}},H5=P4(k$);function p9($,v,D){let g;return{success:!1,get error(){if(!g)g=new $(v.map((I)=>V$(I,D,N$()))),v=void 0,D=void 0;return g},set error(I){g=I,v=void 0,D=void 0}}}var w4=($)=>async(v,D,g)=>{let I=g?{...g,async:!0}:{async:!0},_=v._zod.run({value:D,issues:[]},I);if(_ instanceof Promise)_=await _;return _.issues.length?p9($,_.issues,I):{success:!0,data:_.value}},F5=w4(k$),P5=Symbol.for("zod.compile.invalid"),w5=Symbol.for("zod.compile.fallback"),k_=($,v,D)=>{let g=$._zod.bag.validator;if(g!==void 0){if(g(v)!==P5)return!0;if(g.definite===!0&&D===void 0)return!1}return q5($,v,D)};function q5($,v,D){let g=D?{...D,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},I=$._zod.bag.fallbackRun,_;if(I)g[w5]=!0,_=I({value:v,issues:[]},g);else _=$._zod.run({value:v,issues:[]},g);if(_ instanceof Promise)throw new y$;return _.issues.length===0}var R_=async($,v,D)=>{let g=D?{...D,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},I=$._zod.run({value:v,issues:[]},g);if(I instanceof Promise)I=await I;return I.issues.length===0},ig=($)=>{let v=H4($),D=(g,I,_,N)=>{let b=_?{..._,direction:"backward"}:{direction:"backward"};return v(g,I,b,fg(D,N))};return D},M5=ig(k$),lg=($)=>{let v=H4($),D=(g,I,_,N)=>{return v(g,I,_,fg(D,N))};return D},T5=lg(k$),ng=($)=>{let v=F4($),D=async(g,I,_,N)=>{let b=_?{..._,direction:"backward"}:{direction:"backward"};return await v(g,I,b,fg(D,N))};return D},S5=ng(k$),mg=($)=>{let v=F4($),D=async(g,I,_,N)=>{return await v(g,I,_,fg(D,N))};return D},A5=mg(k$),hg=($)=>(v,D,g)=>{let I=g?{...g,direction:"backward"}:{direction:"backward"};return P4($)(v,D,I)},Z5=hg(k$),rg=($)=>(v,D,g)=>{return P4($)(v,D,g)},L5=rg(k$),dg=($)=>async(v,D,g)=>{let I=g?{...g,direction:"backward"}:{direction:"backward"};return w4($)(v,D,I)},E5=dg(k$),pg=($)=>async(v,D,g)=>{return w4($)(v,D,g)},V5=pg(k$);var d$={};zv(d$,{xid:()=>xU,uuid7:()=>x5,uuid6:()=>C5,uuid4:()=>R5,uuid:()=>H6,uppercase:()=>WJ,unicodeEmail:()=>c9,undefined:()=>JJ,ulid:()=>CU,time:()=>IJ,string:()=>gJ,sha512_hex:()=>v3,sha512_base64url:()=>_3,sha512_base64:()=>I3,sha384_hex:()=>e5,sha384_base64url:()=>$3,sha384_base64:()=>s5,sha256_hex:()=>t5,sha256_base64url:()=>a5,sha256_base64:()=>o5,sha1_hex:()=>d5,sha1_base64url:()=>c5,sha1_base64:()=>p5,rfc5322Email:()=>y5,number:()=>_v,null:()=>UJ,nanoidOfLength:()=>uU,nanoid:()=>yU,md5_hex:()=>m5,md5_base64url:()=>r5,md5_base64:()=>h5,mac:()=>dU,lowercase:()=>XJ,ksuid:()=>fU,ipv6:()=>rU,ipv4:()=>hU,integer:()=>x_,idnEmail:()=>u5,iban:()=>tg,httpProtocol:()=>C_,html5Email:()=>f5,hostname:()=>aU,hex:()=>QJ,guid:()=>lU,extendedDuration:()=>k5,emoji:()=>mU,email:()=>nU,e164:()=>sU,duration:()=>iU,domain:()=>eU,datetime:()=>_J,date:()=>vJ,currencyCode:()=>$J,cuid2:()=>RU,cuid:()=>kU,creditCard:()=>cg,cidrv6:()=>cU,cidrv4:()=>pU,browserEmail:()=>i5,boolean:()=>bJ,bigint:()=>NJ,base64url:()=>oU,base64:()=>tU,anyString:()=>DJ});var kU=/^[cC][0-9a-z]{6,}$/,RU=/^[0-9a-z]+$/,CU=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,xU=/^[0-9a-vA-V]{20}$/,fU=/^[A-Za-z0-9]{27}$/,yU=/^[a-zA-Z0-9_-]{21}$/;function uU($){return new RegExp(`^[a-zA-Z0-9_-]{${$}}$`)}var iU=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,k5=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,lU=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,H6=($)=>{if(!$)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},R5=H6(4),C5=H6(6),x5=H6(7),nU=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,f5=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,y5=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,c9=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,u5=c9,i5=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,l5="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function mU(){return new RegExp(l5,"u")}var hU=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,rU=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,dU=($)=>{let v=r$($??":");return new RegExp(`^(?:[0-9A-F]{2}${v}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${v}){5}[0-9a-f]{2}$`)},pU=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,cU=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,tU=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,oU=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,aU=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,eU=/^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/,C_=/^https?$/,sU=/^\+[1-9]\d{6,14}$/,cg=/^\d(?:[ -]?\d){11,18}$/,$J=/^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/,tg=/^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/,t9="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))";function n5($){return new RegExp(`^${$}$`)}var vJ=n5(t9);function VU($){return typeof $.precision==="number"?$.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":$.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${$.precision}}`:$.seconds?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?":"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function IJ($){return new RegExp(`^${VU($)}$`)}function _J($){let v=["Z"];if($.offset)v.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let D=`${VU({precision:$.precision,seconds:!0})}(?:${v.join("|")})`,g=$.local?`${D}|${VU({precision:$.precision})}`:D;return new RegExp(`^${t9}T(?:${g})$`)}var DJ=/^[\s\S]{0,}$/,gJ=($)=>{let v=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${v}$`)},NJ=/^-?\d+n?$/,x_=/^-?\d+$/,_v=/^-?\d+(?:\.\d+)?$/,bJ=/^(?:true|false)$/i,UJ=/^null$/i;var JJ=/^undefined$/i;var XJ=/^[^A-Z]*$/,WJ=/^[^a-z]*$/,QJ=/^[0-9a-fA-F]*$/;function f_($,v){return new RegExp(`^[A-Za-z0-9+/]{${$}}${v}$`)}function y_($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var m5=/^[0-9a-fA-F]{32}$/,h5=f_(22,"=="),r5=y_(22),d5=/^[0-9a-fA-F]{40}$/,p5=f_(27,"="),c5=y_(27),t5=/^[0-9a-fA-F]{64}$/,o5=f_(43,"="),a5=y_(43),e5=/^[0-9a-fA-F]{96}$/,s5=f_(64,""),$3=y_(64),v3=/^[0-9a-fA-F]{128}$/,I3=f_(86,"=="),_3=y_(86);var v$=z("$ZodCheck",($,v)=>{var D;$._zod??($._zod={}),$._zod.def=v,(D=$._zod).onattach??(D.onattach=[])}),YJ=($)=>{let v=$.value;return!kg(v)&&v.size!==void 0},GJ=($)=>{let v=$.value;return!kg(v)&&v.length!==void 0},og={number:"number",bigint:"bigint",object:"date"},eg=z("$ZodCheckLessThan",($,v)=>{v$.init($,v);let D=og[typeof v.value];$._zod.check=(g)=>{if(v.inclusive?g.value<=v.value:g.value{v$.init($,v);let D=og[typeof v.value];$._zod.check=(g)=>{if(v.inclusive?g.value>=v.value:g.value>v.value)return;g.issues.push({origin:og[typeof g.value]??D,code:"too_small",minimum:typeof v.value==="object"?v.value.getTime():v.value,input:g.value,inclusive:v.inclusive,inst:$,continue:!v.abort})}}),BJ=z("$ZodCheckMultipleOf",($,v)=>{v$.init($,v),$._zod.check=(D)=>{if(typeof D.value!==typeof v.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof D.value==="bigint"?v.value!==BigInt(0)&&D.value%v.value===BigInt(0):F_(D.value,v.value)===0)return;D.issues.push({origin:typeof D.value,code:"not_multiple_of",divisor:v.value,input:D.value,inst:$,continue:!v.abort})}}),jJ=z("$ZodCheckNumberFormat",($,v)=>{v$.init($,v),v.format=v.format||"float64";let D=v.format?.includes("int"),g=D?"int":"number",[I,_]=q_[v.format];$._zod.check=(N)=>{let b=N.value;if(D){if(!Number.isInteger(b)){N.issues.push({expected:g,format:v.format,code:"invalid_type",continue:!1,input:b,inst:$});return}if(!Number.isSafeInteger(b)){if(b>0)N.issues.push({input:b,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:g,inclusive:!0,continue:!v.abort});else N.issues.push({input:b,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:g,inclusive:!0,continue:!v.abort});return}}if(b_)N.issues.push({origin:"number",input:b,code:"too_big",maximum:_,inclusive:!0,inst:$,continue:!v.abort})}}),zJ=z("$ZodCheckBigIntFormat",($,v)=>{v$.init($,v);let[D,g]=M_[v.format];$._zod.check=(I)=>{let _=I.value;if(_g)I.issues.push({origin:"bigint",input:_,code:"too_big",maximum:g,inclusive:!0,inst:$,continue:!v.abort})}}),KJ=z("$ZodCheckMaxSize",($,v)=>{var D;v$.init($,v),(D=$._zod.def).when??(D.when=YJ),$._zod.check=(g)=>{let I=g.value;if(I.size<=v.maximum)return;g.issues.push({origin:S_(I),code:"too_big",maximum:v.maximum,inclusive:!0,input:I,inst:$,continue:!v.abort})}}),OJ=z("$ZodCheckMinSize",($,v)=>{var D;v$.init($,v),(D=$._zod.def).when??(D.when=YJ),$._zod.check=(g)=>{let I=g.value;if(I.size>=v.minimum)return;g.issues.push({origin:S_(I),code:"too_small",minimum:v.minimum,inclusive:!0,input:I,inst:$,continue:!v.abort})}}),HJ=z("$ZodCheckSizeEquals",($,v)=>{var D;v$.init($,v),(D=$._zod.def).when??(D.when=YJ),$._zod.check=(g)=>{let I=g.value,_=I.size;if(_===v.size)return;let N=_>v.size;g.issues.push({origin:S_(I),...N?{code:"too_big",maximum:v.size}:{code:"too_small",minimum:v.size},inclusive:!0,exact:!0,input:g.value,inst:$,continue:!v.abort})}}),FJ=z("$ZodCheckMaxLength",($,v)=>{var D;v$.init($,v),(D=$._zod.def).when??(D.when=GJ),$._zod.check=(g)=>{let I=g.value,_=I.length;if((typeof I==="string"&&_>v.maximum?K6(I):_)<=v.maximum)return;let b=A_(I);g.issues.push({origin:b,code:"too_big",maximum:v.maximum,inclusive:!0,input:I,inst:$,continue:!v.abort})}}),PJ=z("$ZodCheckMinLength",($,v)=>{var D;v$.init($,v),(D=$._zod.def).when??(D.when=GJ),$._zod.check=(g)=>{let I=g.value,_=I.length;if((typeof I==="string"&&_>=v.minimum&&_=v.minimum)return;let b=A_(I);g.issues.push({origin:b,code:"too_small",minimum:v.minimum,inclusive:!0,input:I,inst:$,continue:!v.abort})}}),wJ=z("$ZodCheckLengthEquals",($,v)=>{var D;v$.init($,v),(D=$._zod.def).when??(D.when=GJ),$._zod.check=(g)=>{let I=g.value,_=I.length,N=typeof I==="string"&&_>=v.length&&_<=v.length*2?K6(I):_;if(N===v.length)return;let b=A_(I),U=N>v.length;g.issues.push({origin:b,...U?{code:"too_big",maximum:v.length}:{code:"too_small",minimum:v.length},inclusive:!0,exact:!0,input:g.value,inst:$,continue:!v.abort})}}),q4=z("$ZodCheckStringFormat",($,v)=>{var D,g;if(v$.init($,v),v.pattern)(D=$._zod).check??(D.check=(I)=>{if(v.pattern.lastIndex=0,v.pattern.test(I.value))return;I.issues.push({origin:"string",code:"invalid_format",format:v.format,input:I.value,...v.pattern?{pattern:v.pattern.toString()}:{},inst:$,continue:!v.abort})});else(g=$._zod).check??(g.check=()=>{})}),qJ=z("$ZodCheckRegex",($,v)=>{q4.init($,v),$._zod.check=(D)=>{if(v.pattern.lastIndex=0,v.pattern.test(D.value))return;D.issues.push({origin:"string",code:"invalid_format",format:"regex",input:D.value,pattern:v.pattern.toString(),inst:$,continue:!v.abort})}}),MJ=z("$ZodCheckLowerCase",($,v)=>{v.pattern??(v.pattern=XJ),q4.init($,v)}),TJ=z("$ZodCheckUpperCase",($,v)=>{v.pattern??(v.pattern=WJ),q4.init($,v)}),SJ=z("$ZodCheckIncludes",($,v)=>{v$.init($,v);let D=r$(v.includes),g=new RegExp(typeof v.position==="number"?`^.{${v.position},}${D}`:D);v.pattern=g,$._zod.check=(I)=>{if(I.value.includes(v.includes,v.position))return;I.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:v.includes,input:I.value,inst:$,continue:!v.abort})}}),AJ=z("$ZodCheckStartsWith",($,v)=>{v$.init($,v);let D=new RegExp(`^${r$(v.prefix)}.*`);v.pattern??(v.pattern=D),$._zod.check=(g)=>{if(g.value.startsWith(v.prefix))return;g.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:v.prefix,input:g.value,inst:$,continue:!v.abort})}}),ZJ=z("$ZodCheckEndsWith",($,v)=>{v$.init($,v);let D=new RegExp(`.*${r$(v.suffix)}$`);v.pattern??(v.pattern=D),$._zod.check=(g)=>{if(g.value.endsWith(v.suffix))return;g.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:v.suffix,input:g.value,inst:$,continue:!v.abort})}});function ag($,v,D){if($.issues.length)v.issues.push(...E$(D,$.issues))}var LJ=z("$ZodCheckProperty",($,v)=>{v$.init($,v),$._zod.check=(D)=>{let g=v.schema._zod.run({value:D.value[v.property],issues:[]},{});if(g instanceof Promise)return g.then((I)=>ag(I,D,v.property));ag(g,D,v.property);return}}),EJ=z("$ZodCheckProperties",($,v)=>{v$.init($,v),Z_($,Symbol.iterator,function*(){yield $});let D;$._zod.check=(g)=>{if(g.value==null){g.issues.push({expected:"object",code:"invalid_type",input:g.value,inst:$});return}D??(D=Reflect.ownKeys(v.shape).map((N)=>[N,v.shape[N]]));let I=g.value,_;for(let[N,b]of D){let U=b._zod.run({value:I[N],issues:[]},{});if(U instanceof Promise)_??(_=[]),_.push(U.then((J)=>ag(J,g,N)));else ag(U,g,N)}if(_)return Promise.all(_).then(()=>{return});return}}),VJ=z("$ZodCheckMimeType",($,v)=>{v$.init($,v);let D=new Set(v.mime);$._zod.check=(g)=>{if(D.has(g.value.type))return;g.issues.push({code:"invalid_value",values:v.mime,input:g.value.type,inst:$,continue:!v.abort})}}),kJ=z("$ZodCheckOverwrite",($,v)=>{v$.init($,v),$._zod.check=(D)=>{D.value=v.tx(D.value)}});class M4{constructor($=[],v={}){this.content=[],this.indent=0,this.args=$,this.closed=v}indented($){this.indent+=1;try{$(this)}finally{this.indent-=1}}write($){if(typeof $==="function"){$(this,{execution:"sync"}),$(this,{execution:"async"});return}let D=$.split(` +`).filter((_)=>_),g=Math.min(...D.map((_)=>_.length-_.trimStart().length)),I=D.map((_)=>_.slice(g)).map((_)=>" ".repeat(this.indent*2)+_);for(let _ of I)this.content.push(_)}compile(){let $=Function,v=this?.content??[""];return new $(...Object.keys(this.closed),`return function (${this.args.join(", ")}) { +${v.join(` +`)} +};`)(...Object.values(this.closed))}}var RJ={major:4,minor:6,patch:6};var m=z("$ZodType",($,v)=>{var D;$??($={}),$._zod.def=v,$._zod.bag=$._zod.bag||{},$._zod.version=RJ;let g=$._zod.def.checks,I=$._zod.traits.has("$ZodCheck")?[$,...g??[]]:g?.length?[...g]:[];for(let _ of I)for(let N of _._zod.onattach)N($);if(I.length===0)(D=$._zod).deferred??(D.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let _=(b,U,J)=>{if(b.memo)return b;let W=M$(b),Y;for(let B of U){if(B._zod.def.when){if(PU(b))continue;if(!B._zod.def.when(b))continue}else if(W)continue;let j=b.issues.length,K=B._zod.check(b);if(K instanceof Promise&&J?.async===!1)throw new y$;if(Y||K instanceof Promise)Y=(Y??Promise.resolve()).then(async()=>{if(await K,b.issues.length===j)return;if(T_(b.issues,j,$),!W)W=M$(b,j)});else{if(b.issues.length===j)continue;if(T_(b.issues,j,$),!W)W=M$(b,j)}}if(Y)return Y.then(()=>{return b});return b},N=(b,U,J)=>{if(M$(b))return b.aborted=!0,b;let W=_(U,I,J);if(W instanceof Promise){if(J.async===!1)throw new y$;return W.then((Y)=>$._zod.parse(Y,J))}return $._zod.parse(W,J)};$._zod.run=(b,U)=>{if(U.skipChecks)return $._zod.parse(b,U);if(U.direction==="backward"){let W=$._zod.parse({value:b.value,issues:[]},{...U,skipChecks:!0});if(W instanceof Promise)return W.then((Y)=>{return N(Y,b,U)});return N(W,b,U)}let J=$._zod.parse(b,U);if(J instanceof Promise){if(U.async===!1)throw new y$;return J.then((W)=>_(W,I,U))}return _(J,I,U)}}},{get "~standard"(){return Z_(this,"~standard",DN(this))},set "~standard"($){xv(this,"~standard",$)}}),QY=($,v)=>$.issues.length?{issues:$.issues.map((D)=>V$(D,v,N$()))}:{value:$.value};async function D3($,v){let D={async:!0};return QY(await $._zod.run({value:v,issues:[]},D),D)}function DN($){return{validate:(v)=>{let D={async:!1};try{let g=$._zod.run({value:v,issues:[]},D);if(!(g instanceof Promise))return QY(g,D)}catch(g){}return D3($,v)},vendor:"zod",version:1}}var F6=z("$ZodString",($,v)=>{m.init($,v),$._zod.pattern=v.pattern??DJ,$._zod.parse=(D,g)=>{if(v.coerce)try{D.value=String(D.value)}catch(I){}if(typeof D.value==="string")return D;return D.issues.push({expected:"string",code:"invalid_type",input:D.value,inst:$}),D}}),e=z("$ZodStringFormat",($,v)=>{q4.init($,v),F6.init($,v)}),xJ=z("$ZodGUID",($,v)=>{v.pattern??(v.pattern=lU),e.init($,v)}),fJ=z("$ZodUUID",($,v)=>{if(v.version){let g={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[v.version];if(g===void 0)throw Error(`Invalid UUID version: "${v.version}"`);v.pattern??(v.pattern=H6(g))}else v.pattern??(v.pattern=H6());e.init($,v)}),yJ=z("$ZodEmail",($,v)=>{v.pattern??(v.pattern=nU),e.init($,v)}),uJ=1,u_=2;function iJ($){try{if(typeof URL<"u"&&typeof URL.canParse==="function")return URL.canParse($);return new URL($),!0}catch{return!1}}function gN($,v){if(!("normalize"in v)&&!("hostname"in v)&&!("protocol"in v))return iJ($)||u_;return YY($,v)}function YY($,v){if(!v.normalize&&v.protocol?.source===C_.source&&!/^https?:\/\//i.test($))return uJ;try{if(typeof URL<"u"){let D=URL;if(typeof D.parse==="function")return D.parse($)??u_}return new URL($)}catch{return u_}}var g3=/[\t\n\r]/g;function i_($){return $.replace(g3,"")}function NN($,v){return v.lastIndex=0,v.test($.hostname)}function bN($,v){return v.lastIndex=0,v.test($.protocol.endsWith(":")?$.protocol.slice(0,-1):$.protocol)}var lJ=z("$ZodURL",($,v)=>{e.init($,v),$._zod.check=(D)=>{try{let g=D.value.trim(),I=gN(g,v);if(I===uJ){D.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:D.value,inst:$,continue:!v.abort});return}if(I===u_){D.issues.push({code:"invalid_format",format:"url",input:D.value,inst:$,continue:!v.abort});return}if(I===!0){D.value=i_(g);return}if(v.hostname&&!NN(I,v.hostname))D.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:v.hostname.source,input:D.value,inst:$,continue:!v.abort});if(v.protocol&&!bN(I,v.protocol))D.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:v.protocol.source,input:D.value,inst:$,continue:!v.abort});D.value=v.normalize?I.href:i_(g);return}catch(g){D.issues.push({code:"invalid_format",format:"url",input:D.value,inst:$,continue:!v.abort})}}}),nJ=z("$ZodEmoji",($,v)=>{v.pattern??(v.pattern=mU()),e.init($,v)}),mJ=z("$ZodNanoID",($,v)=>{if(v.length!==void 0&&(!Number.isInteger(v.length)||v.length<1))throw Error(`Invalid nanoid length: ${v.length}`);v.pattern??(v.pattern=v.length===void 0?yU:uU(v.length)),e.init($,v)}),hJ=z("$ZodCUID",($,v)=>{v.pattern??(v.pattern=kU),e.init($,v)}),rJ=z("$ZodCUID2",($,v)=>{v.pattern??(v.pattern=RU),e.init($,v)}),dJ=z("$ZodULID",($,v)=>{v.pattern??(v.pattern=CU),e.init($,v)}),pJ=z("$ZodXID",($,v)=>{v.pattern??(v.pattern=xU),e.init($,v)}),cJ=z("$ZodKSUID",($,v)=>{v.pattern??(v.pattern=fU),e.init($,v)}),tJ=z("$ZodISODateTime",($,v)=>{v.pattern??(v.pattern=_J(v)),e.init($,v)}),oJ=z("$ZodISODate",($,v)=>{v.pattern??(v.pattern=vJ),e.init($,v)}),aJ=z("$ZodISOTime",($,v)=>{v.pattern??(v.pattern=IJ(v)),e.init($,v)}),eJ=z("$ZodISODuration",($,v)=>{v.pattern??(v.pattern=iU),e.init($,v)}),sJ=z("$ZodIPv4",($,v)=>{v.pattern??(v.pattern=hU),e.init($,v)}),N3=/^[0-9a-fA-F:.]+$/;function l_($){if(!N3.test($))return!1;return iJ(`http://[${$}]`)}var $0=z("$ZodIPv6",($,v)=>{v.pattern??(v.pattern=rU),e.init($,v),$._zod.check=(D)=>{if(!l_(D.value))D.issues.push({code:"invalid_format",format:"ipv6",input:D.value,inst:$,continue:!v.abort})}}),v0=z("$ZodMAC",($,v)=>{v.pattern??(v.pattern=dU(v.delimiter)),e.init($,v)}),I0=z("$ZodCIDRv4",($,v)=>{v.pattern??(v.pattern=pU),e.init($,v)});function UN($){let v=$.split("/");if(v.length!==2)return!1;let[D,g]=v;if(!g)return!1;let I=Number(g);if(`${I}`!==g)return!1;if(I<0||I>128)return!1;return l_(D)}var _0=z("$ZodCIDRv6",($,v)=>{v.pattern??(v.pattern=cU),e.init($,v),$._zod.check=(D)=>{if(!UN(D.value))D.issues.push({code:"invalid_format",format:"cidrv6",input:D.value,inst:$,continue:!v.abort})}});function n_($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}var JN=/^[0-9a-zA-Z+/]*={0,2}$/,D0=z("$ZodBase64",($,v)=>{v.pattern??(v.pattern=JN),e.init($,v),$._zod.check=(D)=>{if(n_(D.value))return;D.issues.push({code:"invalid_format",format:"base64",input:D.value,inst:$,continue:!v.abort})}}),m_=/^[A-Za-z0-9_-]*$/;function XN($){if(!m_.test($))return!1;let v=$.replace(/[-_]/g,(g)=>g==="-"?"+":"/"),D=v.padEnd(Math.ceil(v.length/4)*4,"=");return n_(D)}var g0=z("$ZodBase64URL",($,v)=>{v.pattern??(v.pattern=m_),e.init($,v),$._zod.check=(D)=>{if(XN(D.value))return;D.issues.push({code:"invalid_format",format:"base64url",input:D.value,inst:$,continue:!v.abort})}}),N0=z("$ZodE164",($,v)=>{v.pattern??(v.pattern=sU),e.init($,v)}),b3=/[- ]/g;function U3($){let v=$.length,D=1,g=0;while(v){let I=$.charCodeAt(--v)-48;D^=1,g+=D?[0,2,4,6,8,1,3,5,7,9][I]:I}return g%10===0}function WN($){if(!cg.test($))return!1;return U3($.replace(b3,""))}var b0=z("$ZodCreditCard",($,v)=>{v.pattern??(v.pattern=cg),e.init($,v),$._zod.check=(D)=>{if(WN(D.value))return;D.issues.push({code:"invalid_format",format:"credit_card",input:D.value,inst:$,continue:!v.abort})}});function J3($){let v=0,D=$.length;for(let g=4;g=65?v*100+(I-55):v*10+(I-48))%97}for(let g=0;g<4;g++){let I=$.charCodeAt(g);v=(I>=65?v*100+(I-55):v*10+(I-48))%97}return v===1}function QN($){if(!tg.test($))return!1;return J3($)}var U0=z("$ZodIBAN",($,v)=>{v.pattern??(v.pattern=tg),e.init($,v),$._zod.check=(D)=>{if(QN(D.value))return;D.issues.push({code:"invalid_format",format:"iban",input:D.value,inst:$,continue:!v.abort})}});function YN($,v=null){try{let D=$.split(".");if(D.length!==3)return!1;let[g]=D;if(!g)return!1;let I=JSON.parse(atob(g));if("typ"in I&&I?.typ!=="JWT")return!1;if(!I.alg)return!1;if(v&&(!("alg"in I)||I.alg!==v))return!1;return!0}catch{return!1}}var J0=z("$ZodJWT",($,v)=>{e.init($,v),$._zod.check=(D)=>{if(YN(D.value,v.alg))return;D.issues.push({code:"invalid_format",format:"jwt",input:D.value,inst:$,continue:!v.abort})}}),X0=z("$ZodCustomStringFormat",($,v)=>{e.init($,v),$._zod.check=(D)=>{if(v.fn(D.value))return;D.issues.push({code:"invalid_format",format:v.format,input:D.value,inst:$,continue:!v.abort})}}),GN=z("$ZodNumber",($,v)=>{m.init($,v),$._zod.pattern=_v,$._zod.parse=(D,g)=>{if(v.coerce)try{D.value=Number(D.value)}catch(N){}let I=D.value;if(typeof I==="number"&&!Number.isNaN(I)&&Number.isFinite(I))return D;let _=typeof I==="number"?Number.isNaN(I)?"NaN":!Number.isFinite(I)?String(I):void 0:void 0;return D.issues.push({expected:"number",code:"invalid_type",input:I,inst:$,..._?{received:_}:{}}),D}}),W0=z("$ZodNumberFormat",($,v)=>{jJ.init($,v),GN.init($,v)}),h_=z("$ZodBoolean",($,v)=>{m.init($,v),$._zod.pattern=bJ,$._zod.parse=(D,g)=>{if(v.coerce)try{D.value=Boolean(D.value)}catch(_){}let I=D.value;if(typeof I==="boolean")return D;return D.issues.push({expected:"boolean",code:"invalid_type",input:I,inst:$}),D}}),BN=z("$ZodBigInt",($,v)=>{m.init($,v),$._zod.pattern=NJ,$._zod.parse=(D,g)=>{if(v.coerce)try{D.value=BigInt(D.value)}catch(I){}if(typeof D.value==="bigint")return D;return D.issues.push({expected:"bigint",code:"invalid_type",input:D.value,inst:$}),D}}),Q0=z("$ZodBigIntFormat",($,v)=>{zJ.init($,v),BN.init($,v)}),Y0=z("$ZodSymbol",($,v)=>{m.init($,v),$._zod.parse=(D,g)=>{let I=D.value;if(typeof I==="symbol")return D;return D.issues.push({expected:"symbol",code:"invalid_type",input:I,inst:$}),D}}),G0=z("$ZodUndefined",($,v)=>{m.init($,v),$._zod.pattern=JJ,$._zod.values=new Set([void 0]),$._zod.parse=(D,g)=>{let I=D.value;if(typeof I>"u")return D;return D.issues.push({expected:"undefined",code:"invalid_type",input:I,inst:$}),D}}),B0=z("$ZodNull",($,v)=>{m.init($,v),$._zod.pattern=UJ,$._zod.values=new Set([null]),$._zod.parse=(D,g)=>{let I=D.value;if(I===null)return D;return D.issues.push({expected:"null",code:"invalid_type",input:I,inst:$}),D}}),j0=z("$ZodAny",($,v)=>{m.init($,v),$._zod.parse=(D)=>D}),z0=z("$ZodUnknown",($,v)=>{m.init($,v),$._zod.parse=(D)=>D}),K0=z("$ZodNever",($,v)=>{m.init($,v),$._zod.parse=(D,g)=>{return D.issues.push({expected:"never",code:"invalid_type",input:D.value,inst:$}),D}}),O0=z("$ZodVoid",($,v)=>{m.init($,v),$._zod.parse=(D,g)=>{let I=D.value;if(typeof I>"u")return D;return D.issues.push({expected:"void",code:"invalid_type",input:I,inst:$}),D}}),H0=z("$ZodDate",($,v)=>{m.init($,v),$._zod.parse=(D,g)=>{if(v.coerce)try{D.value=new Date(D.value)}catch(b){}let I=D.value,_=I instanceof Date;if(_&&!Number.isNaN(I.getTime()))return D;return D.issues.push({expected:"date",code:"invalid_type",input:I,..._?{received:"Invalid Date"}:{},inst:$}),D}});function F0($,v){let D=K4($._zod.def.checks);if(!D.length)return;let g=Math.min(...D.map((_)=>_[0])),I=$._zod.parse;$._zod.parse=(_,N)=>{let b=v(_.value);if(b>g&&!N?.skipChecks&&N?.direction!=="backward"){for(let[U,J]of K4($._zod.def.checks))if(b>U&&J._zod.def.when(_)){let W=_.issues.length;return J._zod.check(_),_.issues[W].continue=!1,T_(_.issues,W,$),_}}return I(_,N)}}var X3=($)=>Array.isArray($)?$.length:-1,W3=($)=>$ instanceof Map?$.size:-1,Q3=($)=>$ instanceof Set?$.size:-1;function a9($,v,D){if($.issues.length)v.issues.push(...E$(D,$.issues));v.value[D]=$.value}var P0=z("$ZodArray",($,v)=>{m.init($,v);let D=Q$.memoizer;D?.attach($),$._zod.parse=(g,I)=>{let _=g.value;if(!Array.isArray(_))return g.issues.push({expected:"array",code:"invalid_type",input:_,inst:$}),g;g.value=D?D.alloc($,g,Array(_.length),I):Array(_.length);let N=[],b=I?.abortEarly;for(let U=0;U<_.length;U++){let J=_[U],W=v.element._zod.run({value:J,issues:[]},I);if(W instanceof Promise)N.push(W.then((Y)=>a9(Y,g,U)));else if(a9(W,g,U),b&&W.issues.length!==0&&M$(W))break}if(N.length)return Promise.all(N).then(()=>g);return g},F0($,X3)});function _N($,v,D,g,I,_){let N=D in g,b=_==="optional";if(!N&&b&&I==="optional")return;if($.issues.length){if(I!==void 0&&b&&!N)return;v.issues.push(...E$(D,$.issues))}if(!N&&I===void 0){if(!$.issues.length)v.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[D]});return}if($.value===void 0){if(N||I==="defaulted"&&!b)v.value[D]=void 0}else v.value[D]=$.value}var Y3=[];function GY($){let v=Object.keys($.shape),D=Object.getOwnPropertySymbols($.shape),g=D.length?D:Y3,I=g.length?[...v,...g]:v;for(let N of I)if(!$.shape?.[N]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${String(N)}": expected a Zod schema`);let _=FU($.shape);return{...$,allKeys:I,symbolKeys:g,keySet:new Set(v),numKeys:v.length,optionalKeys:new Set(_)}}function BY($,v,D,g,I,_,N){let b=[],U=I.keySet,J=I.catchall._zod,W=J.def.type,Y=J.optin,B=J.optout,j=0;for(let K in v){if(N&&D.issues.length!==j){if(M$(D,j))break;j=D.issues.length}if(U.has(K))continue;if(K==="__proto__"){if(W==="never")b.push(K);continue}if(W==="never"){b.push(K);continue}let F=J.run({value:v[K],issues:[]},g);if(F instanceof Promise)$.push(F.then((T)=>_N(T,D,K,v,Y,B)));else _N(F,D,K,v,Y,B)}if(b.length)D.issues.push({code:"unrecognized_keys",keys:b,input:v,inst:_,continue:!0});if(!$.length)return D;return Promise.all($).then(()=>{return D})}var jY=z("$ZodObject",($,v)=>{m.init($,v);let D=Object.getOwnPropertyDescriptor(v,"shape"),g=D?.get?D.get.raw:v.shape??{};if(g){let J=()=>{let W={...g};return Object.defineProperty(v,"shape",{value:W}),J.raw=W,W};J.raw=g,Object.defineProperty(v,"shape",{get:J})}let I=j4(()=>GY(v));d($,"propValues",(J)=>{let W=J.def.shape,Y={};for(let B in W){let j=W[B]._zod;if(j.values){if(!Object.prototype.hasOwnProperty.call(Y,B))B$(Y,B,new Set);for(let K of j.values)Y[B].add(K);if(j.optin!==void 0)Y[B].add(void 0)}}return Y});let _=z6,N=v.catchall,b,U=Q$.memoizer;U?.attach($),$._zod.parse=(J,W)=>{b??(b=I.value);let Y=J.value;if(!_(Y))return J.issues.push({expected:"object",code:"invalid_type",input:Y,inst:$}),J;J.value=U?U.alloc($,J,{},W):{};let B=[],j=b.shape,K=W?.abortEarly,F=J.issues.length;for(let T of b.allKeys){if(K&&J.issues.length!==F){if(M$(J,F))break;F=J.issues.length}if(T==="__proto__")continue;let V=j[T],Z=V._zod.optin,f=V._zod.optout,r=V._zod.run({value:Y[T],issues:[]},W);if(r instanceof Promise)B.push(r.then((t)=>_N(t,J,T,Y,Z,f)));else _N(r,J,T,Y,Z,f)}if(!N)return B.length?Promise.all(B).then(()=>J):J;return BY(B,Y,J,W,I.value,$,K===!0)}}),w0=z("$ZodObjectJIT",($,v)=>{jY.init($,v);let D=$._zod.parse,g=j4(()=>GY(v)),I=Q$.memoizer,_=(j)=>{let K=g.value,F=K.symbolKeys,T=new M4(["payload","ctx"],{shape:j,inst:$,memo:I,syms:F}),V=(t)=>`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`,Z=(t,y)=>` + let ${t}_ab = false; + for (let i = 0; i < ${t}.issues.length; i++) { + const iss = ${t}.issues[i]; + iss.path = iss.path ? [${y}, ...iss.path] : [${y}]; + payload.issues.push(iss); + if (iss.continue !== true) ${t}_ab = true; + } + if (${t}_ab && ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + }`;T.write("const input = payload.value;");let f=Object.create(null),r=0;for(let t of K.allKeys)f[t]=`key_${r++}`;T.write(I?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(let t of K.allKeys){if(t==="__proto__")continue;let y=f[t],o=typeof t==="symbol"?`syms[${F.indexOf(t)}]`:q$(t),C$=`${o} in input`,W$=j[t],n$=W$?._zod?.optin,$v=n$!==void 0,v6=W$?._zod?.optout==="optional";if(T.write(`const ${y} = ${V(o)};`),$v&&v6){let I6=n$==="optional"?`${y}_present`:`${y}.value !== undefined || ${y}_present`;T.write(` + const ${y}_present = ${C$}; + if (!${y}.issues.length || ${y}_present) { + if (${y}.issues.length) {${Z(y,o)} + } + + if (${I6}) { + newResult[${o}] = ${y}.value; + } + } + + `)}else if(!$v)T.write(` + const ${y}_present = ${C$}; + if (${y}.issues.length) {${Z(y,o)} + } + if (!${y}_present && !${y}.issues.length) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: undefined, + path: [${o}] + }); + if (ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + } + } + + if (${y}_present) { + newResult[${o}] = ${y}.value; + } + + `);else if(T.write(` + if (${y}.issues.length) {${Z(y,o)} + } + `),n$==="defaulted")T.write(`newResult[${o}] = ${y}.value;`);else T.write(` + if (${y}.value !== undefined || ${C$}) { + newResult[${o}] = ${y}.value; + } + `)}return T.write("payload.value = newResult;"),T.write("return payload;"),T.compile()},N,b=z6,U=!Q$.jitless,W=U&&OU.value,Y=v.catchall,B;$._zod.parse=(j,K)=>{B??(B=g.value);let F=j.value;if(!b(F))return j.issues.push({expected:"object",code:"invalid_type",input:F,inst:$}),j;if(U&&W&&K?.async===!1&&K.jitless!==!0){if(!N)N=_(v.shape);if(j=N(j,K),!Y)return j;return BY([],F,j,K,B,$,K?.abortEarly===!0)}return D(j,K)}});function e9($,v,D,g){for(let _ of $)if(_.issues.length===0)return v.value=_.value,v;let I=$.filter((_)=>!M$(_));if(I.length===1)return v.value=I[0].value,I[0];return v.issues.push({code:"invalid_union",input:v.value,inst:D,errors:$.map((_)=>_.issues.map((N)=>V$(N,g,N$())))}),v}var r_=z("$ZodUnion",($,v)=>{m.init($,v),d($,"optin",(g)=>g.def.options.some((I)=>I._zod.optin==="defaulted")?"defaulted":g.def.options.some((I)=>I._zod.optin!==void 0)?"optional":void 0),d($,"optout",(g)=>g.def.options.some((I)=>I._zod.optout==="optional")?"optional":void 0),d($,"values",(g)=>{if(g.def.options.every((I)=>I._zod.values))return new Set(g.def.options.flatMap((I)=>Array.from(I._zod.values)));return}),d($,"pattern",(g)=>{if(g.def.options.every((I)=>I._zod.pattern)){let I=g.def.options.map((_)=>_._zod.pattern);return new RegExp(`^(${I.map((_)=>Ov(_.source)).join("|")})$`)}return});let D=v.options.length===1?v.options[0]._zod.run:null;$._zod.parse=(g,I)=>{if(D)return D(g,I);let _=!1,N=[];for(let b of v.options){let U=b._zod.run({value:g.value,issues:[]},I);if(U instanceof Promise)N.push(U),_=!0;else{if(U.issues.length===0)return U;N.push(U)}}if(!_)return e9(N,g,$,I);return Promise.all(N).then((b)=>{return e9(b,g,$,I)})}});function s9($,v,D,g){let I=[];for(let _=0;_<$.length;_++)if($[_].issues.length===0)I.push(_);if(I.length===1)return v.value=$[I[0]].value,v;if(I.length===0)v.issues.push({code:"invalid_union",input:v.value,inst:D,errors:$.map((_)=>_.issues.map((N)=>V$(N,g,N$())))});else v.issues.push({code:"invalid_union",input:v.value,inst:D,errors:[],inclusive:!1,matches:I});return v}var q0=z("$ZodXor",($,v)=>{r_.init($,v),v.inclusive=!1;let D=v.options.length===1?v.options[0]._zod.run:null;$._zod.parse=(g,I)=>{if(D)return D(g,I);let _=!1,N=[];for(let b of v.options){let U=b._zod.run({value:g.value,issues:[]},I);if(U instanceof Promise)N.push(U),_=!0;else N.push(U)}if(!_)return s9(N,g,$,I);return Promise.all(N).then((b)=>{return s9(b,g,$,I)})}});function M0($,v){let D=$._zod,g=D.bag.optionsMap;if(!g)g=zY(D.def),D.bag.optionsMap=g;let I=g.get(v);if(I===null)throw Error(`Ambiguous discriminator value "${String(v)}"`);return I}function zY($){let v=new Map;for(let D of $.options){let g=D._zod.propValues?.[$.discriminator];if(!g||g.size===0)throw Error(`Invalid discriminated union option at index "${$.options.indexOf(D)}"`);for(let I of g)if(v.has(I)){if(I!==void 0)throw Error(`Duplicate discriminator value "${String(I)}"`);v.set(I,null)}else v.set(I,D)}return v}var T0=z("$ZodDiscriminatedUnion",($,v)=>{v.inclusive=!1,r_.init($,v);let D=$._zod.parse;d($,"propValues",(I)=>{let _={},N=0;for(let b of I.def.options){let U=b._zod.propValues;if(!U||Object.keys(U).length===0)throw Error(`Invalid discriminated union option at index "${I.def.options.indexOf(b)}"`);if(U[I.def.discriminator]?.has(void 0))N++;for(let[J,W]of Object.entries(U)){if(!Object.prototype.hasOwnProperty.call(_,J))B$(_,J,new Set);for(let Y of W)_[J].add(Y)}}if(!I.def.unionFallback&&N>1)_[I.def.discriminator]?.delete(void 0);return _}),v.options.forEach((I,_)=>{let N=z4(I._zod.def);if(N&&!Object.prototype.hasOwnProperty.call(N,v.discriminator))throw Error(`Invalid discriminated union option at index "${_}"`)});let g=j4(()=>zY(v));$._zod.parse=(I,_)=>{let N=I.value;if(!z6(N))return I.issues.push({code:"invalid_type",expected:"object",input:N,inst:$}),I;let b=N?.[v.discriminator],U=g.value.get(b);if(U&&(b!==void 0||_.direction!=="backward"))return U._zod.run(I,_);if(v.unionFallback||_.direction==="backward")return D(I,_);return I.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:v.discriminator,options:Array.from(g.value.keys()).filter((J)=>g.value.get(J)!==null),input:N,path:[v.discriminator],inst:$}),I}}),S0=z("$ZodIntersection",($,v)=>{m.init($,v),$._zod.parse=(D,g)=>{let I=D.value,_=v.left._zod.run({value:I,issues:[]},g),N=v.right._zod.run({value:I,issues:[]},g);if(_ instanceof Promise||N instanceof Promise)return Promise.all([_,N]).then(([U,J])=>{return $Y(D,U,J)});return $Y(D,_,N)}});function T4($,v){if($===v)return{valid:!0,data:$};if($ instanceof Date&&v instanceof Date&&+$===+v)return{valid:!0,data:$};if(h$($)&&h$(v)){let D=Object.keys(v),g=Object.keys($).filter((_)=>D.indexOf(_)!==-1),I={...$,...v};if(Object.prototype.hasOwnProperty.call(I,"__proto__"))delete I.__proto__;for(let _ of g){if(_==="__proto__")continue;let N=T4($[_],v[_]);if(!N.valid)return{valid:!1,mergeErrorPath:[_,...N.mergeErrorPath]};I[_]=N.data}return{valid:!0,data:I}}if(Array.isArray($)&&Array.isArray(v)){if($.length!==v.length)return{valid:!1,mergeErrorPath:[]};let D=[];for(let g=0;g<$.length;g++){let I=$[g],_=v[g],N=T4(I,_);if(!N.valid)return{valid:!1,mergeErrorPath:[g,...N.mergeErrorPath]};D.push(N.data)}return{valid:!0,data:D}}return{valid:!1,mergeErrorPath:[]}}function $Y($,v,D){let g=new Map,I,_=new Map,N=(J,W)=>{let Y;if(J.code==="unrecognized_keys"&&!J.path?.length)I??(I=J),Y=J.keys;else if(J.code==="invalid_key"&&J.origin==="record"&&J.path?.length===1){let B=String(J.path[0]);if(!_.has(B))_.set(B,J);Y=[B]}else return!1;for(let B of Y){if(!g.has(B))g.set(B,{});g.get(B)[W]=!0}return!0};for(let J of v.issues)if(!N(J,"l"))$.issues.push(J);for(let J of D.issues)if(!N(J,"r"))$.issues.push(J);let b=[...g].filter(([,J])=>J.l&&J.r).map(([J])=>J);if(b.length){let J=I?b.filter((W)=>I.keys.includes(W)):[];if(J.length)$.issues.push({...I,keys:J});for(let W of b)if(!J.includes(W)&&_.has(W))$.issues.push(_.get(W))}let U=T4(v.value,D.value);if(!U.valid){if(M$($))return $;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(U.mergeErrorPath)}`)}return $.value=U.data,$}var jN=z("$ZodTuple",($,v)=>{m.init($,v);let D=v.items,g=Q$.memoizer;g?.attach($),$._zod.parse=(I,_)=>{let N=I.value;if(!Array.isArray(N))return I.issues.push({input:N,inst:$,expected:"tuple",code:"invalid_type"}),I;I.value=g?g.alloc($,I,[],_):[];let b=[],U=vY(D,"optin"),J=vY(D,"optout");if(!v.rest){if(N.lengthD.length)I.issues.push({code:"too_big",maximum:D.length,inclusive:!0,input:N,inst:$,origin:"array"})}let W=Array(D.length),Y=v.rest?_?.abortEarly:void 0,B=!1;for(let j=0;j{W[j]=F}));else if(W[j]=K,Y&&!B&&K.issues.length)B=M$(K)}if(v.rest&&!B){let j=D.length-1,K=N.slice(D.length),F=I.issues.length;for(let T of K){if(Y&&I.issues.length!==F){if(M$(I,F))break;F=I.issues.length}j++;let V=v.rest._zod.run({value:T,issues:[]},_);if(V instanceof Promise)b.push(V.then((Z)=>IY(Z,I,j)));else IY(V,I,j)}}if(b.length)return Promise.all(b).then(()=>_Y(W,I,D,N,J));return _Y(W,I,D,N,J)}});function vY($,v){for(let D=$.length-1;D>=0;D--)if(!(v==="optin"?$[D]._zod.optin!==void 0:$[D]._zod.optout==="optional"))return D+1;return 0}function IY($,v,D){if($.issues.length)v.issues.push(...E$(D,$.issues));v.value[D]=$.value}function _Y($,v,D,g,I){for(let _=0;_=I&&D[_]._zod.optin==="optional"){v.value.length=_;break}if(N.issues.length){if(!b&&_>=I){v.value.length=_;break}v.issues.push(...E$(_,N.issues))}v.value[_]=N.value}for(let _=v.value.length-1;_>=g.length;_--)if(D[_]._zod.optout==="optional"&&v.value[_]===void 0)v.value.length=_;else break;return v}var A0=z("$ZodRecord",($,v)=>{m.init($,v);let D=Q$.memoizer;D?.attach($),$._zod.parse=(g,I)=>{let _=g.value;if(!h$(_))return g.issues.push({expected:"record",code:"invalid_type",input:_,inst:$}),g;let N=[],b=v.keyType._zod.values;if(b&&!v.partial){g.value=D?D.alloc($,g,{},I):{};let U=new Set;for(let W of b)if(typeof W==="string"||typeof W==="number"||typeof W==="symbol"){if(U.add(typeof W==="number"?W.toString():W),W==="__proto__")continue;let Y=v.keyType._zod.run({value:W,issues:[]},I);if(Y instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(Y.issues.length){g.issues.push({code:"invalid_key",origin:"record",issues:Y.issues.map((K)=>V$(K,I,N$())),input:W,path:[W],inst:$});continue}let B=Y.value;if(B==="__proto__")continue;let j=v.valueType._zod.run({value:_[W],issues:[]},I);if(j instanceof Promise)N.push(j.then((K)=>{if(K.issues.length)g.issues.push(...E$(W,K.issues));g.value[B]=K.value}));else{if(j.issues.length)g.issues.push(...E$(W,j.issues));g.value[B]=j.value}}let J;for(let W in _)if(!U.has(W))if(v.mode==="loose"){if(W==="__proto__")continue;g.value[W]=_[W]}else J=J??[],J.push(W);if(J&&J.length>0)g.issues.push({code:"unrecognized_keys",input:_,inst:$,keys:J,continue:!0})}else{g.value=D?D.alloc($,g,{},I):{};let U;for(let J of Reflect.ownKeys(_)){if(J==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(_,J))continue;let W=v.keyType._zod.run({value:J,issues:[]},I);if(W instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof J==="string"&&_v.test(J)&&W.issues.length){let K=v.keyType._zod.run({value:Number(J),issues:[]},I);if(K instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(K.issues.length===0)W=K}if(W.issues.length){if(v.mode==="loose")g.value[J]=_[J];else if(b)U=U??[],U.push(J);else g.issues.push({code:"invalid_key",origin:"record",issues:W.issues.map((K)=>V$(K,I,N$())),input:J,path:[J],inst:$});continue}let B=W.value;if(B==="__proto__")continue;let j=v.valueType._zod.run({value:_[J],issues:[]},I);if(j instanceof Promise)N.push(j.then((K)=>{if(K.issues.length)g.issues.push(...E$(J,K.issues));g.value[B]=K.value}));else{if(j.issues.length)g.issues.push(...E$(J,j.issues));g.value[B]=j.value}}if(U&&U.length>0)g.issues.push({code:"unrecognized_keys",input:_,inst:$,keys:U,continue:!0})}if(N.length)return Promise.all(N).then(()=>g);return g}}),Z0=z("$ZodMap",($,v)=>{m.init($,v);let D=Q$.memoizer;D?.attach($),$._zod.parse=(g,I)=>{let _=g.value;if(!(_ instanceof Map))return g.issues.push({expected:"map",code:"invalid_type",input:_,inst:$}),g;let N=[];g.value=D?D.alloc($,g,new Map,I):new Map;let b=I?.abortEarly,U=g.issues.length;for(let[J,W]of _){if(b&&g.issues.length!==U){if(M$(g,U))break;U=g.issues.length}let Y=v.keyType._zod.run({value:J,issues:[]},I),B=v.valueType._zod.run({value:W,issues:[]},I);if(Y instanceof Promise||B instanceof Promise)N.push(Promise.all([Y,B]).then(([j,K])=>{DY(j,K,g,J,_,$,I)}));else DY(Y,B,g,J,_,$,I)}if(N.length)return Promise.all(N).then(()=>g);return g},F0($,W3)});function DY($,v,D,g,I,_,N){if($.issues.length)if(w_.has(typeof g))D.issues.push(...E$(g,$.issues));else D.issues.push({code:"invalid_key",origin:"map",input:I,inst:_,issues:$.issues.map((b)=>V$(b,N,N$()))});if(v.issues.length)if(w_.has(typeof g))D.issues.push(...E$(g,v.issues));else D.issues.push({origin:"map",code:"invalid_element",input:I,inst:_,key:g,issues:v.issues.map((b)=>V$(b,N,N$()))});D.value.set($.value,v.value)}var L0=z("$ZodSet",($,v)=>{m.init($,v);let D=Q$.memoizer;D?.attach($),$._zod.parse=(g,I)=>{let _=g.value;if(!(_ instanceof Set))return g.issues.push({input:_,inst:$,expected:"set",code:"invalid_type"}),g;let N=[];g.value=D?D.alloc($,g,new Set,I):new Set;let b=I?.abortEarly,U=g.issues.length;for(let J of _){if(b&&g.issues.length!==U){if(M$(g,U))break;U=g.issues.length}let W=v.valueType._zod.run({value:J,issues:[]},I);if(W instanceof Promise)N.push(W.then((Y)=>gY(Y,g)));else gY(W,g)}if(N.length)return Promise.all(N).then(()=>g);return g},F0($,Q3)});function gY($,v){if($.issues.length)v.issues.push(...$.issues);v.value.add($.value)}var E0=z("$ZodEnum",($,v)=>{m.init($,v);let D=G4(v.entries),g=new Set(D);$._zod.values=g,d($,"pattern",(I)=>{let _=G4(I.def.entries).filter((N)=>w_.has(typeof N));return new RegExp(_.length?`^(${_.map((N)=>r$(N.toString())).join("|")})$`:"^[^\\s\\S]$")}),$._zod.parse=(I,_)=>{let N=I.value;if(g.has(N))return I;return I.issues.push({code:"invalid_value",values:D,input:N,inst:$}),I}}),V0=z("$ZodLiteral",($,v)=>{m.init($,v);let D=new Set(v.values);$._zod.values=D,d($,"pattern",(g)=>{let I=g.def.values;return new RegExp(I.length?`^(${I.map((_)=>typeof _==="string"?r$(_):_?r$(_.toString()):String(_)).join("|")})$`:"^[^\\s\\S]$")}),$._zod.parse=(g,I)=>{let _=g.value;if(D.has(_))return g;return g.issues.push({code:"invalid_value",values:v.values,input:_,inst:$}),g}}),k0=z("$ZodFile",($,v)=>{m.init($,v),$._zod.parse=(D,g)=>{let I=D.value;if(I instanceof File)return D;return D.issues.push({expected:"file",code:"invalid_type",input:I,inst:$}),D}}),R0=z("$ZodTransform",($,v)=>{m.init($,v),$._zod.optin="optional",Q$.memoizer?.guard($),$._zod.parse=(D,g)=>{if(g.direction==="backward")throw new O6($.constructor.name);let I=v.transform(D.value,D);if(g.async)return(I instanceof Promise?I:Promise.resolve(I)).then((N)=>{return D.value=N,D});if(I instanceof Promise)throw new y$;return D.value=I,D}});function NY($,v){return $.value=v.issues.length?void 0:v.value,$}var zN=z("$ZodOptional",($,v)=>{m.init($,v),d($,"optin",(D)=>D.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),$._zod.optout="optional",d($,"values",(D)=>{let g=D.def.innerType._zod.values;return g?new Set([...g,void 0]):void 0}),d($,"pattern",(D)=>{let g=D.def.innerType._zod.pattern;return g?new RegExp(`^(${Ov(g.source)})?$`):void 0}),$._zod.parse=(D,g)=>{if(D.value===void 0){if(v.innerType._zod.optin!=="defaulted")return D;let I=v.innerType._zod.run({value:D.value,issues:[]},g);if(I instanceof Promise)return I.then((_)=>NY(D,_));return NY(D,I)}return v.innerType._zod.run(D,g)}}),C0=z("$ZodExactOptional",($,v)=>{zN.init($,v),d($,"values",(D)=>D.def.innerType._zod.values),d($,"pattern",(D)=>D.def.innerType._zod.pattern),$._zod.parse=(D,g)=>{return v.innerType._zod.run(D,g)}}),x0=z("$ZodNullable",($,v)=>{m.init($,v),d($,"optin",(D)=>D.def.innerType._zod.optin),d($,"optout",(D)=>D.def.innerType._zod.optout),d($,"pattern",(D)=>{let g=D.def.innerType._zod.pattern;return g?new RegExp(`^(${Ov(g.source)}|null)$`):void 0}),d($,"values",(D)=>{return D.def.innerType._zod.values?new Set([...D.def.innerType._zod.values,null]):void 0}),$._zod.parse=(D,g)=>{if(D.value===null)return D;return v.innerType._zod.run(D,g)}}),f0=z("$ZodDefault",($,v)=>{m.init($,v),$._zod.optin="defaulted",d($,"values",(D)=>D.def.innerType._zod.values),$._zod.parse=(D,g)=>{if(g.direction==="backward")return v.innerType._zod.run(D,g);if(D.value===void 0)return D.value=v.defaultValue,D;let I=v.innerType._zod.run(D,g);if(I instanceof Promise)return I.then((_)=>bY(_,v));return bY(I,v)}});function bY($,v){if($.value===void 0)$.value=v.defaultValue;return $}var y0=z("$ZodPrefault",($,v)=>{m.init($,v),$._zod.optin="defaulted",d($,"values",(D)=>D.def.innerType._zod.values),$._zod.parse=(D,g)=>{if(g.direction==="backward")return v.innerType._zod.run(D,g);if(D.value===void 0)D.value=v.defaultValue;return v.innerType._zod.run(D,g)}}),u0=z("$ZodNonOptional",($,v)=>{m.init($,v),d($,"values",(D)=>{let g=D.def.innerType._zod.values;return g?new Set([...g].filter((I)=>I!==void 0)):void 0}),$._zod.parse=(D,g)=>{let I=v.innerType._zod.run(D,g);if(I instanceof Promise)return I.then((_)=>UY(_,$));return UY(I,$)}});function UY($,v){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:v});return $}var i0=z("$ZodSuccess",($,v)=>{m.init($,v),$._zod.parse=(D,g)=>{if(g.direction==="backward")throw new O6("ZodSuccess");let I=v.innerType._zod.run(D,g);if(I instanceof Promise)return I.then((_)=>{return D.value=_.issues.length===0,D});return D.value=I.issues.length===0,D}});function JY($,v,D,g){if(!v.issues.length){if($.value=v.value,v.memo)$.memo=!0;return $}return $.value=D.catchValue({...v,value:$.value,error:{issues:v.issues.map((I)=>V$(I,g,N$()))},input:$.value}),$}var l0=z("$ZodCatch",($,v)=>{m.init($,v),d($,"optin",(D)=>D.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),d($,"optout",(D)=>D.def.innerType._zod.optout),d($,"values",(D)=>D.def.innerType._zod.values),$._zod.parse=(D,g)=>{if(g.direction==="backward")return v.innerType._zod.run(D,g);let I=v.innerType._zod.run({value:D.value,issues:[]},g);if(I instanceof Promise)return I.then((_)=>JY(D,_,v,g));return JY(D,I,v,g)}}),n0=z("$ZodNaN",($,v)=>{m.init($,v),$._zod.parse=(D,g)=>{if(typeof D.value!=="number"||!Number.isNaN(D.value))return D.issues.push({input:D.value,inst:$,expected:"nan",code:"invalid_type"}),D;return D}}),KN=z("$ZodPipe",($,v)=>{m.init($,v),d($,"values",(D)=>D.def.in._zod.values),d($,"optin",(D)=>D.def.in._zod.optin),d($,"optout",(D)=>D.def.out._zod.optout),d($,"propValues",(D)=>D.def.in._zod.propValues),$._zod.parse=(D,g)=>{if(g.direction==="backward"){let _=v.out._zod.run(D,g);if(_ instanceof Promise)return _.then((N)=>$N(N,v.in,g));return $N(_,v.in,g)}let I=v.in._zod.run(D,g);if(I instanceof Promise)return I.then((_)=>$N(_,v.out,g));return $N(I,v.out,g)}});function $N($,v,D){if($.issues.some((g)=>g.code!=="unrecognized_keys"))return $.aborted=!0,$;return v._zod.run({value:$.value,issues:$.issues},D)}var d_=z("$ZodCodec",($,v)=>{m.init($,v),d($,"values",(D)=>D.def.in._zod.values),d($,"optin",(D)=>D.def.in._zod.optin),d($,"optout",(D)=>D.def.out._zod.optout),d($,"propValues",(D)=>D.def.in._zod.propValues),$._zod.parse=(D,g)=>{if((g.direction||"forward")==="forward"){let _=v.in._zod.run(D,g);if(_ instanceof Promise)return _.then((N)=>vN(N,v,g));return vN(_,v,g)}else{let _=v.out._zod.run(D,g);if(_ instanceof Promise)return _.then((N)=>vN(N,v,g));return vN(_,v,g)}}});function vN($,v,D){if($.issues.length)return $.aborted=!0,$;if((D.direction||"forward")==="forward"){let I=v.transform($.value,$);if(I instanceof Promise)return I.then((_)=>IN($,_,v.out,D));return IN($,I,v.out,D)}else{let I=v.reverseTransform($.value,$);if(I instanceof Promise)return I.then((_)=>IN($,_,v.in,D));return IN($,I,v.in,D)}}function IN($,v,D,g){if($.issues.length)return $.aborted=!0,$;return D._zod.run({value:v,issues:$.issues},g)}var m0=z("$ZodPreprocess",($,v)=>{KN.init($,v)}),h0=z("$ZodReadonly",($,v)=>{m.init($,v),d($,"propValues",(D)=>D.def.innerType._zod.propValues),d($,"values",(D)=>D.def.innerType._zod.values),d($,"optin",(D)=>D.def.innerType?._zod?.optin),d($,"optout",(D)=>D.def.innerType?._zod?.optout),$._zod.parse=(D,g)=>{if(g.direction==="backward")return v.innerType._zod.run(D,g);let I=v.innerType._zod.run(D,g);if(I instanceof Promise)return I.then(XY);return XY(I)}});function XY($){if(!$.memo)$.value=Object.freeze($.value);return $}function G3($){let v=$._zod.def,D=v.pattern,g=!!v.format?.includes("int"),I,_;for(let b of v.checks??[]){let U=b._zod.def;if(U.pattern)D=U.pattern;g||(g=!!U.format?.includes("int"));let J=U.minimum??U.length,W=U.maximum??U.length;if(J!==void 0&&(I===void 0||J>I))I=J;if(W!==void 0&&(_===void 0||W<_))_=W}if(D)return D.source;if(I!==void 0&&_!==void 0&&I>_)return"(?!)";if(I!==void 0||_!==void 0)return gJ({minimum:I,maximum:_}).source;let N=$._zod.pattern;return(g&&N===_v?x_:N)?.source}function CJ($){let v=$._zod.def,D=$._zod.pattern?.source,g=v.innerType??$._zod.innerType;if(g){let I=g._zod.pattern?.source,_=CJ(g);if(D&&I&&_&&_!==I)return D.replace(Ov(I),()=>Ov(_));return D}if(v.options){let I=v.options.map(CJ);if(I.every(Boolean))return`^(${I.map((_)=>Ov(_)).join("|")})$`}return G3($)}var r0=z("$ZodTemplateLiteral",($,v)=>{m.init($,v);let D=[];for(let g of v.parts)if(typeof g==="object"&&g!==null){let I=CJ(g);if(!I)throw Error(`Invalid template literal part, no pattern found: ${[...g._zod.traits].shift()}`);D.push(Ov(I))}else if(g===null||HU.has(typeof g))D.push(r$(`${g}`));else throw Error(`Invalid template literal part: ${g}`);$._zod.pattern=new RegExp(`^${D.join("")}$`),$._zod.parse=(g,I)=>{if(typeof g.value!=="string")return g.issues.push({input:g.value,inst:$,expected:"string",code:"invalid_type"}),g;if($._zod.pattern.lastIndex=0,!$._zod.pattern.test(g.value))return g.issues.push({input:g.value,inst:$,code:"invalid_format",format:v.format??"template_literal",pattern:$._zod.pattern.source}),g;return g}}),d0=z("$ZodFunction",($,v)=>{return m.init($,v),Object.defineProperty($,"_def",{value:v}),$._zod.def=v,$.implement=(D)=>{if(typeof D!=="function")throw Error("implement() must be called with a function");return Object.defineProperty(function(...g){let I=$._def.input?yg($._def.input,g):g,_=Reflect.apply(D,this,I);if($._def.output)return yg($._def.output,_);return _},"_zod",{value:$._zod,enumerable:!1})},$.implementAsync=(D)=>{if(typeof D!=="function")throw Error("implementAsync() must be called with a function");return Object.defineProperty(async function(...g){let I=$._def.input?await ug($._def.input,g):g,_=await Reflect.apply(D,this,I);if($._def.output)return await ug($._def.output,_);return _},"_zod",{value:$._zod,enumerable:!1})},$._zod.parse=(D,g)=>{if(typeof D.value!=="function")return D.issues.push({code:"invalid_type",expected:"function",input:D.value,inst:$}),D;if($._def.output&&$._def.output._zod.def.type==="promise")D.value=$.implementAsync(D.value);else D.value=$.implement(D.value);return D},$.input=(...D)=>{let g=$.constructor;if(Array.isArray(D[0]))return new g({type:"function",input:new jN({type:"tuple",items:D[0],rest:D[1]}),output:$._def.output});return new g({type:"function",input:D[0],output:$._def.output})},$.output=(D)=>{return new $.constructor({type:"function",input:$._def.input,output:D})},$}),p0=z("$ZodPromise",($,v)=>{m.init($,v),$._zod.parse=(D,g)=>{return Promise.resolve(D.value).then((I)=>v.innerType._zod.run({value:I,issues:[]},g))}}),p_=z("$ZodLazy",($,v)=>{m.init($,v),zU($._zod,"innerType",()=>{let D=v;if(!D._cachedInner)D._cachedInner=v.getter();return D._cachedInner}),d($,"pattern",(D)=>D.innerType?._zod?.pattern),d($,"propValues",(D)=>D.innerType?._zod?.propValues),d($,"optin",(D)=>D.innerType?._zod?.optin??void 0),d($,"optout",(D)=>D.innerType?._zod?.optout??void 0),$._zod.parse=(D,g)=>{return $._zod.innerType._zod.run(D,g)}}),c0=z("$ZodCustom",($,v)=>{v$.init($,v),m.init($,v),$._zod.parse=(D,g)=>{return D},$._zod.check=(D)=>{let g=D.value,I=v.fn(g);if(I instanceof Promise)return I.then((_)=>WY(_,D,g,$));WY(I,D,g,$);return}});function WY($,v,D,g){if(!$){let I={code:"custom",input:D,inst:g,path:[...g._zod.def.path??[]],continue:!g._zod.def.abort};if(g._zod.def.params)I.params=g._zod.def.params;v.issues.push(O4(I))}}class a0 extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform");this.name="ZodCyclicError"}}var o0="~memo",OY=[];function HY($){return $!==null&&typeof $==="object"}function t0($){return $.map((v)=>v.path?{...v,path:v.path.slice()}:{...v})}var FY=new WeakMap,S4=0,FN=1,c_=2;function t_($,v,D){let g=FY.get($);if(g!==void 0)return g?c_:S4;if(v.has($))return c_;v.add($);let I=S4,_=(W)=>{if(I!==c_&&W?._zod){let Y=t_(W,v,D);if(Y>I)I=Y}},N=(W,Y)=>{let B=S4;for(let j of Reflect.ownKeys(W)){let K=Object.getOwnPropertyDescriptor(W,j);if(Y&&!K.enumerable)continue;let F=K.get?FN:K.value?._zod?t_(K.value,v,D):S4;if(F>B)B=F}return B},b=(W)=>{if(W>I)I=W},U=$._zod.def,J=U.type;switch(J){case"object":{let W=z4(U);b(W?N(W,!0):FN),_(U.catchall);break}case"array":_(U.element);break;case"tuple":for(let W of U.items)_(W);_(U.rest);break;case"record":case"map":_(U.keyType),_(U.valueType);break;case"set":_(U.valueType);break;case"union":for(let W of U.options)_(W);break;case"intersection":_(U.left),_(U.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":_(U.innerType);break;case"pipe":_(U.in),_(U.out);break;case"function":_(U.input),_(U.output);break;case"lazy":{let W=U._cachedInner??(D?$._zod.innerType:void 0);b(W?t_(W,v,!1):FN);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let W in U){let Y=Object.getOwnPropertyDescriptor(U,W);if(!Y||Y.get)continue;let B=Y.value;if(!B||typeof B!=="object")continue;if(B._zod)_(B);else if(Array.isArray(B))for(let j of B)_(j)}}return v.delete($),B3($,I)}function B3($,v){if(v!==FN)FY.set($,v===c_);return v}function PN($){return t_($,new Set,!0)!==S4}function j3($,v){let D=$.buckets.get(v);if(!D)D=new WeakMap,$.buckets.set(v,D);return D}var ON,HN=[],z3={alloc($,v,D){let g=ON;if(!g)return D;ON=void 0;let I={value:D,issues:null};return g.set(v.value,I),HN.push(I),D},guard($){var v;(v=$._zod).deferred??(v.deferred=[]),$._zod.deferred.push(()=>{let D=$._zod.parse,g=(I,_)=>{if(_.direction!=="backward"&&wN(_,I.value))throw new a0;return D(I,_)};if($._zod.parse=g,$._zod.run===D)$._zod.run=g})},attach($){var v;let D,g=!1,I,_;(v=$._zod).deferred??(v.deferred=[]),$._zod.deferred.push(()=>{let N=$._zod.parse,b=(U,J)=>{if(D===void 0){let V=t_($,new Set,!1);if(V===S4){if($._zod.parse=N,$._zod.run===b)$._zod.run=N;return N(U,J)}if(V===c_||g)D=!0;else g=!0}let W=U.value;if(!HY(W))return N(U,J);let Y=J[o0];if(!Y)Y={buckets:new WeakMap,backEdges:void 0},J[o0]=Y;let B;if(I===J)B=_;else B=j3(Y,$),I=J,_=B;let j=B.get(W);if(j){if(U.value=j.value,j.issues){if(j.issues.length)U.issues.push(...t0(j.issues))}else U.memo=!0,Y.backEdges??(Y.backEdges=new WeakSet),Y.backEdges.add(j.value);return U}ON=B;let K=HN.length,F=N(U,J);ON=void 0;let T=HN.length>K?HN.pop():void 0;if(F instanceof Promise)return F.then((V)=>{if(T)T.issues=V.issues.length?t0(V.issues):OY;return V});if(T)T.issues=F.issues.length?t0(F.issues):OY;return F};if($._zod.parse=b,$._zod.run===N)$._zod.run=b})}};function o_(){return z3}function wN($,v){let D=$[o0]?.backEdges;return D!==void 0&&HY(v)&&D.has(v)}var vD={};zv(vD,{zhTW:()=>I2,zhCN:()=>v2,yo:()=>_2,vi:()=>$2,uz:()=>sX,ur:()=>eX,uk:()=>$D,ua:()=>aX,tr:()=>oX,tk:()=>tX,th:()=>cX,tg:()=>pX,ta:()=>dX,sv:()=>rX,sl:()=>hX,sk:()=>mX,ru:()=>nX,ro:()=>lX,ptBR:()=>iX,pt:()=>uX,ps:()=>fX,pl:()=>yX,ota:()=>xX,no:()=>CX,nn:()=>RX,nl:()=>kX,ne:()=>VX,ms:()=>EX,mk:()=>LX,lt:()=>ZX,ko:()=>AX,kn:()=>SX,km:()=>e_,kh:()=>TX,ka:()=>MX,ja:()=>qX,it:()=>wX,is:()=>PX,id:()=>FX,hy:()=>HX,hu:()=>OX,hr:()=>KX,hi:()=>zX,he:()=>jX,gu:()=>BX,frCA:()=>GX,fr:()=>YX,fi:()=>QX,fa:()=>WX,es:()=>XX,eo:()=>JX,en:()=>a_,el:()=>UX,de:()=>bX,da:()=>NX,cs:()=>gX,ckb:()=>DX,ca:()=>_X,bn:()=>IX,bg:()=>vX,be:()=>$X,az:()=>s0,ar:()=>e0});var K3=()=>{let $={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"},map:{unit:"عنصر",verb:"أن يحوي"}};function v(I){return $[I]??null}let D={regex:"مدخل",email:"بريد إلكتروني",url:"رابط",emoji:"إيموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاريخ ووقت بمعيار ISO",date:"تاريخ بمعيار ISO",time:"وقت بمعيار ISO",duration:"مدة بمعيار ISO",ipv4:"عنوان IPv4",ipv6:"عنوان IPv6",mac:"عنوان MAC",cidrv4:"مدى عناوين بصيغة IPv4",cidrv6:"مدى عناوين بصيغة IPv6",base64:"نَص بترميز base64-encoded",base64url:"نَص بترميز base64url-encoded",json_string:"نَص على هيئة JSON",e164:"رقم هاتف بمعيار E.164",credit_card:"رقم بطاقة الائتمان",currency_code:"رمز العملة",iban:"IBAN",jwt:"JWT",template_literal:"مدخل"},g={nan:"NaN"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`مدخلات غير مقبولة: يفترض إدخال instanceof ${I.expected}، ولكن تم إدخال ${b}`;return`مدخلات غير مقبولة: يفترض إدخال ${_}، ولكن تم إدخال ${b}`}case"invalid_value":if(I.values.length===1)return`مدخلات غير مقبولة: يفترض إدخال ${q(I.values[0])}`;return`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return` أكبر من اللازم: يفترض أن تكون ${I.origin??"القيمة"} ${_} ${I.maximum.toString()} ${N.unit??"عنصر"}`;return`أكبر من اللازم: يفترض أن تكون ${I.origin??"القيمة"} ${_} ${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`أصغر من اللازم: يفترض لـ ${I.origin} أن يكون ${_} ${I.minimum.toString()} ${N.unit}`;return`أصغر من اللازم: يفترض لـ ${I.origin} أن يكون ${_} ${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`نَص غير مقبول: يجب أن يبدأ بـ "${I.prefix}"`;if(_.format==="ends_with")return`نَص غير مقبول: يجب أن ينتهي بـ "${_.suffix}"`;if(_.format==="includes")return`نَص غير مقبول: يجب أن يتضمَّن "${_.includes}"`;if(_.format==="regex")return`نَص غير مقبول: يجب أن يطابق النمط ${_.pattern}`;return`${D[_.format]??I.format} غير مقبول`}case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${I.divisor}`;case"unrecognized_keys":return`معرف${I.keys.length>1?"ات":""} غريب${I.keys.length>1?"ة":""}: ${O(I.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${I.origin}`;case"invalid_union":return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${I.origin}`;default:return"مدخل غير مقبول"}}};function e0(){return{localeError:K3()}}var O3=()=>{let $={string:{unit:"simvol",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"element",verb:"olmalıdır"},set:{unit:"element",verb:"olmalıdır"},map:{unit:"element",verb:"olmalıdır"}};function v(I){return $[I]??null}let D={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",credit_card:"kredit kartı nömrəsi",currency_code:"valyuta kodu",iban:"IBAN",jwt:"JWT",template_literal:"input"},g={nan:"NaN"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Yanlış dəyər: gözlənilən instanceof ${I.expected}, daxil olan ${b}`;return`Yanlış dəyər: gözlənilən ${_}, daxil olan ${b}`}case"invalid_value":if(I.values.length===1)return`Yanlış dəyər: gözlənilən ${q(I.values[0])}`;return`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`Çox böyük: gözlənilən ${I.origin??"dəyər"} ${_}${I.maximum.toString()} ${N.unit??"element"}`;return`Çox böyük: gözlənilən ${I.origin??"dəyər"} ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`Çox kiçik: gözlənilən ${I.origin} ${_}${I.minimum.toString()} ${N.unit}`;return`Çox kiçik: gözlənilən ${I.origin} ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Yanlış mətn: "${_.prefix}" ilə başlamalıdır`;if(_.format==="ends_with")return`Yanlış mətn: "${_.suffix}" ilə bitməlidir`;if(_.format==="includes")return`Yanlış mətn: "${_.includes}" daxil olmalıdır`;if(_.format==="regex")return`Yanlış mətn: ${_.pattern} şablonuna uyğun olmalıdır`;return`Yanlış ${D[_.format]??I.format}`}case"not_multiple_of":return`Yanlış ədəd: ${I.divisor} ilə bölünə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan açar${I.keys.length>1?"lar":""}: ${O(I.keys,", ")}`;case"invalid_key":return`${I.origin} daxilində yanlış açar`;case"invalid_union":return"Yanlış dəyər";case"invalid_element":return`${I.origin} daxilində yanlış dəyər`;default:return"Yanlış dəyər"}}};function s0(){return{localeError:O3()}}function PY($,v,D,g){let I=Math.abs($),_=I%10,N=I%100;if(N>=11&&N<=19)return g;if(_===1)return v;if(_>=2&&_<=4)return D;return g}var H3=()=>{let $={string:{unit:{one:"сімвал",few:"сімвалы",many:"сімвалаў"},verb:"мець"},array:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},set:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},map:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},file:{unit:{one:"байт",few:"байты",many:"байтаў"},verb:"мець"}};function v(I){return $[I]??null}let D={regex:"увод",email:"email адрас",url:"URL",emoji:"эмодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата і час",date:"ISO дата",time:"ISO час",duration:"ISO працягласць",ipv4:"IPv4 адрас",ipv6:"IPv6 адрас",mac:"MAC адрас",cidrv4:"IPv4 дыяпазон",cidrv6:"IPv6 дыяпазон",base64:"радок у фармаце base64",base64url:"радок у фармаце base64url",json_string:"JSON радок",e164:"нумар E.164",credit_card:"нумар крэдытнай карты",currency_code:"код валюты",iban:"IBAN",jwt:"JWT",template_literal:"увод"},g={nan:"NaN",number:"лік",array:"масіў"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Няправільны ўвод: чакаўся instanceof ${I.expected}, атрымана ${b}`;return`Няправільны ўвод: чакаўся ${_}, атрымана ${b}`}case"invalid_value":if(I.values.length===1)return`Няправільны ўвод: чакалася ${q(I.values[0])}`;return`Няправільны варыянт: чакаўся адзін з ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N){let b=Number(I.maximum),U=PY(b,N.unit.one,N.unit.few,N.unit.many);return`Занадта вялікі: чакалася, што ${I.origin??"значэнне"} павінна ${N.verb} ${_}${I.maximum.toString()} ${U}`}return`Занадта вялікі: чакалася, што ${I.origin??"значэнне"} павінна быць ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N){let b=Number(I.minimum),U=PY(b,N.unit.one,N.unit.few,N.unit.many);return`Занадта малы: чакалася, што ${I.origin} павінна ${N.verb} ${_}${I.minimum.toString()} ${U}`}return`Занадта малы: чакалася, што ${I.origin} павінна быць ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Няправільны радок: павінен пачынацца з "${_.prefix}"`;if(_.format==="ends_with")return`Няправільны радок: павінен заканчвацца на "${_.suffix}"`;if(_.format==="includes")return`Няправільны радок: павінен змяшчаць "${_.includes}"`;if(_.format==="regex")return`Няправільны радок: павінен адпавядаць шаблону ${_.pattern}`;return`Няправільны ${D[_.format]??I.format}`}case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${I.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${I.keys.length>1?"ключы":"ключ"}: ${O(I.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${I.origin}`;case"invalid_union":return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${I.origin}`;default:return"Няправільны ўвод"}}};function $X(){return{localeError:H3()}}var F3=()=>{let $={string:{unit:"символа",verb:"да съдържа"},file:{unit:"байта",verb:"да съдържа"},array:{unit:"елемента",verb:"да съдържа"},set:{unit:"елемента",verb:"да съдържа"},map:{unit:"елемента",verb:"да съдържа"}};function v(I){return $[I]??null}let D={regex:"вход",email:"имейл адрес",url:"URL",emoji:"емоджи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO време",date:"ISO дата",time:"ISO време",duration:"ISO продължителност",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",mac:"MAC адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"base64-кодиран низ",base64url:"base64url-кодиран низ",json_string:"JSON низ",e164:"E.164 номер",credit_card:"номер на кредитна карта",currency_code:"код на валута",iban:"IBAN",jwt:"JWT",template_literal:"вход"},g={nan:"NaN",number:"число",array:"масив"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Невалиден вход: очакван instanceof ${I.expected}, получен ${b}`;return`Невалиден вход: очакван ${_}, получен ${b}`}case"invalid_value":if(I.values.length===1)return`Невалиден вход: очакван ${q(I.values[0])}`;return`Невалидна опция: очаквано едно от ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`Твърде голямо: очаква се ${I.origin??"стойност"} да съдържа ${_}${I.maximum.toString()} ${N.unit??"елемента"}`;return`Твърде голямо: очаква се ${I.origin??"стойност"} да бъде ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`Твърде малко: очаква се ${I.origin} да съдържа ${_}${I.minimum.toString()} ${N.unit}`;return`Твърде малко: очаква се ${I.origin} да бъде ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Невалиден низ: трябва да започва с "${_.prefix}"`;if(_.format==="ends_with")return`Невалиден низ: трябва да завършва с "${_.suffix}"`;if(_.format==="includes")return`Невалиден низ: трябва да включва "${_.includes}"`;if(_.format==="regex")return`Невалиден низ: трябва да съвпада с ${_.pattern}`;let N="Невалиден";if(_.format==="emoji")N="Невалидно";if(_.format==="datetime")N="Невалидно";if(_.format==="date")N="Невалидна";if(_.format==="time")N="Невалидно";if(_.format==="duration")N="Невалидна";return`${N} ${D[_.format]??I.format}`}case"not_multiple_of":return`Невалидно число: трябва да бъде кратно на ${I.divisor}`;case"unrecognized_keys":return`Неразпознат${I.keys.length>1?"и":""} ключ${I.keys.length>1?"ове":""}: ${O(I.keys,", ")}`;case"invalid_key":return`Невалиден ключ в ${I.origin}`;case"invalid_union":return"Невалиден вход";case"invalid_element":return`Невалидна стойност в ${I.origin}`;default:return"Невалиден вход"}}};function vX(){return{localeError:F3()}}var P3=()=>{let $={string:{unit:"অক্ষর",verb:"থাকতে হবে"},file:{unit:"বাইট",verb:"থাকতে হবে"},array:{unit:"আইটেম",verb:"থাকতে হবে"},set:{unit:"আইটেম",verb:"থাকতে হবে"},map:{unit:"এন্ট্রি",verb:"থাকতে হবে"}};function v(I){return $[I]??null}let D={regex:"ইনপুট",email:"ইমেইল ঠিকানা",url:"URL",emoji:"ইমোজি",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO তারিখ ও সময়",date:"ISO তারিখ",time:"ISO সময়",duration:"ISO সময়কাল",ipv4:"IPv4 ঠিকানা",ipv6:"IPv6 ঠিকানা",mac:"MAC ঠিকানা",cidrv4:"IPv4 রেঞ্জ",cidrv6:"IPv6 রেঞ্জ",base64:"base64-এনকোডেড স্ট্রিং",base64url:"base64url-এনকোডেড স্ট্রিং",json_string:"JSON স্ট্রিং",e164:"E.164 নম্বর",credit_card:"ক্রেডিট কার্ড নম্বর",currency_code:"মুদ্রা কোড",iban:"IBAN",jwt:"JWT",template_literal:"ইনপুট"},g={nan:"NaN"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;return`অবৈধ ইনপুট: প্রত্যাশিত ${_}, প্রাপ্ত ${b}`}case"invalid_value":if(I.values.length===1)return`অবৈধ ইনপুট: প্রত্যাশিত ${q(I.values[0])}`;return`অবৈধ অপশন: ${O(I.values," | ")} এর মধ্যে একটি প্রত্যাশিত`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`অনেক বড়: ${I.origin??"মান"} ${_}${I.maximum.toString()} ${N.unit??"এলিমেন্ট"} হতে হবে`;return`অনেক বড়: ${I.origin??"মান"} ${_}${I.maximum.toString()} হতে হবে`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`অনেক ছোট: ${I.origin} ${_}${I.minimum.toString()} ${N.unit} হতে হবে`;return`অনেক ছোট: ${I.origin} ${_}${I.minimum.toString()} হতে হবে`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`অবৈধ স্ট্রিং: "${_.prefix}" দিয়ে শুরু হতে হবে`;if(_.format==="ends_with")return`অবৈধ স্ট্রিং: "${_.suffix}" দিয়ে শেষ হতে হবে`;if(_.format==="includes")return`অবৈধ স্ট্রিং: "${_.includes}" অন্তর্ভুক্ত থাকতে হবে`;if(_.format==="regex")return`অবৈধ স্ট্রিং: ${_.pattern} প্যাটার্ন মিলতে হবে`;return`অবৈধ ${D[_.format]??I.format}`}case"not_multiple_of":return`অবৈধ নম্বর: ${I.divisor} এর গুণিতক হতে হবে`;case"unrecognized_keys":return`অচেনা কী${I.keys.length>1?"গুলো":""}: ${O(I.keys,", ")}`;case"invalid_key":return`${I.origin} এ অবৈধ কী`;case"invalid_union":if(I.options&&Array.isArray(I.options)&&I.options.length>0)return`অবৈধ ডিসক্রিমিনেটর মান। প্রত্যাশিত ${I.options.map((N)=>`'${N}'`).join(" | ")}`;return"অবৈধ ইনপুট";case"invalid_element":return`${I.origin} এ অবৈধ মান`;default:return"অবৈধ ইনপুট"}}};function IX(){return{localeError:P3()}}var w3=()=>{let $={string:{unit:"caràcters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"},map:{unit:"elements",verb:"contenir"}};function v(I){return $[I]??null}let D={regex:"entrada",email:"adreça electrònica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adreça IPv4",ipv6:"adreça IPv6",mac:"adreça MAC",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"número E.164",credit_card:"número de targeta de crèdit",currency_code:"codi de moneda",iban:"IBAN",jwt:"JWT",template_literal:"entrada"},g={nan:"NaN"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Tipus invàlid: s'esperava instanceof ${I.expected}, s'ha rebut ${b}`;return`Tipus invàlid: s'esperava ${_}, s'ha rebut ${b}`}case"invalid_value":if(I.values.length===1)return`Valor invàlid: s'esperava ${q(I.values[0])}`;return`Opció invàlida: s'esperava una de ${O(I.values," o ")}`;case"too_big":{let _=I.inclusive?"com a màxim":"menys de",N=v(I.origin);if(N)return`Massa gran: s'esperava que ${I.origin??"el valor"} contingués ${_} ${I.maximum.toString()} ${N.unit??"elements"}`;return`Massa gran: s'esperava que ${I.origin??"el valor"} fos ${_} ${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?"com a mínim":"més de",N=v(I.origin);if(N)return`Massa petit: s'esperava que ${I.origin} contingués ${_} ${I.minimum.toString()} ${N.unit}`;return`Massa petit: s'esperava que ${I.origin} fos ${_} ${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Format invàlid: ha de començar amb "${_.prefix}"`;if(_.format==="ends_with")return`Format invàlid: ha d'acabar amb "${_.suffix}"`;if(_.format==="includes")return`Format invàlid: ha d'incloure "${_.includes}"`;if(_.format==="regex")return`Format invàlid: ha de coincidir amb el patró ${_.pattern}`;return`Format invàlid per a ${D[_.format]??I.format}`}case"not_multiple_of":return`Número invàlid: ha de ser múltiple de ${I.divisor}`;case"unrecognized_keys":return`Clau${I.keys.length>1?"s":""} no reconeguda${I.keys.length>1?"s":""}: ${O(I.keys,", ")}`;case"invalid_key":return`Clau invàlida a ${I.origin}`;case"invalid_union":return"Entrada invàlida";case"invalid_element":return`Element invàlid a ${I.origin}`;default:return"Entrada invàlida"}}};function _X(){return{localeError:w3()}}var q3=()=>{let $={string:{unit:"پیت",verb:"بێت"},file:{unit:"بایت",verb:"بێت"},array:{unit:"دانە",verb:"بێت"},set:{unit:"دانە",verb:"بێت"},map:{unit:"دانە",verb:"بێت"}};function v(I){return $[I]??null}let D={regex:"regex",email:"ئیمەیڵ",url:"بەستەر (URL)",emoji:"ئیمۆجی",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ڕێکەوت و کات",date:"ڕێکەوت",time:"کات",duration:"ماوە",ipv4:"ناونیشانی IPv4",ipv6:"ناونیشانی IPv6",mac:"ناونیشانی MAC",cidrv4:"مەودای IPv4",cidrv6:"مەودای IPv6",base64:"دەقی base64",base64url:"دەقی base64url",json_string:"دەقی JSON",e164:"ژمارەی E.164",credit_card:"ژمارەی کارتی کرێدیت",currency_code:"کۆدی دراو",iban:"IBAN",jwt:"JWT",template_literal:"تێکردە"},g={nan:"NaN",string:"نووسین",number:"ژمارە",boolean:"boolean",array:"array",object:"object",date:"ڕێکەوت",integer:"ژمارە",float:"ژمارە",null:"null",undefined:"undefined",function:"function",symbol:"symbol",unknown:"unknown",promise:"promise",void:"void",never:"never",map:"map",set:"set"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N,U=["ا","و","ۆ","وو","ە","ی","ێ"].some((W)=>b.endsWith(W))?"یە":"ە",J=/^[a-zA-Z]+$/.test(b);if(N==="null"||N==="undefined")return"داواکراوە";return`چاوەڕوانکراوە ${_} بێت، بەڵام ${b}${J?"":U}`}case"invalid_value":if(I.values.length===1)return`بەهاکە نادرووستە: چاوەڕوانکراوە ${q(I.values[0])} بێت`;return`هەڵبژاردەی نادروست: چاوەڕوانکراوە یەکێک بێت لە ${O(I.values,"|")}`;case"too_big":{let _=v(I.origin);if(_)return`پێویستە بە لایەنی زۆرەوە ${I.maximum.toString()} ${_.unit} ${_.verb}`;return`پێویستە بە لایەنی زۆرەوە ${I.maximum.toString()} بێت`}case"too_small":{let _=v(I.origin);if(_)return`پێویستە بە لایەنی کەمەوە ${I.minimum.toString()} ${_.unit} ${_.verb}`;return`پێویستە بە لایەنی کەمەوە ${I.minimum.toString()} بێت`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`دەقی نادروست: پێویستە دەستپێبکات بە "${_.prefix}"`;if(_.format==="ends_with")return`دەقی نادروست: پێویستە کۆتاییبێت بە "${_.suffix}"`;if(_.format==="includes")return`دەقی نادروست: پێویستە "${_.includes}" لەخۆبگرێت`;if(_.format==="regex")return`دەقی نادروست: پێویستە لەگەڵ پاتێرنی ${_.pattern} بگونجێت`;return`بەهای ${D[_.format]??I.format} نادروستە`}case"not_multiple_of":return`ژمارەی نادروست: دەبێت چەند هێندە بێت بۆ ${I.divisor}`;case"unrecognized_keys":return`کلیلی نەناسراو: ${O(I.keys,", ")}`;case"invalid_key":return`کلیلی نادروست لە ${I.origin}`;case"invalid_union":if(I.options&&Array.isArray(I.options)&&I.options.length>0)return`بەهای نەناسراو هەیە. بەهای چاوەڕوانکراو: ${I.options.map((N)=>`'${N}'`).join(" | ")}`;return"یەکگرتنی نادروست";case"invalid_element":return`${I.origin} بەهاکە نادروستە`;default:return"تێکردەی نادروست"}}};function DX(){return{localeError:q3()}}var M3=()=>{let $={string:{unit:"znaků",verb:"mít"},file:{unit:"bajtů",verb:"mít"},array:{unit:"prvků",verb:"mít"},set:{unit:"prvků",verb:"mít"},map:{unit:"prvků",verb:"mít"}};function v(I){return $[I]??null}let D={regex:"regulární výraz",email:"e-mailová adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a čas ve formátu ISO",date:"datum ve formátu ISO",time:"čas ve formátu ISO",duration:"doba trvání ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",mac:"MAC adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"řetězec zakódovaný ve formátu base64",base64url:"řetězec zakódovaný ve formátu base64url",json_string:"řetězec ve formátu JSON",e164:"číslo E.164",credit_card:"číslo kreditní karty",currency_code:"kód měny",iban:"IBAN",jwt:"JWT",template_literal:"vstup"},g={nan:"NaN",number:"číslo",string:"řetězec",function:"funkce",array:"pole"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Neplatný vstup: očekáváno instanceof ${I.expected}, obdrženo ${b}`;return`Neplatný vstup: očekáváno ${_}, obdrženo ${b}`}case"invalid_value":if(I.values.length===1)return`Neplatný vstup: očekáváno ${q(I.values[0])}`;return`Neplatná možnost: očekávána jedna z hodnot ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`Hodnota je příliš velká: ${I.origin??"hodnota"} musí mít ${_}${I.maximum.toString()} ${N.unit??"prvků"}`;return`Hodnota je příliš velká: ${I.origin??"hodnota"} musí být ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`Hodnota je příliš malá: ${I.origin??"hodnota"} musí mít ${_}${I.minimum.toString()} ${N.unit??"prvků"}`;return`Hodnota je příliš malá: ${I.origin??"hodnota"} musí být ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Neplatný řetězec: musí začínat na "${_.prefix}"`;if(_.format==="ends_with")return`Neplatný řetězec: musí končit na "${_.suffix}"`;if(_.format==="includes")return`Neplatný řetězec: musí obsahovat "${_.includes}"`;if(_.format==="regex")return`Neplatný řetězec: musí odpovídat vzoru ${_.pattern}`;return`Neplatný formát ${D[_.format]??I.format}`}case"not_multiple_of":return`Neplatné číslo: musí být násobkem ${I.divisor}`;case"unrecognized_keys":return`Neznámé klíče: ${O(I.keys,", ")}`;case"invalid_key":return`Neplatný klíč v ${I.origin}`;case"invalid_union":return"Neplatný vstup";case"invalid_element":return`Neplatná hodnota v ${I.origin}`;default:return"Neplatný vstup"}}};function gX(){return{localeError:M3()}}var T3=()=>{let $={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"},map:{unit:"elementer",verb:"indeholdt"}};function v(I){return $[I]??null}let D={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslæt",date:"ISO-dato",time:"ISO-klokkeslæt",duration:"ISO-varighed",ipv4:"IPv4-adresse",ipv6:"IPv6-adresse",mac:"MAC-adresse",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",credit_card:"kreditkortnummer",currency_code:"valutakode",iban:"IBAN",jwt:"JWT",template_literal:"input"},g={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"sæt",file:"fil"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Ugyldigt input: forventede instanceof ${I.expected}, fik ${b}`;return`Ugyldigt input: forventede ${_}, fik ${b}`}case"invalid_value":if(I.values.length===1)return`Ugyldig værdi: forventede ${q(I.values[0])}`;return`Ugyldigt valg: forventede en af følgende ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin),b=g[I.origin]??I.origin;if(N)return`For stor: forventede ${b??"value"} ${N.verb} ${_} ${I.maximum.toString()} ${N.unit??"elementer"}`;return`For stor: forventede ${b??"value"} havde ${_} ${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin),b=g[I.origin]??I.origin;if(N)return`For lille: forventede ${b} ${N.verb} ${_} ${I.minimum.toString()} ${N.unit}`;return`For lille: forventede ${b} havde ${_} ${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Ugyldig streng: skal starte med "${_.prefix}"`;if(_.format==="ends_with")return`Ugyldig streng: skal ende med "${_.suffix}"`;if(_.format==="includes")return`Ugyldig streng: skal indeholde "${_.includes}"`;if(_.format==="regex")return`Ugyldig streng: skal matche mønsteret ${_.pattern}`;return`Ugyldig ${D[_.format]??I.format}`}case"not_multiple_of":return`Ugyldigt tal: skal være deleligt med ${I.divisor}`;case"unrecognized_keys":return`${I.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${O(I.keys,", ")}`;case"invalid_key":return`Ugyldig nøgle i ${I.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig værdi i ${I.origin}`;default:return"Ugyldigt input"}}};function NX(){return{localeError:T3()}}var S3=()=>{let $={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"},map:{unit:"Elemente",verb:"zu haben"}};function v(I){return $[I]??null}let D={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",mac:"MAC-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",credit_card:"Kreditkartennummer",currency_code:"Währungscode",iban:"IBAN",jwt:"JWT",template_literal:"Eingabe"},g={nan:"NaN",number:"Zahl",array:"Array"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Ungültige Eingabe: erwartet instanceof ${I.expected}, erhalten ${b}`;return`Ungültige Eingabe: erwartet ${_}, erhalten ${b}`}case"invalid_value":if(I.values.length===1)return`Ungültige Eingabe: erwartet ${q(I.values[0])}`;return`Ungültige Option: erwartet eine von ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`Zu groß: erwartet, dass ${I.origin??"Wert"} ${_}${I.maximum.toString()} ${N.unit??"Elemente"} hat`;return`Zu groß: erwartet, dass ${I.origin??"Wert"} ${_}${I.maximum.toString()} ist`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`Zu klein: erwartet, dass ${I.origin} ${_}${I.minimum.toString()} ${N.unit} hat`;return`Zu klein: erwartet, dass ${I.origin} ${_}${I.minimum.toString()} ist`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Ungültiger String: muss mit "${_.prefix}" beginnen`;if(_.format==="ends_with")return`Ungültiger String: muss mit "${_.suffix}" enden`;if(_.format==="includes")return`Ungültiger String: muss "${_.includes}" enthalten`;if(_.format==="regex")return`Ungültiger String: muss dem Muster ${_.pattern} entsprechen`;return`Ungültig: ${D[_.format]??I.format}`}case"not_multiple_of":return`Ungültige Zahl: muss ein Vielfaches von ${I.divisor} sein`;case"unrecognized_keys":return`${I.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${O(I.keys,", ")}`;case"invalid_key":return`Ungültiger Schlüssel in ${I.origin}`;case"invalid_union":return"Ungültige Eingabe";case"invalid_element":return`Ungültiger Wert in ${I.origin}`;default:return"Ungültige Eingabe"}}};function bX(){return{localeError:S3()}}var A3=()=>{let $={string:{unit:"χαρακτήρες",verb:"να έχει"},file:{unit:"bytes",verb:"να έχει"},array:{unit:"στοιχεία",verb:"να έχει"},set:{unit:"στοιχεία",verb:"να έχει"},map:{unit:"καταχωρήσεις",verb:"να έχει"}};function v(I){return $[I]??null}let D={regex:"είσοδος",email:"διεύθυνση email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO ημερομηνία και ώρα",date:"ISO ημερομηνία",time:"ISO ώρα",duration:"ISO διάρκεια",ipv4:"διεύθυνση IPv4",ipv6:"διεύθυνση IPv6",mac:"διεύθυνση MAC",cidrv4:"εύρος IPv4",cidrv6:"εύρος IPv6",base64:"συμβολοσειρά κωδικοποιημένη σε base64",base64url:"συμβολοσειρά κωδικοποιημένη σε base64url",json_string:"συμβολοσειρά JSON",e164:"αριθμός E.164",credit_card:"αριθμός πιστωτικής κάρτας",currency_code:"κωδικός νομίσματος",iban:"IBAN",jwt:"JWT",template_literal:"είσοδος"},g={nan:"NaN"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(typeof I.expected==="string"&&/^[A-Z]/.test(I.expected))return`Μη έγκυρη είσοδος: αναμενόταν instanceof ${I.expected}, λήφθηκε ${b}`;return`Μη έγκυρη είσοδος: αναμενόταν ${_}, λήφθηκε ${b}`}case"invalid_value":if(I.values.length===1)return`Μη έγκυρη είσοδος: αναμενόταν ${q(I.values[0])}`;return`Μη έγκυρη επιλογή: αναμενόταν ένα από ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`Πολύ μεγάλο: αναμενόταν ${I.origin??"τιμή"} να έχει ${_}${I.maximum.toString()} ${N.unit??"στοιχεία"}`;return`Πολύ μεγάλο: αναμενόταν ${I.origin??"τιμή"} να είναι ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`Πολύ μικρό: αναμενόταν ${I.origin} να έχει ${_}${I.minimum.toString()} ${N.unit}`;return`Πολύ μικρό: αναμενόταν ${I.origin} να είναι ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Μη έγκυρη συμβολοσειρά: πρέπει να ξεκινά με "${_.prefix}"`;if(_.format==="ends_with")return`Μη έγκυρη συμβολοσειρά: πρέπει να τελειώνει με "${_.suffix}"`;if(_.format==="includes")return`Μη έγκυρη συμβολοσειρά: πρέπει να περιέχει "${_.includes}"`;if(_.format==="regex")return`Μη έγκυρη συμβολοσειρά: πρέπει να ταιριάζει με το μοτίβο ${_.pattern}`;return`Μη έγκυρο: ${D[_.format]??I.format}`}case"not_multiple_of":return`Μη έγκυρος αριθμός: πρέπει να είναι πολλαπλάσιο του ${I.divisor}`;case"unrecognized_keys":return`Άγνωστ${I.keys.length>1?"α":"ο"} κλειδ${I.keys.length>1?"ιά":"ί"}: ${O(I.keys,", ")}`;case"invalid_key":return`Μη έγκυρο κλειδί στο ${I.origin}`;case"invalid_union":return"Μη έγκυρη είσοδος";case"invalid_element":return`Μη έγκυρη τιμή στο ${I.origin}`;default:return"Μη έγκυρη είσοδος"}}};function UX(){return{localeError:A3()}}var Z3=()=>{let $={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function v(_){return $[_]??null}let D={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},g={nan:"NaN"};function I(_,N){if(_==="number"&&typeof N==="number"&&!Number.isFinite(N))return String(N);return g[_]??_}return(_)=>{switch(_.code){case"invalid_type":{let N=I(_.expected),b=M(_.input),U=I(b,_.input);return`Invalid input: expected ${N}, received ${U}`}case"invalid_value":if(_.values.length===1)return`Invalid input: expected ${q(_.values[0])}`;return`Invalid option: expected one of ${O(_.values,"|")}`;case"too_big":{let N=_.exact?"exactly ":_.inclusive?"<=":"<",b=v(_.origin);if(b)return`Too big: expected ${_.origin??"value"} to have ${N}${_.maximum.toString()} ${b.unit??"elements"}`;return`Too big: expected ${_.origin??"value"} to be ${N}${_.maximum.toString()}`}case"too_small":{let N=_.exact?"exactly ":_.inclusive?">=":">",b=v(_.origin);if(b)return`Too small: expected ${_.origin} to have ${N}${_.minimum.toString()} ${b.unit}`;return`Too small: expected ${_.origin} to be ${N}${_.minimum.toString()}`}case"invalid_format":{let N=_;if(N.format==="starts_with")return`Invalid string: must start with "${N.prefix}"`;if(N.format==="ends_with")return`Invalid string: must end with "${N.suffix}"`;if(N.format==="includes")return`Invalid string: must include "${N.includes}"`;if(N.format==="regex")return`Invalid string: must match pattern ${N.pattern}`;return`Invalid ${D[N.format]??_.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${_.divisor}`;case"unrecognized_keys":return`Unrecognized key${_.keys.length>1?"s":""}: ${O(_.keys,", ")}`;case"invalid_key":return`Invalid key in ${_.origin}`;case"invalid_union":if(_.options&&Array.isArray(_.options)&&_.options.length>0)return`Invalid discriminator value. Expected ${_.options.map((b)=>`'${b}'`).join(" | ")}`;if(_.inclusive===!1)return"Invalid input: more than one option matched";return"Invalid input";case"invalid_element":return`Invalid value in ${_.origin}`;default:return"Invalid input"}}};function a_(){return{localeError:Z3()}}var L3=()=>{let $={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"},map:{unit:"elementojn",verb:"havi"}};function v(I){return $[I]??null}let D={regex:"enigo",email:"retadreso",url:"URL",emoji:"emoĝio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-daŭro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",mac:"MAC-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",credit_card:"kreditkarta numero",currency_code:"valuta kodo",iban:"IBAN",jwt:"JWT",template_literal:"enigo"},g={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Nevalida enigo: atendiĝis instanceof ${I.expected}, riceviĝis ${b}`;return`Nevalida enigo: atendiĝis ${_}, riceviĝis ${b}`}case"invalid_value":if(I.values.length===1)return`Nevalida enigo: atendiĝis ${q(I.values[0])}`;return`Nevalida opcio: atendiĝis unu el ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`Tro granda: atendiĝis ke ${I.origin??"valoro"} havu ${_}${I.maximum.toString()} ${N.unit??"elementojn"}`;return`Tro granda: atendiĝis ke ${I.origin??"valoro"} havu ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`Tro malgranda: atendiĝis ke ${I.origin} havu ${_}${I.minimum.toString()} ${N.unit}`;return`Tro malgranda: atendiĝis ke ${I.origin} estu ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Nevalida karaktraro: devas komenciĝi per "${_.prefix}"`;if(_.format==="ends_with")return`Nevalida karaktraro: devas finiĝi per "${_.suffix}"`;if(_.format==="includes")return`Nevalida karaktraro: devas inkluzivi "${_.includes}"`;if(_.format==="regex")return`Nevalida karaktraro: devas kongrui kun la modelo ${_.pattern}`;return`Nevalida ${D[_.format]??I.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${I.divisor}`;case"unrecognized_keys":return`Nekonata${I.keys.length>1?"j":""} ŝlosilo${I.keys.length>1?"j":""}: ${O(I.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${I.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${I.origin}`;default:return"Nevalida enigo"}}};function JX(){return{localeError:L3()}}var E3=()=>{let $={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function v(I){return $[I]??null}let D={regex:"entrada",email:"dirección de correo electrónico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duración ISO",ipv4:"dirección IPv4",ipv6:"dirección IPv6",mac:"dirección MAC",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"número E.164",credit_card:"número de tarjeta de crédito",currency_code:"código de moneda",iban:"IBAN",jwt:"JWT",template_literal:"entrada"},g={nan:"NaN",string:"texto",number:"número",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"número grande",symbol:"símbolo",undefined:"indefinido",null:"nulo",function:"función",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeración",union:"unión",literal:"literal",promise:"promesa",void:"vacío",never:"nunca",unknown:"desconocido",any:"cualquiera"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Entrada inválida: se esperaba instanceof ${I.expected}, recibido ${b}`;return`Entrada inválida: se esperaba ${_}, recibido ${b}`}case"invalid_value":if(I.values.length===1)return`Entrada inválida: se esperaba ${q(I.values[0])}`;return`Opción inválida: se esperaba una de ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin),b=g[I.origin]??I.origin;if(N)return`Demasiado grande: se esperaba que ${b??"valor"} tuviera ${_}${I.maximum.toString()} ${N.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${b??"valor"} fuera ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin),b=g[I.origin]??I.origin;if(N)return`Demasiado pequeño: se esperaba que ${b} tuviera ${_}${I.minimum.toString()} ${N.unit}`;return`Demasiado pequeño: se esperaba que ${b} fuera ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Cadena inválida: debe comenzar con "${_.prefix}"`;if(_.format==="ends_with")return`Cadena inválida: debe terminar en "${_.suffix}"`;if(_.format==="includes")return`Cadena inválida: debe incluir "${_.includes}"`;if(_.format==="regex")return`Cadena inválida: debe coincidir con el patrón ${_.pattern}`;return`Inválido ${D[_.format]??I.format}`}case"not_multiple_of":return`Número inválido: debe ser múltiplo de ${I.divisor}`;case"unrecognized_keys":return`Llave${I.keys.length>1?"s":""} desconocida${I.keys.length>1?"s":""}: ${O(I.keys,", ")}`;case"invalid_key":return`Llave inválida en ${g[I.origin]??I.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido en ${g[I.origin]??I.origin}`;default:return"Entrada inválida"}}};function XX(){return{localeError:E3()}}var V3=()=>{let $={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"},map:{unit:"آیتم",verb:"داشته باشد"}};function v(I){return $[I]??null}let D={regex:"ورودی",email:"آدرس ایمیل",url:"URL",emoji:"ایموجی",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاریخ و زمان ایزو",date:"تاریخ ایزو",time:"زمان ایزو",duration:"مدت زمان ایزو",ipv4:"IPv4 آدرس",ipv6:"IPv6 آدرس",mac:"MAC آدرس",cidrv4:"IPv4 دامنه",cidrv6:"IPv6 دامنه",base64:"base64-encoded رشته",base64url:"base64url-encoded رشته",json_string:"JSON رشته",e164:"E.164 عدد",credit_card:"شماره کارت اعتباری",currency_code:"کد ارز",iban:"IBAN",jwt:"JWT",template_literal:"ورودی"},g={nan:"NaN",number:"عدد",array:"آرایه"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`ورودی نامعتبر: می‌بایست instanceof ${I.expected} می‌بود، ${b} دریافت شد`;return`ورودی نامعتبر: می‌بایست ${_} می‌بود، ${b} دریافت شد`}case"invalid_value":if(I.values.length===1)return`ورودی نامعتبر: می‌بایست ${q(I.values[0])} می‌بود`;return`گزینه نامعتبر: می‌بایست یکی از ${O(I.values,"|")} می‌بود`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`خیلی بزرگ: ${I.origin??"مقدار"} باید ${_}${I.maximum.toString()} ${N.unit??"عنصر"} باشد`;return`خیلی بزرگ: ${I.origin??"مقدار"} باید ${_}${I.maximum.toString()} باشد`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`خیلی کوچک: ${I.origin} باید ${_}${I.minimum.toString()} ${N.unit} باشد`;return`خیلی کوچک: ${I.origin} باید ${_}${I.minimum.toString()} باشد`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`رشته نامعتبر: باید با "${_.prefix}" شروع شود`;if(_.format==="ends_with")return`رشته نامعتبر: باید با "${_.suffix}" تمام شود`;if(_.format==="includes")return`رشته نامعتبر: باید شامل "${_.includes}" باشد`;if(_.format==="regex")return`رشته نامعتبر: باید با الگوی ${_.pattern} مطابقت داشته باشد`;return`${D[_.format]??I.format} نامعتبر`}case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${I.divisor} باشد`;case"unrecognized_keys":return`کلید${I.keys.length>1?"های":""} ناشناس: ${O(I.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${I.origin}`;case"invalid_union":return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${I.origin}`;default:return"ورودی نامعتبر"}}};function WX(){return{localeError:V3()}}var k3=()=>{let $={string:{unit:"merkkiä",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},map:{unit:"alkiota",subject:"kuvauksen"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"päivämäärän"}};function v(I){return $[I]??null}let D={regex:"säännöllinen lauseke",email:"sähköpostiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-päivämäärä",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",mac:"MAC-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",credit_card:"luottokortin numero",currency_code:"valuuttakoodi",iban:"IBAN",jwt:"JWT",template_literal:"templaattimerkkijono"},g={nan:"NaN"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Virheellinen tyyppi: odotettiin instanceof ${I.expected}, oli ${b}`;return`Virheellinen tyyppi: odotettiin ${_}, oli ${b}`}case"invalid_value":if(I.values.length===1)return`Virheellinen syöte: täytyy olla ${q(I.values[0])}`;return`Virheellinen valinta: täytyy olla yksi seuraavista: ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`Liian suuri: ${N.subject} täytyy olla ${_}${I.maximum.toString()} ${N.unit}`.trim();return`Liian suuri: arvon täytyy olla ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`Liian pieni: ${N.subject} täytyy olla ${_}${I.minimum.toString()} ${N.unit}`.trim();return`Liian pieni: arvon täytyy olla ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Virheellinen syöte: täytyy alkaa "${_.prefix}"`;if(_.format==="ends_with")return`Virheellinen syöte: täytyy loppua "${_.suffix}"`;if(_.format==="includes")return`Virheellinen syöte: täytyy sisältää "${_.includes}"`;if(_.format==="regex")return`Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${_.pattern}`;return`Virheellinen ${D[_.format]??I.format}`}case"not_multiple_of":return`Virheellinen luku: täytyy olla luvun ${I.divisor} monikerta`;case"unrecognized_keys":return`${I.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${O(I.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen syöte"}}};function QX(){return{localeError:k3()}}var R3=()=>{let $={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function v(I){return $[I]??null}let D={regex:"expression régulière",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",mac:"adresse MAC",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne de caractères encodée en base64",base64url:"chaîne de caractères encodée en base64url",json_string:"chaîne de caractères JSON",e164:"numéro au format E.164",credit_card:"numéro de carte de crédit",currency_code:"code de devise",iban:"IBAN",jwt:"JWT",template_literal:"entrée"},g={string:"chaîne de caractères",number:"nombre",int:"entier",boolean:"booléen",bigint:"grand entier",symbol:"symbole",undefined:"indéfini",null:"null",never:"jamais",void:"vide",date:"date",array:"tableau",object:"objet",tuple:"tuple",record:"record",map:"map",set:"ensemble",file:"fichier",nonoptional:"non optionnel",nan:"NaN",function:"fonction"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Entrée invalide : instance de ${I.expected} attendu, ${b} reçu`;return`Entrée invalide : ${_} attendu, ${b} reçu`}case"invalid_value":if(I.values.length===1)return`Entrée invalide : ${q(I.values[0])} attendu`;return`Option invalide : une valeur parmi ${O(I.values,"|")} attendue`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`Trop grand : ${g[I.origin]??"valeur"} doit ${N.verb} ${_}${I.maximum.toString()} ${N.unit??"élément(s)"}`;return`Trop grand : ${g[I.origin]??"valeur"} doit être ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`Trop petit : ${g[I.origin]??"valeur"} doit ${N.verb} ${_}${I.minimum.toString()} ${N.unit}`;return`Trop petit : ${g[I.origin]??"valeur"} doit être ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Chaîne de caractères invalide : doit commencer par "${_.prefix}"`;if(_.format==="ends_with")return`Chaîne de caractères invalide : doit se terminer par "${_.suffix}"`;if(_.format==="includes")return`Chaîne de caractères invalide : doit inclure "${_.includes}"`;if(_.format==="regex")return`Chaîne de caractères invalide : doit correspondre au motif ${_.pattern}`;return`${D[_.format]??I.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${I.divisor}`;case"unrecognized_keys":return`Clé${I.keys.length>1?"s":""} non reconnue${I.keys.length>1?"s":""} : ${O(I.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${I.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${I.origin}`;default:return"Entrée invalide"}}};function YX(){return{localeError:R3()}}var C3=()=>{let $={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"},map:{unit:"éléments",verb:"avoir"}};function v(I){return $[I]??null}let D={regex:"entrée",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",mac:"adresse MAC",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",credit_card:"numéro de carte de crédit",currency_code:"code de devise",iban:"IBAN",jwt:"JWT",template_literal:"entrée"},g={nan:"NaN"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Entrée invalide : attendu instanceof ${I.expected}, reçu ${b}`;return`Entrée invalide : attendu ${_}, reçu ${b}`}case"invalid_value":if(I.values.length===1)return`Entrée invalide : attendu ${q(I.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"≤":"<",N=v(I.origin);if(N)return`Trop grand : attendu que ${I.origin??"la valeur"} ait ${_}${I.maximum.toString()} ${N.unit}`;return`Trop grand : attendu que ${I.origin??"la valeur"} soit ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?"≥":">",N=v(I.origin);if(N)return`Trop petit : attendu que ${I.origin} ait ${_}${I.minimum.toString()} ${N.unit}`;return`Trop petit : attendu que ${I.origin} soit ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Chaîne invalide : doit commencer par "${_.prefix}"`;if(_.format==="ends_with")return`Chaîne invalide : doit se terminer par "${_.suffix}"`;if(_.format==="includes")return`Chaîne invalide : doit inclure "${_.includes}"`;if(_.format==="regex")return`Chaîne invalide : doit correspondre au motif ${_.pattern}`;return`${D[_.format]??I.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${I.divisor}`;case"unrecognized_keys":return`Clé${I.keys.length>1?"s":""} non reconnue${I.keys.length>1?"s":""} : ${O(I.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${I.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${I.origin}`;default:return"Entrée invalide"}}};function GX(){return{localeError:C3()}}var x3=()=>{let $={string:{unit:"અક્ષર",verb:"હોવા જોઈએ"},file:{unit:"બાયટ",verb:"હોવા જોઈએ"},array:{unit:"આઇટમ",verb:"હોવા જોઈએ"},set:{unit:"આઇટમ",verb:"હોવા જોઈએ"},map:{unit:"એન્ટ્રી",verb:"હોવા જોઈએ"}};function v(I){return $[I]??null}let D={regex:"ઇનપુટ",email:"ઈમેઇલ એડ્રેસ",url:"URL",emoji:"ઇમોજી",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO તારીખ અને સમય",date:"ISO તારીખ",time:"ISO સમય",duration:"ISO અવધિ",ipv4:"IPv4 એડ્રેસ",ipv6:"IPv6 એડ્રેસ",mac:"MAC એડ્રેસ",cidrv4:"IPv4 શ્રેણી",cidrv6:"IPv6 શ્રેણી",base64:"base64-એન્કોડેડ સ્ટ્રિંગ",base64url:"base64url-એન્કોડેડ સ્ટ્રિંગ",json_string:"JSON સ્ટ્રિંગ",e164:"E.164 નંબર",credit_card:"ક્રેડિટ કાર્ડ નંબર",currency_code:"ચલણ કોડ",iban:"IBAN",jwt:"JWT",template_literal:"ઇનપુટ"},g={nan:"NaN"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;return`અમાન્ય ઇનપુટ: અપેક્ષિત ${_}, પ્રાપ્ત ${b}`}case"invalid_value":if(I.values.length===1)return`અમાન્ય ઇનપુટ: અપેક્ષિત ${q(I.values[0])}`;return`અમાન્ય વિકલ્પ: ${O(I.values," | ")} માધ્યમથી એક અપેક્ષિત`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`ખૂબ મોટું: ${I.origin??"મૂલ્ય"} ${_}${I.maximum.toString()} ${N.unit??"એલિમેન્ટ"} હોવા જોઈએ`;return`ખૂબ મોટું: ${I.origin??"મૂલ્ય"} ${_}${I.maximum.toString()} હોવું જોઈએ`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`ખૂબ નાનું: ${I.origin} ${_}${I.minimum.toString()} ${N.unit} હોવા જોઈએ`;return`ખૂબ નાનું: ${I.origin} ${_}${I.minimum.toString()} હોવું જોઈએ`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`અમાન્ય સ્ટ્રિંગ: "${_.prefix}" થી શરૂ થવું જોઈએ`;if(_.format==="ends_with")return`અમાન્ય સ્ટ્રિંગ: "${_.suffix}" પર સમાપ્ત થવું જોઈએ`;if(_.format==="includes")return`અમાન્ય સ્ટ્રિંગ: "${_.includes}" શામેલ હોવું જોઈએ`;if(_.format==="regex")return`અમાન્ય સ્ટ્રિંગ: પેટર્ન ${_.pattern} સાથે મેળ ખાવું જોઈએ`;return`અમાન્ય ${D[_.format]??I.format}`}case"not_multiple_of":return`અમાન્ય નંબર: ${I.divisor} નો ગુણાંક હોવો જોઈએ`;case"unrecognized_keys":return`ઓળખી શકાતા નહીં તે કી${I.keys.length>1?"ઓ":""}: ${O(I.keys,", ")}`;case"invalid_key":return`${I.origin} માં અમાન્ય કી`;case"invalid_union":if(I.options&&Array.isArray(I.options)&&I.options.length>0)return`અમાન્ય ડિસ્ક્રિમિનેટર મૂલ્ય. અપેક્ષિત ${I.options.map((N)=>`'${N}'`).join(" | ")}`;return"અમાન્ય ઇનપુટ";case"invalid_element":return`${I.origin} માં અમાન્ય મૂલ્ય`;default:return"અમાન્ય ઇનપુટ"}}};function BX(){return{localeError:x3()}}var f3=()=>{let $={string:{label:"מחרוזת",gender:"f"},number:{label:"מספר",gender:"m"},boolean:{label:"ערך בוליאני",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"תאריך",gender:"m"},array:{label:"מערך",gender:"m"},object:{label:"אובייקט",gender:"m"},null:{label:"ערך ריק (null)",gender:"m"},undefined:{label:"ערך לא מוגדר (undefined)",gender:"m"},symbol:{label:"סימבול (Symbol)",gender:"m"},function:{label:"פונקציה",gender:"f"},map:{label:"מפה (Map)",gender:"f"},set:{label:"קבוצה (Set)",gender:"f"},file:{label:"קובץ",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"ערך לא ידוע",gender:"m"},value:{label:"ערך",gender:"m"}},v={string:{unit:"תווים",shortLabel:"קצר",longLabel:"ארוך"},file:{unit:"בייטים",shortLabel:"קטן",longLabel:"גדול"},array:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},set:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},number:{unit:"",shortLabel:"קטן",longLabel:"גדול"}},D=(J)=>J?$[J]:void 0,g=(J)=>{let W=D(J);if(W)return W.label;return J??$.unknown.label},I=(J)=>`ה${g(J)}`,_=(J)=>{return(D(J)?.gender??"m")==="f"?"צריכה להיות":"צריך להיות"},N=(J)=>{if(!J)return null;return v[J]??null},b={regex:{label:"קלט",gender:"m"},email:{label:"כתובת אימייל",gender:"f"},url:{label:"כתובת רשת",gender:"f"},emoji:{label:"אימוג'י",gender:"m"},uuid:{label:"UUID",gender:"m"},uuidv4:{label:"UUIDv4",gender:"m"},uuidv6:{label:"UUIDv6",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"תאריך וזמן ISO",gender:"m"},date:{label:"תאריך ISO",gender:"m"},time:{label:"זמן ISO",gender:"m"},duration:{label:"משך זמן ISO",gender:"m"},ipv4:{label:"כתובת IPv4",gender:"f"},ipv6:{label:"כתובת IPv6",gender:"f"},mac:{label:"כתובת MAC",gender:"f"},cidrv4:{label:"טווח IPv4",gender:"m"},cidrv6:{label:"טווח IPv6",gender:"m"},base64:{label:"מחרוזת בבסיס 64",gender:"f"},base64url:{label:"מחרוזת בבסיס 64 לכתובות רשת",gender:"f"},json_string:{label:"מחרוזת JSON",gender:"f"},e164:{label:"מספר E.164",gender:"m"},credit_card:{label:"מספר כרטיס אשראי",gender:"m"},currency_code:{label:"קוד מטבע",gender:"m"},iban:{label:"IBAN",gender:"m"},jwt:{label:"JWT",gender:"m"},template_literal:{label:"קלט",gender:"m"},ends_with:{label:"קלט",gender:"m"},includes:{label:"קלט",gender:"m"},lowercase:{label:"קלט",gender:"m"},starts_with:{label:"קלט",gender:"m"},uppercase:{label:"קלט",gender:"m"}},U={nan:"NaN"};return(J)=>{switch(J.code){case"invalid_type":{let W=J.expected,Y=U[W??""]??g(W),B=M(J.input),j=U[B]??$[B]?.label??B;if(/^[A-Z]/.test(J.expected))return`קלט לא תקין: צריך להיות instanceof ${J.expected}, התקבל ${j}`;return`קלט לא תקין: צריך להיות ${Y}, התקבל ${j}`}case"invalid_value":{if(J.values.length===1)return`ערך לא תקין: הערך חייב להיות ${q(J.values[0])}`;let W=J.values.map((j)=>q(j));if(J.values.length===2)return`ערך לא תקין: האפשרויות המתאימות הן ${W[0]} או ${W[1]}`;let Y=W[W.length-1];return`ערך לא תקין: האפשרויות המתאימות הן ${W.slice(0,-1).join(", ")} או ${Y}`}case"too_big":{let W=N(J.origin),Y=I(J.origin??"value");if(J.origin==="string")return`${W?.longLabel??"ארוך"} מדי: ${Y} צריכה להכיל ${J.maximum.toString()} ${W?.unit??""} ${J.inclusive?"או פחות":"לכל היותר"}`.trim();if(J.origin==="number"){let K=J.inclusive?`קטן או שווה ל-${J.maximum}`:`קטן מ-${J.maximum}`;return`גדול מדי: ${Y} צריך להיות ${K}`}if(J.origin==="array"||J.origin==="set"){let K=J.origin==="set"?"צריכה":"צריך",F=J.inclusive?`${J.maximum} ${W?.unit??""} או פחות`:`פחות מ-${J.maximum} ${W?.unit??""}`;return`גדול מדי: ${Y} ${K} להכיל ${F}`.trim()}let B=J.inclusive?"<=":"<",j=_(J.origin??"value");if(W?.unit)return`${W.longLabel} מדי: ${Y} ${j} ${B}${J.maximum.toString()} ${W.unit}`;return`${W?.longLabel??"גדול"} מדי: ${Y} ${j} ${B}${J.maximum.toString()}`}case"too_small":{let W=N(J.origin),Y=I(J.origin??"value");if(J.origin==="string")return`${W?.shortLabel??"קצר"} מדי: ${Y} צריכה להכיל ${J.minimum.toString()} ${W?.unit??""} ${J.inclusive?"או יותר":"לפחות"}`.trim();if(J.origin==="number"){let K=J.inclusive?`גדול או שווה ל-${J.minimum}`:`גדול מ-${J.minimum}`;return`קטן מדי: ${Y} צריך להיות ${K}`}if(J.origin==="array"||J.origin==="set"){let K=J.origin==="set"?"צריכה":"צריך";if(J.minimum===1&&J.inclusive){let T=J.origin==="set"?"לפחות פריט אחד":"לפחות פריט אחד";return`קטן מדי: ${Y} ${K} להכיל ${T}`}let F=J.inclusive?`${J.minimum} ${W?.unit??""} או יותר`:`יותר מ-${J.minimum} ${W?.unit??""}`;return`קטן מדי: ${Y} ${K} להכיל ${F}`.trim()}let B=J.inclusive?">=":">",j=_(J.origin??"value");if(W?.unit)return`${W.shortLabel} מדי: ${Y} ${j} ${B}${J.minimum.toString()} ${W.unit}`;return`${W?.shortLabel??"קטן"} מדי: ${Y} ${j} ${B}${J.minimum.toString()}`}case"invalid_format":{let W=J;if(W.format==="starts_with")return`המחרוזת חייבת להתחיל ב "${W.prefix}"`;if(W.format==="ends_with")return`המחרוזת חייבת להסתיים ב "${W.suffix}"`;if(W.format==="includes")return`המחרוזת חייבת לכלול "${W.includes}"`;if(W.format==="regex")return`המחרוזת חייבת להתאים לתבנית ${W.pattern}`;let Y=b[W.format],B=Y?.label??W.format,K=(Y?.gender??"m")==="f"?"תקינה":"תקין";return`${B} לא ${K}`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${J.divisor}`;case"unrecognized_keys":return`מפתח${J.keys.length>1?"ות":""} לא מזוה${J.keys.length>1?"ים":"ה"}: ${O(J.keys,", ")}`;case"invalid_key":return"שדה לא תקין באובייקט";case"invalid_union":return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${I(J.origin??"array")}`;default:return"קלט לא תקין"}}};function jX(){return{localeError:f3()}}var y3=()=>{let $={string:{unit:"अक्षर",verb:"रखने के लिए"},file:{unit:"बाइट्स",verb:"रखने के लिए"},array:{unit:"तत्व",verb:"रखने के लिए"},set:{unit:"तत्व",verb:"रखने के लिए"},map:{unit:"प्रविष्टियाँ",verb:"रखने के लिए"}};function v(I){return $[I]??null}let D={regex:"इनपुट",email:"ईमेल पता",url:"URL",emoji:"इमोजी",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO तिथि और समय",date:"ISO तिथि",time:"ISO समय",duration:"ISO अवधि",ipv4:"IPv4 पता",ipv6:"IPv6 पता",mac:"MAC पता",cidrv4:"IPv4 श्रेणी",cidrv6:"IPv6 श्रेणी",base64:"Base64-एन्कोडेड स्ट्रिंग",base64url:"Base64URL-एन्कोडेड स्ट्रिंग",json_string:"JSON स्ट्रिंग",e164:"E.164 संख्या",credit_card:"क्रेडिट कार्ड संख्या",currency_code:"मुद्रा कोड",iban:"IBAN",jwt:"JWT",template_literal:"इनपुट"},g={nan:"NaN"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;return`अमान्य इनपुट: अपेक्षित ${_}, प्राप्त ${b}`}case"invalid_value":if(I.values.length===1)return`अमान्य इनपुट: अपेक्षित ${q(I.values[0])}`;return`अमान्य विकल्प: अपेक्षित मानों में से एक ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`बहुत बड़ा: अपेक्षित था कि ${I.origin??"मान"} में ${_}${I.maximum} ${N.unit} हों`;return`बहुत बड़ा: अपेक्षित था कि ${I.origin??"मान"} ${_}${I.maximum} हो`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`बहुत छोटा: अपेक्षित था कि ${I.origin} में ${_}${I.minimum} ${N.unit} हों`;return`बहुत छोटा: अपेक्षित था कि ${I.origin} ${_}${I.minimum} हो`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`अमान्य स्ट्रिंग: "${_.prefix}" से शुरू होना चाहिए`;if(_.format==="ends_with")return`अमान्य स्ट्रिंग: "${_.suffix}" पर समाप्त होना चाहिए`;if(_.format==="includes")return`अमान्य स्ट्रिंग: इसमें "${_.includes}" शामिल होना चाहिए`;if(_.format==="regex")return`अमान्य स्ट्रिंग: पैटर्न ${_.pattern} से मेल खाना चाहिए`;return`अमान्य ${D[_.format]??I.format}`}case"not_multiple_of":return`अमान्य संख्या: यह ${I.divisor} का गुणज होना चाहिए`;case"unrecognized_keys":return`अपरिचित कुंजी${I.keys.length>1?"याँ":""}: ${O(I.keys,", ")}`;case"invalid_key":return`अमान्य कुंजी: ${I.origin} में`;case"invalid_union":if(I.options&&Array.isArray(I.options)&&I.options.length>0)return`अमान्य डिस्क्रिमिनेटर मान: अपेक्षित ${I.options.map((N)=>`'${N}'`).join(" | ")}`;return"अमान्य इनपुट";case"invalid_element":return`अमान्य मान: ${I.origin} में`;default:return"अमान्य इनपुट"}}};function zX(){return{localeError:y3()}}var u3=()=>{let $={string:{unit:"znakova",verb:"imati"},file:{unit:"bajtova",verb:"imati"},array:{unit:"stavki",verb:"imati"},set:{unit:"stavki",verb:"imati"}};function v(I){return $[I]??null}let D={regex:"unos",email:"email adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum i vrijeme",date:"ISO datum",time:"ISO vrijeme",duration:"ISO trajanje",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",mac:"MAC adresa",cidrv4:"IPv4 raspon",cidrv6:"IPv6 raspon",base64:"base64 kodirani tekst",base64url:"base64url kodirani tekst",json_string:"JSON tekst",e164:"E.164 broj",credit_card:"broj kreditne kartice",currency_code:"kod valute",iban:"IBAN",jwt:"JWT",template_literal:"unos"},g={nan:"NaN",string:"tekst",number:"broj",boolean:"boolean",array:"niz",object:"objekt",set:"skup",file:"datoteka",date:"datum",bigint:"bigint",symbol:"simbol",undefined:"undefined",null:"null",function:"funkcija",map:"mapa"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Neispravan unos: očekuje se instanceof ${I.expected}, a primljeno je ${b}`;return`Neispravan unos: očekuje se ${_}, a primljeno je ${b}`}case"invalid_value":if(I.values.length===1)return`Neispravna vrijednost: očekivano ${q(I.values[0])}`;return`Neispravna opcija: očekivano jedno od ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin),b=g[I.origin]??I.origin;if(N)return`Preveliko: očekivano da ${b??"vrijednost"} ima ${_}${I.maximum.toString()} ${N.unit??"elemenata"}`;return`Preveliko: očekivano da ${b??"vrijednost"} bude ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin),b=g[I.origin]??I.origin;if(N)return`Premalo: očekivano da ${b} ima ${_}${I.minimum.toString()} ${N.unit}`;return`Premalo: očekivano da ${b} bude ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Neispravan tekst: mora započinjati s "${_.prefix}"`;if(_.format==="ends_with")return`Neispravan tekst: mora završavati s "${_.suffix}"`;if(_.format==="includes")return`Neispravan tekst: mora sadržavati "${_.includes}"`;if(_.format==="regex")return`Neispravan tekst: mora odgovarati uzorku ${_.pattern}`;return`Neispravna ${D[_.format]??I.format}`}case"not_multiple_of":return`Neispravan broj: mora biti višekratnik od ${I.divisor}`;case"unrecognized_keys":return`Neprepoznat${I.keys.length>1?"i ključevi":" ključ"}: ${O(I.keys,", ")}`;case"invalid_key":return`Neispravan ključ u ${g[I.origin]??I.origin}`;case"invalid_union":return"Neispravan unos";case"invalid_element":return`Neispravna vrijednost u ${g[I.origin]??I.origin}`;default:return"Neispravan unos"}}};function KX(){return{localeError:u3()}}var i3=()=>{let $={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"},map:{unit:"elem",verb:"legyen"}};function v(I){return $[I]??null}let D={regex:"bemenet",email:"email cím",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO időbélyeg",date:"ISO dátum",time:"ISO idő",duration:"ISO időintervallum",ipv4:"IPv4 cím",ipv6:"IPv6 cím",mac:"MAC cím",cidrv4:"IPv4 tartomány",cidrv6:"IPv6 tartomány",base64:"base64-kódolt string",base64url:"base64url-kódolt string",json_string:"JSON string",e164:"E.164 szám",credit_card:"hitelkártyaszám",currency_code:"pénznemkód",iban:"IBAN",jwt:"JWT",template_literal:"bemenet"},g={nan:"NaN",number:"szám",array:"tömb"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Érvénytelen bemenet: a várt érték instanceof ${I.expected}, a kapott érték ${b}`;return`Érvénytelen bemenet: a várt érték ${_}, a kapott érték ${b}`}case"invalid_value":if(I.values.length===1)return`Érvénytelen bemenet: a várt érték ${q(I.values[0])}`;return`Érvénytelen opció: valamelyik érték várt ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`Túl nagy: ${I.origin??"érték"} mérete túl nagy ${_}${I.maximum.toString()} ${N.unit??"elem"}`;return`Túl nagy: a bemeneti érték ${I.origin??"érték"} túl nagy: ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`Túl kicsi: a bemeneti érték ${I.origin} mérete túl kicsi ${_}${I.minimum.toString()} ${N.unit}`;return`Túl kicsi: a bemeneti érték ${I.origin} túl kicsi ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Érvénytelen string: "${_.prefix}" értékkel kell kezdődnie`;if(_.format==="ends_with")return`Érvénytelen string: "${_.suffix}" értékkel kell végződnie`;if(_.format==="includes")return`Érvénytelen string: "${_.includes}" értéket kell tartalmaznia`;if(_.format==="regex")return`Érvénytelen string: ${_.pattern} mintának kell megfelelnie`;return`Érvénytelen ${D[_.format]??I.format}`}case"not_multiple_of":return`Érvénytelen szám: ${I.divisor} többszörösének kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${I.keys.length>1?"s":""}: ${O(I.keys,", ")}`;case"invalid_key":return`Érvénytelen kulcs ${I.origin}`;case"invalid_union":return"Érvénytelen bemenet";case"invalid_element":return`Érvénytelen érték: ${I.origin}`;default:return"Érvénytelen bemenet"}}};function OX(){return{localeError:i3()}}function wY($,v,D){return Math.abs($)===1?v:D}function A4($){if(!$)return"";let v=["ա","ե","ը","ի","ո","ու","օ"],D=$[$.length-1];return $+(v.includes(D)?"ն":"ը")}var l3=()=>{let $={string:{unit:{one:"նշան",many:"նշաններ"},verb:"ունենալ"},file:{unit:{one:"բայթ",many:"բայթեր"},verb:"ունենալ"},array:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"},set:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"},map:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"}};function v(I){return $[I]??null}let D={regex:"մուտք",email:"էլ. հասցե",url:"URL",emoji:"էմոջի",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO ամսաթիվ և ժամ",date:"ISO ամսաթիվ",time:"ISO ժամ",duration:"ISO տևողություն",ipv4:"IPv4 հասցե",ipv6:"IPv6 հասցե",mac:"MAC հասցե",cidrv4:"IPv4 միջակայք",cidrv6:"IPv6 միջակայք",base64:"base64 ձևաչափով տող",base64url:"base64url ձևաչափով տող",json_string:"JSON տող",e164:"E.164 համար",credit_card:"կրեդիտ քարտի համար",currency_code:"արժույթի կոդ",iban:"IBAN",jwt:"JWT",template_literal:"մուտք"},g={nan:"NaN",number:"թիվ",array:"զանգված"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Սխալ մուտքագրում․ սպասվում էր instanceof ${I.expected}, ստացվել է ${b}`;return`Սխալ մուտքագրում․ սպասվում էր ${_}, ստացվել է ${b}`}case"invalid_value":if(I.values.length===1)return`Սխալ մուտքագրում․ սպասվում էր ${q(I.values[1])}`;return`Սխալ տարբերակ․ սպասվում էր հետևյալներից մեկը՝ ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N){let b=Number(I.maximum),U=wY(b,N.unit.one,N.unit.many);return`Չափազանց մեծ արժեք․ սպասվում է, որ ${A4(I.origin??"արժեք")} կունենա ${_}${I.maximum.toString()} ${U}`}return`Չափազանց մեծ արժեք․ սպասվում է, որ ${A4(I.origin??"արժեք")} լինի ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N){let b=Number(I.minimum),U=wY(b,N.unit.one,N.unit.many);return`Չափազանց փոքր արժեք․ սպասվում է, որ ${A4(I.origin)} կունենա ${_}${I.minimum.toString()} ${U}`}return`Չափազանց փոքր արժեք․ սպասվում է, որ ${A4(I.origin)} լինի ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Սխալ տող․ պետք է սկսվի "${_.prefix}"-ով`;if(_.format==="ends_with")return`Սխալ տող․ պետք է ավարտվի "${_.suffix}"-ով`;if(_.format==="includes")return`Սխալ տող․ պետք է պարունակի "${_.includes}"`;if(_.format==="regex")return`Սխալ տող․ պետք է համապատասխանի ${_.pattern} ձևաչափին`;return`Սխալ ${D[_.format]??I.format}`}case"not_multiple_of":return`Սխալ թիվ․ պետք է բազմապատիկ լինի ${I.divisor}-ի`;case"unrecognized_keys":return`Չճանաչված բանալի${I.keys.length>1?"ներ":""}. ${O(I.keys,", ")}`;case"invalid_key":return`Սխալ բանալի ${A4(I.origin)}-ում`;case"invalid_union":return"Սխալ մուտքագրում";case"invalid_element":return`Սխալ արժեք ${A4(I.origin)}-ում`;default:return"Սխալ մուտքագրում"}}};function HX(){return{localeError:l3()}}var n3=()=>{let $={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"},map:{unit:"item",verb:"memiliki"}};function v(I){return $[I]??null}let D={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",mac:"alamat MAC",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",credit_card:"nomor kartu kredit",currency_code:"kode mata uang",iban:"IBAN",jwt:"JWT",template_literal:"input"},g={nan:"NaN"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Input tidak valid: diharapkan instanceof ${I.expected}, diterima ${b}`;return`Input tidak valid: diharapkan ${_}, diterima ${b}`}case"invalid_value":if(I.values.length===1)return`Input tidak valid: diharapkan ${q(I.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`Terlalu besar: diharapkan ${I.origin??"value"} memiliki ${_}${I.maximum.toString()} ${N.unit??"elemen"}`;return`Terlalu besar: diharapkan ${I.origin??"value"} menjadi ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`Terlalu kecil: diharapkan ${I.origin} memiliki ${_}${I.minimum.toString()} ${N.unit}`;return`Terlalu kecil: diharapkan ${I.origin} menjadi ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`String tidak valid: harus dimulai dengan "${_.prefix}"`;if(_.format==="ends_with")return`String tidak valid: harus berakhir dengan "${_.suffix}"`;if(_.format==="includes")return`String tidak valid: harus menyertakan "${_.includes}"`;if(_.format==="regex")return`String tidak valid: harus sesuai pola ${_.pattern}`;return`${D[_.format]??I.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${I.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${I.keys.length>1?"s":""}: ${O(I.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${I.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${I.origin}`;default:return"Input tidak valid"}}};function FX(){return{localeError:n3()}}var m3=()=>{let $={string:{unit:"stafi",verb:"að hafa"},file:{unit:"bæti",verb:"að hafa"},array:{unit:"hluti",verb:"að hafa"},set:{unit:"hluti",verb:"að hafa"},map:{unit:"hluti",verb:"að hafa"}};function v(I){return $[I]??null}let D={regex:"gildi",email:"netfang",url:"vefslóð",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og tími",date:"ISO dagsetning",time:"ISO tími",duration:"ISO tímalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 tölugildi",credit_card:"kreditkortanúmer",currency_code:"gjaldmiðilskóði",iban:"IBAN",jwt:"JWT",template_literal:"gildi"},g={nan:"NaN",number:"númer",array:"fylki"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Rangt gildi: Þú slóst inn ${b} þar sem á að vera instanceof ${I.expected}`;return`Rangt gildi: Þú slóst inn ${b} þar sem á að vera ${_}`}case"invalid_value":if(I.values.length===1)return`Rangt gildi: gert ráð fyrir ${q(I.values[0])}`;return`Ógilt val: má vera eitt af eftirfarandi ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`Of stórt: gert er ráð fyrir að ${I.origin??"gildi"} hafi ${_}${I.maximum.toString()} ${N.unit??"hluti"}`;return`Of stórt: gert er ráð fyrir að ${I.origin??"gildi"} sé ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`Of lítið: gert er ráð fyrir að ${I.origin} hafi ${_}${I.minimum.toString()} ${N.unit}`;return`Of lítið: gert er ráð fyrir að ${I.origin} sé ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Ógildur strengur: verður að byrja á "${_.prefix}"`;if(_.format==="ends_with")return`Ógildur strengur: verður að enda á "${_.suffix}"`;if(_.format==="includes")return`Ógildur strengur: verður að innihalda "${_.includes}"`;if(_.format==="regex")return`Ógildur strengur: verður að fylgja mynstri ${_.pattern}`;return`Rangt ${D[_.format]??I.format}`}case"not_multiple_of":return`Röng tala: verður að vera margfeldi af ${I.divisor}`;case"unrecognized_keys":return`Óþekkt ${I.keys.length>1?"ir lyklar":"ur lykill"}: ${O(I.keys,", ")}`;case"invalid_key":return`Rangur lykill í ${I.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi í ${I.origin}`;default:return"Rangt gildi"}}};function PX(){return{localeError:m3()}}var h3=()=>{let $={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"},map:{unit:"elementi",verb:"avere"}};function v(I){return $[I]??null}let D={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",mac:"indirizzo MAC",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",credit_card:"numero di carta di credito",currency_code:"codice valuta",iban:"IBAN",jwt:"JWT",template_literal:"input"},g={nan:"NaN",number:"numero",array:"vettore"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Input non valido: atteso instanceof ${I.expected}, ricevuto ${b}`;return`Input non valido: atteso ${_}, ricevuto ${b}`}case"invalid_value":if(I.values.length===1)return`Input non valido: atteso ${q(I.values[0])}`;return`Opzione non valida: atteso uno tra ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`Troppo grande: ${I.origin??"valore"} deve avere ${_}${I.maximum.toString()} ${N.unit??"elementi"}`;return`Troppo grande: ${I.origin??"valore"} deve essere ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`Troppo piccolo: ${I.origin} deve avere ${_}${I.minimum.toString()} ${N.unit}`;return`Troppo piccolo: ${I.origin} deve essere ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Stringa non valida: deve iniziare con "${_.prefix}"`;if(_.format==="ends_with")return`Stringa non valida: deve terminare con "${_.suffix}"`;if(_.format==="includes")return`Stringa non valida: deve includere "${_.includes}"`;if(_.format==="regex")return`Stringa non valida: deve corrispondere al pattern ${_.pattern}`;return`Input non valido: ${D[_.format]??I.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${I.divisor}`;case"unrecognized_keys":return`Chiav${I.keys.length>1?"i":"e"} non riconosciut${I.keys.length>1?"e":"a"}: ${O(I.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${I.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${I.origin}`;default:return"Input non valido"}}};function wX(){return{localeError:h3()}}var r3=()=>{let $={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"},map:{unit:"要素",verb:"である"}};function v(I){return $[I]??null}let D={regex:"入力値",email:"メールアドレス",url:"URL",emoji:"絵文字",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日時",date:"ISO日付",time:"ISO時刻",duration:"ISO期間",ipv4:"IPv4アドレス",ipv6:"IPv6アドレス",mac:"MACアドレス",cidrv4:"IPv4範囲",cidrv6:"IPv6範囲",base64:"base64エンコード文字列",base64url:"base64urlエンコード文字列",json_string:"JSON文字列",e164:"E.164番号",credit_card:"クレジットカード番号",currency_code:"通貨コード",iban:"IBAN",jwt:"JWT",template_literal:"入力値"},g={nan:"NaN",number:"数値",array:"配列"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`無効な入力: instanceof ${I.expected}が期待されましたが、${b}が入力されました`;return`無効な入力: ${_}が期待されましたが、${b}が入力されました`}case"invalid_value":if(I.values.length===1)return`無効な入力: ${q(I.values[0])}が期待されました`;return`無効な選択: ${O(I.values,"、")}のいずれかである必要があります`;case"too_big":{let _=I.inclusive?"以下である":"より小さい",N=v(I.origin);if(N)return`大きすぎる値: ${I.origin??"値"}は${I.maximum.toString()}${N.unit??"要素"}${_}必要があります`;return`大きすぎる値: ${I.origin??"値"}は${I.maximum.toString()}${_}必要があります`}case"too_small":{let _=I.inclusive?"以上である":"より大きい",N=v(I.origin);if(N)return`小さすぎる値: ${I.origin}は${I.minimum.toString()}${N.unit}${_}必要があります`;return`小さすぎる値: ${I.origin}は${I.minimum.toString()}${_}必要があります`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`無効な文字列: "${_.prefix}"で始まる必要があります`;if(_.format==="ends_with")return`無効な文字列: "${_.suffix}"で終わる必要があります`;if(_.format==="includes")return`無効な文字列: "${_.includes}"を含む必要があります`;if(_.format==="regex")return`無効な文字列: パターン${_.pattern}に一致する必要があります`;return`無効な${D[_.format]??I.format}`}case"not_multiple_of":return`無効な数値: ${I.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${I.keys.length>1?"群":""}: ${O(I.keys,"、")}`;case"invalid_key":return`${I.origin}内の無効なキー`;case"invalid_union":return"無効な入力";case"invalid_element":return`${I.origin}内の無効な値`;default:return"無効な入力"}}};function qX(){return{localeError:r3()}}var d3=()=>{let $={string:{unit:"სიმბოლო",verb:"უნდა შეიცავდეს"},file:{unit:"ბაიტი",verb:"უნდა შეიცავდეს"},array:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"},set:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"},map:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"}};function v(I){return $[I]??null}let D={regex:"შეყვანა",email:"ელ-ფოსტის მისამართი",url:"URL",emoji:"ემოჯი",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"თარიღი-დრო",date:"თარიღი",time:"დრო",duration:"ხანგრძლივობა",ipv4:"IPv4 მისამართი",ipv6:"IPv6 მისამართი",mac:"MAC მისამართი",cidrv4:"IPv4 დიაპაზონი",cidrv6:"IPv6 დიაპაზონი",base64:"base64-კოდირებული ველი",base64url:"base64url-კოდირებული ველი",json_string:"JSON ველი",e164:"E.164 ნომერი",credit_card:"საკრედიტო ბარათის ნომერი",currency_code:"ვალუტის კოდი",iban:"IBAN",jwt:"JWT",template_literal:"შეყვანა"},g={nan:"NaN",number:"რიცხვი",string:"ველი",boolean:"ბულეანი",function:"ფუნქცია",array:"მასივი"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`არასწორი შეყვანა: მოსალოდნელი instanceof ${I.expected}, მიღებული ${b}`;return`არასწორი შეყვანა: მოსალოდნელი ${_}, მიღებული ${b}`}case"invalid_value":if(I.values.length===1)return`არასწორი შეყვანა: მოსალოდნელი ${q(I.values[0])}`;return`არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${O(I.values,"|")}-დან`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`ზედმეტად დიდი: მოსალოდნელი ${I.origin??"მნიშვნელობა"} ${N.verb} ${_}${I.maximum.toString()} ${N.unit}`;return`ზედმეტად დიდი: მოსალოდნელი ${I.origin??"მნიშვნელობა"} იყოს ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`ზედმეტად პატარა: მოსალოდნელი ${I.origin} ${N.verb} ${_}${I.minimum.toString()} ${N.unit}`;return`ზედმეტად პატარა: მოსალოდნელი ${I.origin} იყოს ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`არასწორი ველი: უნდა იწყებოდეს "${_.prefix}"-ით`;if(_.format==="ends_with")return`არასწორი ველი: უნდა მთავრდებოდეს "${_.suffix}"-ით`;if(_.format==="includes")return`არასწორი ველი: უნდა შეიცავდეს "${_.includes}"-ს`;if(_.format==="regex")return`არასწორი ველი: უნდა შეესაბამებოდეს შაბლონს ${_.pattern}`;return`არასწორი ${D[_.format]??I.format}`}case"not_multiple_of":return`არასწორი რიცხვი: უნდა იყოს ${I.divisor}-ის ჯერადი`;case"unrecognized_keys":return`უცნობი გასაღებ${I.keys.length>1?"ები":"ი"}: ${O(I.keys,", ")}`;case"invalid_key":return`არასწორი გასაღები ${I.origin}-ში`;case"invalid_union":return"არასწორი შეყვანა";case"invalid_element":return`არასწორი მნიშვნელობა ${I.origin}-ში`;default:return"არასწორი შეყვანა"}}};function MX(){return{localeError:d3()}}var p3=()=>{let $={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"},map:{unit:"ធាតុ",verb:"គួរមាន"}};function v(I){return $[I]??null}let D={regex:"ទិន្នន័យបញ្ចូល",email:"អាសយដ្ឋានអ៊ីមែល",url:"URL",emoji:"សញ្ញាអារម្មណ៍",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"កាលបរិច្ឆេទ និងម៉ោង ISO",date:"កាលបរិច្ឆេទ ISO",time:"ម៉ោង ISO",duration:"រយៈពេល ISO",ipv4:"អាសយដ្ឋាន IPv4",ipv6:"អាសយដ្ឋាន IPv6",mac:"អាសយដ្ឋាន MAC",cidrv4:"ដែនអាសយដ្ឋាន IPv4",cidrv6:"ដែនអាសយដ្ឋាន IPv6",base64:"ខ្សែអក្សរអ៊ិកូដ base64",base64url:"ខ្សែអក្សរអ៊ិកូដ base64url",json_string:"ខ្សែអក្សរ JSON",e164:"លេខ E.164",credit_card:"លេខប័ណ្ណឥណទាន",currency_code:"កូដរូបិយប័ណ្ណ",iban:"IBAN",jwt:"JWT",template_literal:"ទិន្នន័យបញ្ចូល"},g={nan:"NaN",number:"លេខ",array:"អារេ (Array)",null:"គ្មានតម្លៃ (null)"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ instanceof ${I.expected} ប៉ុន្តែទទួលបាន ${b}`;return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${_} ប៉ុន្តែទទួលបាន ${b}`}case"invalid_value":if(I.values.length===1)return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${q(I.values[0])}`;return`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`ធំពេក៖ ត្រូវការ ${I.origin??"តម្លៃ"} ${_} ${I.maximum.toString()} ${N.unit??"ធាតុ"}`;return`ធំពេក៖ ត្រូវការ ${I.origin??"តម្លៃ"} ${_} ${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`តូចពេក៖ ត្រូវការ ${I.origin} ${_} ${I.minimum.toString()} ${N.unit}`;return`តូចពេក៖ ត្រូវការ ${I.origin} ${_} ${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${_.prefix}"`;if(_.format==="ends_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${_.suffix}"`;if(_.format==="includes")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${_.includes}"`;if(_.format==="regex")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${_.pattern}`;return`មិនត្រឹមត្រូវ៖ ${D[_.format]??I.format}`}case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${I.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${O(I.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${I.origin}`;case"invalid_union":return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${I.origin}`;default:return"ទិន្នន័យមិនត្រឹមត្រូវ"}}};function e_(){return{localeError:p3()}}function TX(){return e_()}var c3=()=>{let $={string:{unit:"ಅಕ್ಷರಗಳು",verb:"ಹೊಂದಲು"},file:{unit:"ಬೈಟ್‌ಗಳು",verb:"ಹೊಂದಲು"},array:{unit:"ವಸ್ತುಗಳು",verb:"ಹೊಂದಲು"},set:{unit:"ವಸ್ತುಗಳು",verb:"ಹೊಂದಲು"},map:{unit:"entries",verb:"ಹೊಂದಲು"}};function v(I){return $[I]??null}let D={regex:"ಇನ್ಪುಟ್",email:"email ವಿಳಾಸ",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO ದಿನಾಂಕದ ಸಮಯ",date:"ISO ದಿನಾಂಕ",time:"ISO ಸಮಯ",duration:"ISO ಅವಧಿ",ipv4:"IPv4 ವಿಳಾಸ",ipv6:"IPv6 ವಿಳಾಸ",mac:"MAC ವಿಳಾಸ",cidrv4:"IPv4 ವ್ಯಾಪ್ತಿಯ",cidrv6:"IPv6 ವ್ಯಾಪ್ತಿಯ",base64:"base64-encodedಸ್ಟ್ರಿಂಗ್",base64url:"base64url-encodedಸ್ಟ್ರಿಂಗ್",json_string:"JSONಸ್ಟ್ರಿಂಗ್",e164:"E.164 ಸಂಖ್ಯೆ",credit_card:"ಕ್ರೆಡಿಟ್ ಕಾರ್ಡ್ ಸಂಖ್ಯೆ",currency_code:"ಕರೆನ್ಸಿ ಕೋಡ್",iban:"IBAN",jwt:"JWT",template_literal:"ಇನ್ಪುಟ್"},g={nan:"NaN"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;return`ಅಮಾನ್ಯ ಇನ್‌ಪುಟ್: ನಿರೀಕ್ಷಿಸಲಾಗಿದೆ ${_}, ಸ್ವೀಕರಿಸಿದನು ${b}`}case"invalid_value":if(I.values.length===1)return`ಅಮಾನ್ಯ ಇನ್‌ಪುಟ್: ನಿರೀಕ್ಷಿಸಲಾಗಿದೆ ${q(I.values[0])}`;return`ಅಮಾನ್ಯ ಆಯ್ಕೆ: ಇವುಗಳಲ್ಲಿ ಒಂದನ್ನು ನಿರೀಕ್ಷಿಸಲಾಗಿದೆ ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`ತುಂಬಾ ದೊಡ್ಡದು: ನಿರೀಕ್ಷಿಸಲಾಗಿದೆ ${I.origin??"value"} ಹೊಂದಲು ${_}${I.maximum.toString()} ${N.unit??"ಅಂಶಗಳು"}`;return`ತುಂಬಾ ದೊಡ್ಡದು: ನಿರೀಕ್ಷಿಸಲಾಗಿದೆ ${I.origin??"value"} ಎಂದು ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`ತುಂಬಾ ಚಿಕ್ಕದು: ನಿರೀಕ್ಷಿಸಲಾಗಿದೆ ${I.origin} ಹೊಂದಲು ${_}${I.minimum.toString()} ${N.unit}`;return`ತುಂಬಾ ಚಿಕ್ಕದು: ನಿರೀಕ್ಷಿಸಲಾಗಿದೆ ${I.origin} ಎಂದು ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`ಅಮಾನ್ಯವಾದ ಸ್ಟ್ರಿಂಗ್: ಇದರೊಂದಿಗೆ ಪ್ರಾರಂಭಿಸಬೇಕು "${_.prefix}"`;if(_.format==="ends_with")return`ಅಮಾನ್ಯವಾದ ಸ್ಟ್ರಿಂಗ್: ಇದರೊಂದಿಗೆ ಕೊನೆಗೊಳ್ಳಬೇಕು "${_.suffix}"`;if(_.format==="includes")return`ಅಮಾನ್ಯ ಸ್ಟ್ರಿಂಗ್: ಒಳಗೊಂಡಿರಬೇಕು "${_.includes}"`;if(_.format==="regex")return`ಅಮಾನ್ಯವಾದ ಸ್ಟ್ರಿಂಗ್: ಮಾದರಿಗೆ ಹೊಂದಿಕೆಯಾಗಬೇಕು ${_.pattern}`;return`ಅಮಾನ್ಯ ${D[_.format]??I.format}`}case"not_multiple_of":return`ಅಮಾನ್ಯ ಸಂಖ್ಯೆ: ಬಹುಸಂಖ್ಯೆಯಾಗಿರಬೇಕು ${I.divisor}`;case"unrecognized_keys":return`ಗುರುತಿಸಲಾಗದ ಕೀ ${I.keys.length>1?"s":""}: ${O(I.keys,", ")}`;case"invalid_key":return`ಅಮಾನ್ಯವಾದ ಕೀ ಇನ್ ${I.origin}`;case"invalid_union":if(I.options&&Array.isArray(I.options)&&I.options.length>0)return`ಅಮಾನ್ಯ ತಾರತಮ್ಯ ಮೌಲ್ಯ. ನಿರೀಕ್ಷಿಸಲಾಗಿದೆ ${I.options.map((N)=>`'${N}'`).join(" | ")}`;return"ಅಮಾನ್ಯ ಇನ್‌ಪುಟ್";case"invalid_element":return`ರಲ್ಲಿ ಅಮಾನ್ಯ ಮೌಲ್ಯ ${I.origin}`;default:return"ಅಮಾನ್ಯ ಇನ್‌ಪುಟ್"}}};function SX(){return{localeError:c3()}}var t3=()=>{let $={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"},map:{unit:"개",verb:"to have"}};function v(I){return $[I]??null}let D={regex:"입력",email:"이메일 주소",url:"URL",emoji:"이모지",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 날짜시간",date:"ISO 날짜",time:"ISO 시간",duration:"ISO 기간",ipv4:"IPv4 주소",ipv6:"IPv6 주소",mac:"MAC 주소",cidrv4:"IPv4 범위",cidrv6:"IPv6 범위",base64:"base64 인코딩 문자열",base64url:"base64url 인코딩 문자열",json_string:"JSON 문자열",e164:"E.164 번호",credit_card:"신용카드 번호",currency_code:"통화 코드",iban:"IBAN",jwt:"JWT",template_literal:"입력"},g={nan:"NaN"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`잘못된 입력: 예상 타입은 instanceof ${I.expected}, 받은 타입은 ${b}입니다`;return`잘못된 입력: 예상 타입은 ${_}, 받은 타입은 ${b}입니다`}case"invalid_value":if(I.values.length===1)return`잘못된 입력: 값은 ${q(I.values[0])} 이어야 합니다`;return`잘못된 옵션: ${O(I.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{let _=I.inclusive?"이하":"미만",N=_==="미만"?"이어야 합니다":"여야 합니다",b=v(I.origin),U=b?.unit??"요소";if(b)return`${I.origin??"값"}이 너무 큽니다: ${I.maximum.toString()}${U} ${_}${N}`;return`${I.origin??"값"}이 너무 큽니다: ${I.maximum.toString()} ${_}${N}`}case"too_small":{let _=I.inclusive?"이상":"초과",N=_==="이상"?"이어야 합니다":"여야 합니다",b=v(I.origin),U=b?.unit??"요소";if(b)return`${I.origin??"값"}이 너무 작습니다: ${I.minimum.toString()}${U} ${_}${N}`;return`${I.origin??"값"}이 너무 작습니다: ${I.minimum.toString()} ${_}${N}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`잘못된 문자열: "${_.prefix}"(으)로 시작해야 합니다`;if(_.format==="ends_with")return`잘못된 문자열: "${_.suffix}"(으)로 끝나야 합니다`;if(_.format==="includes")return`잘못된 문자열: "${_.includes}"을(를) 포함해야 합니다`;if(_.format==="regex")return`잘못된 문자열: 정규식 ${_.pattern} 패턴과 일치해야 합니다`;return`잘못된 ${D[_.format]??I.format}`}case"not_multiple_of":return`잘못된 숫자: ${I.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${O(I.keys,", ")}`;case"invalid_key":return`잘못된 키: ${I.origin}`;case"invalid_union":return"잘못된 입력";case"invalid_element":return`잘못된 값: ${I.origin}`;default:return"잘못된 입력"}}};function AX(){return{localeError:t3()}}var s_=($)=>{return $.charAt(0).toUpperCase()+$.slice(1)};function qY($){let v=Math.abs($),D=v%10,g=v%100;if(g>=11&&g<=19||D===0)return"many";if(D===1)return"one";return"few"}var o3=()=>{let $={string:{unit:{one:"simbolis",few:"simboliai",many:"simbolių"},verb:{smaller:{inclusive:"turi būti ne ilgesnė kaip",notInclusive:"turi būti trumpesnė kaip"},bigger:{inclusive:"turi būti ne trumpesnė kaip",notInclusive:"turi būti ilgesnė kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"baitų"},verb:{smaller:{inclusive:"turi būti ne didesnis kaip",notInclusive:"turi būti mažesnis kaip"},bigger:{inclusive:"turi būti ne mažesnis kaip",notInclusive:"turi būti didesnis kaip"}}},array:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}},set:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}}};function v(I,_,N,b){let U=$[I]??null;if(U===null)return U;return{unit:U.unit[_],verb:U.verb[b][N?"inclusive":"notInclusive"]}}let D={regex:"įvestis",email:"el. pašto adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukmė",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",mac:"MAC adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 užkoduota eilutė",base64url:"base64url užkoduota eilutė",json_string:"JSON eilutė",e164:"E.164 numeris",credit_card:"kredito kortelės numeris",currency_code:"valiutos kodas",iban:"IBAN",jwt:"JWT",template_literal:"įvestis"},g={nan:"NaN",number:"skaičius",bigint:"sveikasis skaičius",string:"eilutė",boolean:"loginė reikšmė",undefined:"neapibrėžta reikšmė",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulinė reikšmė"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Gautas tipas ${b}, o tikėtasi - instanceof ${I.expected}`;return`Gautas tipas ${b}, o tikėtasi - ${_}`}case"invalid_value":if(I.values.length===1)return`Privalo būti ${q(I.values[0])}`;return`Privalo būti vienas iš ${O(I.values,"|")} pasirinkimų`;case"too_big":{let _=g[I.origin]??I.origin,N=v(I.origin,qY(Number(I.maximum)),I.inclusive??!1,"smaller");if(N?.verb)return`${s_(_??I.origin??"reikšmė")} ${N.verb} ${I.maximum.toString()} ${N.unit??"elementų"}`;let b=I.inclusive?"ne didesnis kaip":"mažesnis kaip";return`${s_(_??I.origin??"reikšmė")} turi būti ${b} ${I.maximum.toString()} ${N?.unit}`}case"too_small":{let _=g[I.origin]??I.origin,N=v(I.origin,qY(Number(I.minimum)),I.inclusive??!1,"bigger");if(N?.verb)return`${s_(_??I.origin??"reikšmė")} ${N.verb} ${I.minimum.toString()} ${N.unit??"elementų"}`;let b=I.inclusive?"ne mažesnis kaip":"didesnis kaip";return`${s_(_??I.origin??"reikšmė")} turi būti ${b} ${I.minimum.toString()} ${N?.unit}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Eilutė privalo prasidėti "${_.prefix}"`;if(_.format==="ends_with")return`Eilutė privalo pasibaigti "${_.suffix}"`;if(_.format==="includes")return`Eilutė privalo įtraukti "${_.includes}"`;if(_.format==="regex")return`Eilutė privalo atitikti ${_.pattern}`;return`Neteisingas ${D[_.format]??I.format}`}case"not_multiple_of":return`Skaičius privalo būti ${I.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpažint${I.keys.length>1?"i":"as"} rakt${I.keys.length>1?"ai":"as"}: ${O(I.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga įvestis";case"invalid_element":{let _=g[I.origin]??I.origin;return`${s_(_??I.origin??"reikšmė")} turi klaidingą įvestį`}default:return"Klaidinga įvestis"}}};function ZX(){return{localeError:o3()}}var a3=()=>{let $={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"},map:{unit:"ставки",verb:"да имаат"}};function v(I){return $[I]??null}let D={regex:"внес",email:"адреса на е-пошта",url:"URL",emoji:"емоџи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO датум и време",date:"ISO датум",time:"ISO време",duration:"ISO времетраење",ipv4:"IPv4 адреса",ipv6:"IPv6 адреса",mac:"MAC адреса",cidrv4:"IPv4 опсег",cidrv6:"IPv6 опсег",base64:"base64-енкодирана низа",base64url:"base64url-енкодирана низа",json_string:"JSON низа",e164:"E.164 број",credit_card:"број на кредитна картичка",currency_code:"код на валута",iban:"IBAN",jwt:"JWT",template_literal:"внес"},g={nan:"NaN",number:"број",array:"низа"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Грешен внес: се очекува instanceof ${I.expected}, примено ${b}`;return`Грешен внес: се очекува ${_}, примено ${b}`}case"invalid_value":if(I.values.length===1)return`Invalid input: expected ${q(I.values[0])}`;return`Грешана опција: се очекува една ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`Премногу голем: се очекува ${I.origin??"вредноста"} да има ${_}${I.maximum.toString()} ${N.unit??"елементи"}`;return`Премногу голем: се очекува ${I.origin??"вредноста"} да биде ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`Премногу мал: се очекува ${I.origin} да има ${_}${I.minimum.toString()} ${N.unit}`;return`Премногу мал: се очекува ${I.origin} да биде ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Неважечка низа: мора да започнува со "${_.prefix}"`;if(_.format==="ends_with")return`Неважечка низа: мора да завршува со "${_.suffix}"`;if(_.format==="includes")return`Неважечка низа: мора да вклучува "${_.includes}"`;if(_.format==="regex")return`Неважечка низа: мора да одгоара на патернот ${_.pattern}`;return`Invalid ${D[_.format]??I.format}`}case"not_multiple_of":return`Грешен број: мора да биде делив со ${I.divisor}`;case"unrecognized_keys":return`${I.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${O(I.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${I.origin}`;case"invalid_union":return"Грешен внес";case"invalid_element":return`Грешна вредност во ${I.origin}`;default:return"Грешен внес"}}};function LX(){return{localeError:a3()}}var e3=()=>{let $={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"},map:{unit:"elemen",verb:"mempunyai"}};function v(I){return $[I]??null}let D={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",mac:"alamat MAC",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",credit_card:"nombor kad kredit",currency_code:"kod mata wang",iban:"IBAN",jwt:"JWT",template_literal:"input"},g={nan:"NaN",number:"nombor"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Input tidak sah: dijangka instanceof ${I.expected}, diterima ${b}`;return`Input tidak sah: dijangka ${_}, diterima ${b}`}case"invalid_value":if(I.values.length===1)return`Input tidak sah: dijangka ${q(I.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`Terlalu besar: dijangka ${I.origin??"nilai"} ${N.verb} ${_}${I.maximum.toString()} ${N.unit??"elemen"}`;return`Terlalu besar: dijangka ${I.origin??"nilai"} adalah ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`Terlalu kecil: dijangka ${I.origin} ${N.verb} ${_}${I.minimum.toString()} ${N.unit}`;return`Terlalu kecil: dijangka ${I.origin} adalah ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`String tidak sah: mesti bermula dengan "${_.prefix}"`;if(_.format==="ends_with")return`String tidak sah: mesti berakhir dengan "${_.suffix}"`;if(_.format==="includes")return`String tidak sah: mesti mengandungi "${_.includes}"`;if(_.format==="regex")return`String tidak sah: mesti sepadan dengan corak ${_.pattern}`;return`${D[_.format]??I.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${I.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${O(I.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${I.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${I.origin}`;default:return"Input tidak sah"}}};function EX(){return{localeError:e3()}}var s3=()=>{let $={string:{unit:"अक्षर",verb:"हुनुपर्छ"},file:{unit:"बाइट",verb:"हुनुपर्छ"},array:{unit:"तत्व",verb:"हुनुपर्छ"},set:{unit:"तत्व",verb:"हुनुपर्छ"},map:{unit:"प्रविष्टि",verb:"हुनुपर्छ"}};function v(I){return $[I]??null}let D={regex:"इनपुट",email:"इमेल ठेगाना",url:"URL",emoji:"इमोजी",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO मिति र समय",date:"ISO मिति",time:"ISO समय",duration:"ISO अवधि",ipv4:"IPv4 ठेगाना",ipv6:"IPv6 ठेगाना",mac:"MAC ठेगाना",cidrv4:"IPv4 दायरा",cidrv6:"IPv6 दायरा",base64:"base64-इन्कोड गरिएको स्ट्रिङ",base64url:"base64url-इन्कोड गरिएको स्ट्रिङ",json_string:"JSON स्ट्रिङ",e164:"E.164 नम्बर",credit_card:"क्रेडिट कार्ड नम्बर",currency_code:"मुद्रा कोड",iban:"IBAN",jwt:"JWT",template_literal:"इनपुट"},g={nan:"NaN"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;return`अमान्य इनपुट: अपेक्षित ${_}, प्राप्त ${b}`}case"invalid_value":if(I.values.length===1)return`अमान्य इनपुट: अपेक्षित ${q(I.values[0])}`;return`अमान्य विकल्प: अपेक्षित मानहरू मध्ये एक ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`धेरै ठूलो: ${I.origin??"मान"} मा ${_}${I.maximum.toString()} ${N.unit} ${N.verb}`;return`धेरै ठूलो: ${I.origin??"मान"} ${_}${I.maximum.toString()} हुनुपर्छ`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`धेरै सानो: ${I.origin} मा ${_}${I.minimum.toString()} ${N.unit} ${N.verb}`;return`धेरै सानो: ${I.origin} ${_}${I.minimum.toString()} हुनुपर्छ`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`अमान्य स्ट्रिङ: "${_.prefix}" बाट सुरु हुनुपर्छ`;if(_.format==="ends_with")return`अमान्य स्ट्रिङ: "${_.suffix}" मा समाप्त हुनुपर्छ`;if(_.format==="includes")return`अमान्य स्ट्रिङ: "${_.includes}" समावेश हुनुपर्छ`;if(_.format==="regex")return`अमान्य स्ट्रिङ: ढाँचा ${_.pattern} सँग मेल खानुपर्छ`;return`अमान्य ${D[_.format]??I.format}`}case"not_multiple_of":return`अमान्य संख्या: ${I.divisor} को गुणज हुनुपर्छ`;case"unrecognized_keys":return`अपरिचित कुञ्जी${I.keys.length>1?"हरू":""}: ${O(I.keys,", ")}`;case"invalid_key":return`अमान्य कुञ्जी: ${I.origin} मा`;case"invalid_union":if(I.options&&Array.isArray(I.options)&&I.options.length>0)return`अमान्य डिस्क्रिमिनेटर मान: अपेक्षित ${I.options.map((N)=>`'${N}'`).join(" | ")}`;return"अमान्य इनपुट";case"invalid_element":return`अमान्य मान: ${I.origin} मा`;default:return"अमान्य इनपुट"}}};function VX(){return{localeError:s3()}}var $7=()=>{let $={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"},map:{unit:"elementen",verb:"heeft"}};function v(I){return $[I]??null}let D={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",mac:"MAC-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",credit_card:"creditcardnummer",currency_code:"valutacode",iban:"IBAN",jwt:"JWT",template_literal:"invoer"},g={nan:"NaN",number:"getal"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Ongeldige invoer: verwacht instanceof ${I.expected}, ontving ${b}`;return`Ongeldige invoer: verwacht ${_}, ontving ${b}`}case"invalid_value":if(I.values.length===1)return`Ongeldige invoer: verwacht ${q(I.values[0])}`;return`Ongeldige optie: verwacht één van ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin),b=I.origin==="date"?"laat":I.origin==="string"?"lang":"groot";if(N)return`Te ${b}: verwacht dat ${I.origin??"waarde"} ${_}${I.maximum.toString()} ${N.unit??"elementen"} ${N.verb}`;return`Te ${b}: verwacht dat ${I.origin??"waarde"} ${_}${I.maximum.toString()} is`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin),b=I.origin==="date"?"vroeg":I.origin==="string"?"kort":"klein";if(N)return`Te ${b}: verwacht dat ${I.origin} ${_}${I.minimum.toString()} ${N.unit} ${N.verb}`;return`Te ${b}: verwacht dat ${I.origin} ${_}${I.minimum.toString()} is`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Ongeldige tekst: moet met "${_.prefix}" beginnen`;if(_.format==="ends_with")return`Ongeldige tekst: moet op "${_.suffix}" eindigen`;if(_.format==="includes")return`Ongeldige tekst: moet "${_.includes}" bevatten`;if(_.format==="regex")return`Ongeldige tekst: moet overeenkomen met patroon ${_.pattern}`;return`Ongeldig: ${D[_.format]??I.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${I.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${I.keys.length>1?"s":""}: ${O(I.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${I.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${I.origin}`;default:return"Ongeldige invoer"}}};function kX(){return{localeError:$7()}}var v7=()=>{let $={string:{unit:"teikn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"element",verb:"å innehalde"},set:{unit:"element",verb:"å innehalde"},map:{unit:"element",verb:"å innehalde"}};function v(I){return $[I]??null}let D={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varigheit",ipv4:"IPv4-adresse",ipv6:"IPv6-adresse",mac:"MAC-adresse",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkoda streng",base64url:"base64url-enkoda streng",json_string:"JSON-streng",e164:"E.164-nummer",credit_card:"kredittkortnummer",currency_code:"valutakode",iban:"IBAN",jwt:"JWT",template_literal:"input"},g={nan:"NaN",number:"tal",array:"liste"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Ugyldig input: forventa instanceof ${I.expected}, fekk ${b}`;return`Ugyldig input: forventa ${_}, fekk ${b}`}case"invalid_value":if(I.values.length===1)return`Ugyldig verdi: forventa ${q(I.values[0])}`;return`Ugyldig val: forventa eitt av ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`For stor(t): forventa ${I.origin??"value"} til å ha ${_}${I.maximum.toString()} ${N.unit??"element"}`;return`For stor(t): forventa ${I.origin??"value"} til å ha ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`For lite(n): forventa ${I.origin} til å ha ${_}${I.minimum.toString()} ${N.unit}`;return`For lite(n): forventa ${I.origin} til å ha ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Ugyldig streng: må starte med "${_.prefix}"`;if(_.format==="ends_with")return`Ugyldig streng: må slutte med "${_.suffix}"`;if(_.format==="includes")return`Ugyldig streng: må innehalde "${_.includes}"`;if(_.format==="regex")return`Ugyldig streng: må matche mønsteret ${_.pattern}`;return`Ugyldig ${D[_.format]??I.format}`}case"not_multiple_of":return`Ugyldig tal: må vere eit multiplum av ${I.divisor}`;case"unrecognized_keys":return`${I.keys.length>1?"Ukjende nøklar":"Ukjend nøkkel"}: ${O(I.keys,", ")}`;case"invalid_key":return`Ugyldig nøkkel i ${I.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${I.origin}`;default:return"Ugyldig input"}}};function RX(){return{localeError:v7()}}var I7=()=>{let $={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"},map:{unit:"elementer",verb:"å inneholde"}};function v(I){return $[I]??null}let D={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-adresse",ipv6:"IPv6-adresse",mac:"MAC-adresse",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",credit_card:"kredittkortnummer",currency_code:"valutakode",iban:"IBAN",jwt:"JWT",template_literal:"input"},g={nan:"NaN",number:"tall",array:"liste"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Ugyldig input: forventet instanceof ${I.expected}, fikk ${b}`;return`Ugyldig input: forventet ${_}, fikk ${b}`}case"invalid_value":if(I.values.length===1)return`Ugyldig verdi: forventet ${q(I.values[0])}`;return`Ugyldig valg: forventet en av ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`For stor(t): forventet ${I.origin??"value"} til å ha ${_}${I.maximum.toString()} ${N.unit??"elementer"}`;return`For stor(t): forventet ${I.origin??"value"} til å ha ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`For lite(n): forventet ${I.origin} til å ha ${_}${I.minimum.toString()} ${N.unit}`;return`For lite(n): forventet ${I.origin} til å ha ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Ugyldig streng: må starte med "${_.prefix}"`;if(_.format==="ends_with")return`Ugyldig streng: må ende med "${_.suffix}"`;if(_.format==="includes")return`Ugyldig streng: må inneholde "${_.includes}"`;if(_.format==="regex")return`Ugyldig streng: må matche mønsteret ${_.pattern}`;return`Ugyldig ${D[_.format]??I.format}`}case"not_multiple_of":return`Ugyldig tall: må være et multiplum av ${I.divisor}`;case"unrecognized_keys":return`${I.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${O(I.keys,", ")}`;case"invalid_key":return`Ugyldig nøkkel i ${I.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${I.origin}`;default:return"Ugyldig input"}}};function CX(){return{localeError:I7()}}var _7=()=>{let $={string:{unit:"harf",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"unsur",verb:"olmalıdır"},set:{unit:"unsur",verb:"olmalıdır"},map:{unit:"unsur",verb:"olmalıdır"}};function v(I){return $[I]??null}let D={regex:"giren",email:"epostagâh",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO hengâmı",date:"ISO tarihi",time:"ISO zamanı",duration:"ISO müddeti",ipv4:"IPv4 nişânı",ipv6:"IPv6 nişânı",mac:"MAC nişânı",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-şifreli metin",base64url:"base64url-şifreli metin",json_string:"JSON metin",e164:"E.164 sayısı",credit_card:"i'tibâr kartı numarası",currency_code:"para birimi kodu",iban:"IBAN",jwt:"JWT",template_literal:"giren"},g={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Fâsit giren: umulan instanceof ${I.expected}, alınan ${b}`;return`Fâsit giren: umulan ${_}, alınan ${b}`}case"invalid_value":if(I.values.length===1)return`Fâsit giren: umulan ${q(I.values[0])}`;return`Fâsit tercih: mûteberler ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`Fazla büyük: ${I.origin??"value"}, ${_}${I.maximum.toString()} ${N.unit??"elements"} sahip olmalıydı.`;return`Fazla büyük: ${I.origin??"value"}, ${_}${I.maximum.toString()} olmalıydı.`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`Fazla küçük: ${I.origin}, ${_}${I.minimum.toString()} ${N.unit} sahip olmalıydı.`;return`Fazla küçük: ${I.origin}, ${_}${I.minimum.toString()} olmalıydı.`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Fâsit metin: "${_.prefix}" ile başlamalı.`;if(_.format==="ends_with")return`Fâsit metin: "${_.suffix}" ile bitmeli.`;if(_.format==="includes")return`Fâsit metin: "${_.includes}" ihtivâ etmeli.`;if(_.format==="regex")return`Fâsit metin: ${_.pattern} nakşına uymalı.`;return`Fâsit ${D[_.format]??I.format}`}case"not_multiple_of":return`Fâsit sayı: ${I.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${I.keys.length>1?"s":""}: ${O(I.keys,", ")}`;case"invalid_key":return`${I.origin} için tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${I.origin} için tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}}};function xX(){return{localeError:_7()}}var D7=()=>{let $={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"},map:{unit:"توکي",verb:"ولري"}};function v(I){return $[I]??null}let D={regex:"ورودي",email:"بریښنالیک",url:"یو آر ال",emoji:"ایموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"نیټه او وخت",date:"نېټه",time:"وخت",duration:"موده",ipv4:"د IPv4 پته",ipv6:"د IPv6 پته",mac:"د MAC پته",cidrv4:"د IPv4 ساحه",cidrv6:"د IPv6 ساحه",base64:"base64-encoded متن",base64url:"base64url-encoded متن",json_string:"JSON متن",e164:"د E.164 شمېره",credit_card:"د کریډیټ کارت شمیره",currency_code:"د اسعارو کوډ",iban:"IBAN",jwt:"JWT",template_literal:"ورودي"},g={nan:"NaN",number:"عدد",array:"ارې"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`ناسم ورودي: باید instanceof ${I.expected} وای, مګر ${b} ترلاسه شو`;return`ناسم ورودي: باید ${_} وای, مګر ${b} ترلاسه شو`}case"invalid_value":if(I.values.length===1)return`ناسم ورودي: باید ${q(I.values[0])} وای`;return`ناسم انتخاب: باید یو له ${O(I.values,"|")} څخه وای`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`ډیر لوی: ${I.origin??"ارزښت"} باید ${_}${I.maximum.toString()} ${N.unit??"عنصرونه"} ولري`;return`ډیر لوی: ${I.origin??"ارزښت"} باید ${_}${I.maximum.toString()} وي`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`ډیر کوچنی: ${I.origin} باید ${_}${I.minimum.toString()} ${N.unit} ولري`;return`ډیر کوچنی: ${I.origin} باید ${_}${I.minimum.toString()} وي`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`ناسم متن: باید د "${_.prefix}" سره پیل شي`;if(_.format==="ends_with")return`ناسم متن: باید د "${_.suffix}" سره پای ته ورسيږي`;if(_.format==="includes")return`ناسم متن: باید "${_.includes}" ولري`;if(_.format==="regex")return`ناسم متن: باید د ${_.pattern} سره مطابقت ولري`;return`${D[_.format]??I.format} ناسم دی`}case"not_multiple_of":return`ناسم عدد: باید د ${I.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${I.keys.length>1?"کلیډونه":"کلیډ"}: ${O(I.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${I.origin} کې`;case"invalid_union":return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${I.origin} کې`;default:return"ناسمه ورودي"}}};function fX(){return{localeError:D7()}}var g7=()=>{let $={string:{unit:"znaków",verb:"mieć"},file:{unit:"bajtów",verb:"mieć"},array:{unit:"elementów",verb:"mieć"},set:{unit:"elementów",verb:"mieć"},map:{unit:"elementów",verb:"mieć"}};function v(I){return $[I]??null}let D={regex:"wyrażenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",mac:"adres MAC",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ciąg znaków zakodowany w formacie base64",base64url:"ciąg znaków zakodowany w formacie base64url",json_string:"ciąg znaków w formacie JSON",e164:"liczba E.164",credit_card:"numer karty kredytowej",currency_code:"kod waluty",iban:"IBAN",jwt:"JWT",template_literal:"wejście"},g={nan:"NaN",number:"liczba",array:"tablica"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Nieprawidłowe dane wejściowe: oczekiwano instanceof ${I.expected}, otrzymano ${b}`;return`Nieprawidłowe dane wejściowe: oczekiwano ${_}, otrzymano ${b}`}case"invalid_value":if(I.values.length===1)return`Nieprawidłowe dane wejściowe: oczekiwano ${q(I.values[0])}`;return`Nieprawidłowa opcja: oczekiwano jednej z wartości ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`Za duża wartość: oczekiwano, że ${I.origin??"wartość"} będzie mieć ${_}${I.maximum.toString()} ${N.unit??"elementów"}`;return`Zbyt duż(y/a/e): oczekiwano, że ${I.origin??"wartość"} będzie wynosić ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`Za mała wartość: oczekiwano, że ${I.origin??"wartość"} będzie mieć ${_}${I.minimum.toString()} ${N.unit??"elementów"}`;return`Zbyt mał(y/a/e): oczekiwano, że ${I.origin??"wartość"} będzie wynosić ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Nieprawidłowy ciąg znaków: musi zaczynać się od "${_.prefix}"`;if(_.format==="ends_with")return`Nieprawidłowy ciąg znaków: musi kończyć się na "${_.suffix}"`;if(_.format==="includes")return`Nieprawidłowy ciąg znaków: musi zawierać "${_.includes}"`;if(_.format==="regex")return`Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${_.pattern}`;return`Nieprawidłow(y/a/e) ${D[_.format]??I.format}`}case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${I.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${I.keys.length>1?"s":""}: ${O(I.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${I.origin}`;case"invalid_union":return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${I.origin}`;default:return"Nieprawidłowe dane wejściowe"}}};function yX(){return{localeError:g7()}}var N7=()=>{let $={string:{unit:"caracteres"},file:{unit:"bytes"},array:{unit:"elementos"},set:{unit:"elementos"},map:{unit:"entradas"}};function v(N){return $[N]??null}let D={regex:"a entrada",email:"o endereço de e-mail",url:"o URL",emoji:"o emoji",uuid:"o UUID",uuidv4:"o UUIDv4",uuidv6:"o UUIDv6",nanoid:"o nanoid",guid:"o GUID",cuid:"o cuid",cuid2:"o cuid2",ulid:"o ULID",xid:"o XID",ksuid:"o KSUID",datetime:"a data e hora ISO",date:"a data ISO",time:"a hora ISO",duration:"a duração ISO",ipv4:"o endereço IPv4",ipv6:"o endereço IPv6",mac:"o endereço MAC",cidrv4:"o intervalo de endereços IPv4",cidrv6:"o intervalo de endereços IPv6",base64:"o texto codificado em base64",base64url:"o texto codificado em base64url",json_string:"o texto JSON",e164:"o número E.164",credit_card:"o número de cartão de crédito",currency_code:"o código de moeda",iban:"o IBAN",jwt:"o JWT",template_literal:"a entrada"},g={masculine:{definite:"o",indefinite:"um"},feminine:{definite:"a",indefinite:"uma"}},I={string:{name:"texto",articles:g.masculine},number:{name:"número",articles:g.masculine},int:{name:"número inteiro",articles:g.masculine},boolean:{name:"valor booleano",articles:g.masculine},bigint:{name:"número bigint",articles:g.masculine},symbol:{name:"símbolo",articles:g.masculine},undefined:{name:'valor "undefined"',articles:g.masculine},null:{name:'valor "nulo"',articles:g.masculine},never:{name:'valor "never"',articles:g.masculine},void:{name:'valor "void"',articles:g.masculine},date:{name:"data",articles:g.feminine},array:{name:"vetor",articles:g.masculine},object:{name:"objeto",articles:g.masculine},tuple:{name:"tuplo",articles:g.masculine},record:{name:"registo",articles:g.masculine},map:{name:"mapa",articles:g.masculine},set:{name:"conjunto",articles:g.masculine},file:{name:"ficheiro",articles:g.masculine},nonoptional:{name:"valor não opcional",articles:g.masculine},nan:{name:'valor "NaN"',articles:g.masculine},function:{name:"função",articles:g.feminine}};function _(N,b){let U=I[N]??{name:`valor "${N}"`,articles:g.masculine};return`${U.articles[b]} ${U.name}`}return(N)=>{switch(N.code){case"invalid_type":{let b=_(N.expected,"indefinite"),U=M(N.input),J=_(U,"indefinite");return`Entrada inválida: esperava ${b}, recebeu ${J}`}case"invalid_value":if(N.values.length===1)return`Entrada inválida: esperava ${q(N.values[0])}`;return`Opção inválida: esperava uma das seguintes opções: ${O(N.values,"|")}`;case"too_big":{let b=N.inclusive?"<=":"<",U=v(N.origin);if(U)return`Demasiado grande: esperava que ${_(N.origin,"definite")} tivesse ${b} ${N.maximum.toString()} ${U.unit??"elementos"}`;return`Demasiado grande: esperava que ${_(N.origin,"definite")} fosse ${b} ${N.maximum.toString()}`}case"too_small":{let b=N.inclusive?">=":">",U=v(N.origin);if(U)return`Demasiado pequeno: esperava que ${_(N.origin,"definite")} tivesse ${b} ${N.minimum.toString()} ${U.unit??"elementos"}`;return`Demasiado pequeno: esperava que ${_(N.origin,"definite")} fosse ${b} ${N.minimum.toString()}`}case"invalid_format":{let b=N;if(b.format==="starts_with")return`Texto inválido: deve começar por "${b.prefix}"`;if(b.format==="ends_with")return`Texto inválido: deve terminar em "${b.suffix}"`;if(b.format==="includes")return`Texto inválido: deve incluir "${b.includes}"`;if(b.format==="regex")return`Texto inválido: deve corresponder ao padrão ${b.pattern}`;return`Formato d${D[b.format]??N.format} inválido`}case"not_multiple_of":return`Número inválido: deve ser múltiplo de ${N.divisor}`;case"unrecognized_keys":{let b=N.keys.length>1?"s":"";return`Chave${b} inválida${b}: ${O(N.keys,", ")}`}case"invalid_key":return`Entrada inválida n${_(N.origin,"definite")}`;case"invalid_union":if(N.options&&Array.isArray(N.options)&&N.options.length>0)return`Valor de discriminação inválido. Esperava ${N.options.map((U)=>`'${U}'`).join(" | ")}`;return"Entrada inválida";case"invalid_element":return`Entrada inválida n${_(N.origin,"definite")}`;default:return"Entrada inválida"}}};function uX(){return{localeError:N7()}}var b7=()=>{let $={string:{unit:"caracteres"},file:{unit:"bytes"},array:{unit:"elementos"},set:{unit:"elementos"},map:{unit:"entradas"}};function v(N){return $[N]??null}let D={regex:"a entrada",email:"o endereço de e-mail",url:"o URL",emoji:"o emoji",uuid:"o UUID",uuidv4:"o UUIDv4",uuidv6:"o UUIDv6",nanoid:"o nanoid",guid:"o GUID",cuid:"o cuid",cuid2:"o cuid2",ulid:"o ULID",xid:"o XID",ksuid:"o KSUID",datetime:"a data e hora ISO",date:"a data ISO",time:"a hora ISO",duration:"a duração ISO",ipv4:"o endereço IPv4",ipv6:"o endereço IPv6",mac:"o endereço MAC",cidrv4:"a faixa de endereços IPv4",cidrv6:"a faixa de endereços IPv6",base64:"o texto codificado em base64",base64url:"o texto codificado em base64url",json_string:"o texto JSON",e164:"o número E.164",credit_card:"o número de cartão de crédito",currency_code:"o código de moeda",iban:"o IBAN",jwt:"o JWT",template_literal:"a entrada"},g={masculine:{definite:"o",indefinite:"um"},feminine:{definite:"a",indefinite:"uma"}},I={string:{name:"texto",articles:g.masculine},number:{name:"número",articles:g.masculine},int:{name:"número inteiro",articles:g.masculine},boolean:{name:"valor booleano",articles:g.masculine},bigint:{name:"número bigint",articles:g.masculine},symbol:{name:"símbolo",articles:g.masculine},undefined:{name:'valor "undefined"',articles:g.masculine},null:{name:'valor "nulo"',articles:g.masculine},never:{name:'valor "never"',articles:g.masculine},void:{name:'valor "void"',articles:g.masculine},date:{name:"data",articles:g.feminine},array:{name:"vetor",articles:g.masculine},object:{name:"objeto",articles:g.masculine},tuple:{name:"tupla",articles:g.feminine},record:{name:"registro",articles:g.masculine},map:{name:"mapa",articles:g.masculine},set:{name:"conjunto",articles:g.masculine},file:{name:"arquivo",articles:g.masculine},nonoptional:{name:"valor não opcional",articles:g.masculine},nan:{name:'valor "NaN"',articles:g.masculine},function:{name:"função",articles:g.feminine}};function _(N,b){let U=I[N]??{name:`valor "${N}"`,articles:g.masculine};return`${U.articles[b]} ${U.name}`}return(N)=>{switch(N.code){case"invalid_type":{let b=_(N.expected,"indefinite"),U=M(N.input),J=_(U,"indefinite");return`Entrada inválida: esperava ${b}, recebeu ${J}`}case"invalid_value":if(N.values.length===1)return`Entrada inválida: esperava ${q(N.values[0])}`;return`Opção inválida: esperava uma das seguintes opções: ${O(N.values,"|")}`;case"too_big":{let b=N.inclusive?"<=":"<",U=v(N.origin);if(U)return`Grande demais: esperava que ${_(N.origin,"definite")} tivesse ${b} ${N.maximum.toString()} ${U.unit??"elementos"}`;return`Grande demais: esperava que ${_(N.origin,"definite")} fosse ${b} ${N.maximum.toString()}`}case"too_small":{let b=N.inclusive?">=":">",U=v(N.origin);if(U)return`Pequeno demais: esperava que ${_(N.origin,"definite")} tivesse ${b} ${N.minimum.toString()} ${U.unit??"elementos"}`;return`Pequeno demais: esperava que ${_(N.origin,"definite")} fosse ${b} ${N.minimum.toString()}`}case"invalid_format":{let b=N;if(b.format==="starts_with")return`Texto inválido: deve começar com "${b.prefix}"`;if(b.format==="ends_with")return`Texto inválido: deve terminar com "${b.suffix}"`;if(b.format==="includes")return`Texto inválido: deve incluir "${b.includes}"`;if(b.format==="regex")return`Texto inválido: deve corresponder ao padrão ${b.pattern}`;return`Formato d${D[b.format]??N.format} inválido`}case"not_multiple_of":return`Número inválido: deve ser múltiplo de ${N.divisor}`;case"unrecognized_keys":{let b=N.keys.length>1?"s":"";return`Chave${b} inválida${b}: ${O(N.keys,", ")}`}case"invalid_key":return`Entrada inválida n${_(N.origin,"definite")}`;case"invalid_union":if(N.options&&Array.isArray(N.options)&&N.options.length>0)return`Valor de discriminação inválido. Esperava ${N.options.map((U)=>`'${U}'`).join(" | ")}`;return"Entrada inválida";case"invalid_element":return`Entrada inválida n${_(N.origin,"definite")}`;default:return"Entrada inválida"}}};function iX(){return{localeError:b7()}}var U7=()=>{let $={string:{unit:"caractere",verb:"să aibă"},file:{unit:"octeți",verb:"să aibă"},array:{unit:"elemente",verb:"să aibă"},set:{unit:"elemente",verb:"să aibă"},map:{unit:"intrări",verb:"să aibă"}};function v(I){return $[I]??null}let D={regex:"intrare",email:"adresă de email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"dată și oră ISO",date:"dată ISO",time:"oră ISO",duration:"durată ISO",ipv4:"adresă IPv4",ipv6:"adresă IPv6",mac:"adresă MAC",cidrv4:"interval IPv4",cidrv6:"interval IPv6",base64:"șir codat base64",base64url:"șir codat base64url",json_string:"șir JSON",e164:"număr E.164",credit_card:"număr de card de credit",currency_code:"cod valutar",iban:"IBAN",jwt:"JWT",template_literal:"intrare"},g={nan:"NaN",string:"șir",number:"număr",boolean:"boolean",function:"funcție",array:"matrice",object:"obiect",undefined:"nedefinit",symbol:"simbol",bigint:"număr mare",void:"void",never:"never",map:"hartă",set:"set"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;return`Intrare invalidă: așteptat ${_}, primit ${b}`}case"invalid_value":if(I.values.length===1)return`Intrare invalidă: așteptat ${q(I.values[0])}`;return`Opțiune invalidă: așteptat una dintre ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`Prea mare: așteptat ca ${I.origin??"valoarea"} ${N.verb} ${_}${I.maximum.toString()} ${N.unit??"elemente"}`;return`Prea mare: așteptat ca ${I.origin??"valoarea"} să fie ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`Prea mic: așteptat ca ${I.origin} ${N.verb} ${_}${I.minimum.toString()} ${N.unit}`;return`Prea mic: așteptat ca ${I.origin} să fie ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Șir invalid: trebuie să înceapă cu "${_.prefix}"`;if(_.format==="ends_with")return`Șir invalid: trebuie să se termine cu "${_.suffix}"`;if(_.format==="includes")return`Șir invalid: trebuie să includă "${_.includes}"`;if(_.format==="regex")return`Șir invalid: trebuie să se potrivească cu modelul ${_.pattern}`;return`Format invalid: ${D[_.format]??I.format}`}case"not_multiple_of":return`Număr invalid: trebuie să fie multiplu de ${I.divisor}`;case"unrecognized_keys":return`Chei nerecunoscute: ${O(I.keys,", ")}`;case"invalid_key":return`Cheie invalidă în ${I.origin}`;case"invalid_union":return"Intrare invalidă";case"invalid_element":return`Valoare invalidă în ${I.origin}`;default:return"Intrare invalidă"}}};function lX(){return{localeError:U7()}}function MY($,v,D,g){let I=Math.abs($),_=I%10,N=I%100;if(N>=11&&N<=19)return g;if(_===1)return v;if(_>=2&&_<=4)return D;return g}var J7=()=>{let $={string:{unit:{one:"символ",few:"символа",many:"символов"},verb:"иметь"},file:{unit:{one:"байт",few:"байта",many:"байт"},verb:"иметь"},array:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"},set:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"},map:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"}};function v(I){return $[I]??null}let D={regex:"ввод",email:"email адрес",url:"URL",emoji:"эмодзи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата и время",date:"ISO дата",time:"ISO время",duration:"ISO длительность",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",mac:"MAC адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"строка в формате base64",base64url:"строка в формате base64url",json_string:"JSON строка",e164:"номер E.164",credit_card:"номер кредитной карты",currency_code:"код валюты",iban:"IBAN",jwt:"JWT",template_literal:"ввод"},g={nan:"NaN",number:"число",array:"массив"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Неверный ввод: ожидалось instanceof ${I.expected}, получено ${b}`;return`Неверный ввод: ожидалось ${_}, получено ${b}`}case"invalid_value":if(I.values.length===1)return`Неверный ввод: ожидалось ${q(I.values[0])}`;return`Неверный вариант: ожидалось одно из ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N){let b=Number(I.maximum),U=MY(b,N.unit.one,N.unit.few,N.unit.many);return`Слишком большое значение: ожидалось, что ${I.origin??"значение"} будет иметь ${_}${I.maximum.toString()} ${U}`}return`Слишком большое значение: ожидалось, что ${I.origin??"значение"} будет ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N){let b=Number(I.minimum),U=MY(b,N.unit.one,N.unit.few,N.unit.many);return`Слишком маленькое значение: ожидалось, что ${I.origin} будет иметь ${_}${I.minimum.toString()} ${U}`}return`Слишком маленькое значение: ожидалось, что ${I.origin} будет ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Неверная строка: должна начинаться с "${_.prefix}"`;if(_.format==="ends_with")return`Неверная строка: должна заканчиваться на "${_.suffix}"`;if(_.format==="includes")return`Неверная строка: должна содержать "${_.includes}"`;if(_.format==="regex")return`Неверная строка: должна соответствовать шаблону ${_.pattern}`;return`Неверный ${D[_.format]??I.format}`}case"not_multiple_of":return`Неверное число: должно быть кратным ${I.divisor}`;case"unrecognized_keys":return`Нераспознанн${I.keys.length>1?"ые":"ый"} ключ${I.keys.length>1?"и":""}: ${O(I.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${I.origin}`;case"invalid_union":return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${I.origin}`;default:return"Неверные входные данные"}}};function nX(){return{localeError:J7()}}var X7=()=>{let $={string:{unit:"znakov",verb:"mať"},file:{unit:"bajtov",verb:"mať"},array:{unit:"prvkov",verb:"mať"},set:{unit:"prvkov",verb:"mať"},map:{unit:"položiek",verb:"mať"}};function v(I){return $[I]??null}let D={regex:"regulárny výraz",email:"e-mailová adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"dátum a čas vo formáte ISO",date:"dátum vo formáte ISO",time:"čas vo formáte ISO",duration:"doba trvania ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",mac:"MAC adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"reťazec zakódovaný vo formáte base64",base64url:"reťazec zakódovaný vo formáte base64url",json_string:"reťazec vo formáte JSON",e164:"číslo E.164",credit_card:"číslo kreditnej karty",currency_code:"kód meny",iban:"IBAN",jwt:"JWT",template_literal:"vstup"},g={nan:"NaN",number:"číslo",string:"reťazec",function:"funkcia",array:"pole"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Neplatný vstup: očakávané instanceof ${I.expected}, obdržané ${b}`;return`Neplatný vstup: očakávané ${_}, obdržané ${b}`}case"invalid_value":if(I.values.length===1)return`Neplatný vstup: očakávané ${q(I.values[0])}`;return`Neplatný vstup: očakávaná jedna z hodnôt ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`Hodnota je príliš veľká: ${I.origin??"hodnota"} musí mať ${_}${I.maximum.toString()} ${N.unit??"prvkov"}`;return`Hodnota je príliš veľká: ${I.origin??"hodnota"} musí byť ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`Hodnota je príliš malá: ${I.origin??"hodnota"} musí mať ${_}${I.minimum.toString()} ${N.unit??"prvkov"}`;return`Hodnota je príliš malá: ${I.origin??"hodnota"} musí byť ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Neplatný reťazec: musí začínať na "${_.prefix}"`;if(_.format==="ends_with")return`Neplatný reťazec: musí končiť na "${_.suffix}"`;if(_.format==="includes")return`Neplatný reťazec: musí obsahovať "${_.includes}"`;if(_.format==="regex")return`Neplatný reťazec: musí zodpovedať vzoru ${_.pattern}`;return`Neplatný formát ${D[_.format]??I.format}`}case"not_multiple_of":return`Neplatné číslo: musí byť násobkom ${I.divisor}`;case"unrecognized_keys":return`Neznáme klúče: ${O(I.keys,", ")}`;case"invalid_key":return`Neplatný klúč v ${I.origin}`;case"invalid_union":return"Neplatný vstup";case"invalid_element":return`Neplatná hodnota v ${I.origin}`;default:return"Neplatný vstup"}}};function mX(){return{localeError:X7()}}var W7=()=>{let $={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"},map:{unit:"elementov",verb:"imeti"}};function v(I){return $[I]??null}let D={regex:"vnos",email:"e-poštni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in čas",date:"ISO datum",time:"ISO čas",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",mac:"MAC naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 številka",credit_card:"številka kreditne kartice",currency_code:"koda valute",iban:"IBAN",jwt:"JWT",template_literal:"vnos"},g={nan:"NaN",number:"število",array:"tabela"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Neveljaven vnos: pričakovano instanceof ${I.expected}, prejeto ${b}`;return`Neveljaven vnos: pričakovano ${_}, prejeto ${b}`}case"invalid_value":if(I.values.length===1)return`Neveljaven vnos: pričakovano ${q(I.values[0])}`;return`Neveljavna možnost: pričakovano eno izmed ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`Preveliko: pričakovano, da bo ${I.origin??"vrednost"} imelo ${_}${I.maximum.toString()} ${N.unit??"elementov"}`;return`Preveliko: pričakovano, da bo ${I.origin??"vrednost"} ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`Premajhno: pričakovano, da bo ${I.origin} imelo ${_}${I.minimum.toString()} ${N.unit}`;return`Premajhno: pričakovano, da bo ${I.origin} ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Neveljaven niz: mora se začeti z "${_.prefix}"`;if(_.format==="ends_with")return`Neveljaven niz: mora se končati z "${_.suffix}"`;if(_.format==="includes")return`Neveljaven niz: mora vsebovati "${_.includes}"`;if(_.format==="regex")return`Neveljaven niz: mora ustrezati vzorcu ${_.pattern}`;return`Neveljaven ${D[_.format]??I.format}`}case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${I.divisor}`;case"unrecognized_keys":return`Neprepoznan${I.keys.length>1?"i ključi":" ključ"}: ${O(I.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${I.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${I.origin}`;default:return"Neveljaven vnos"}}};function hX(){return{localeError:W7()}}var Q7=()=>{let $={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att innehålla"},set:{unit:"objekt",verb:"att innehålla"},map:{unit:"objekt",verb:"att innehålla"}};function v(I){return $[I]??null}let D={regex:"reguljärt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-adress",ipv6:"IPv6-adress",mac:"MAC-adress",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad sträng",base64url:"base64url-kodad sträng",json_string:"JSON-sträng",e164:"E.164-nummer",credit_card:"kreditkortsnummer",currency_code:"valutakod",iban:"IBAN",jwt:"JWT",template_literal:"mall-literal"},g={nan:"NaN",number:"antal",array:"lista"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Ogiltig inmatning: förväntat instanceof ${I.expected}, fick ${b}`;return`Ogiltig inmatning: förväntat ${_}, fick ${b}`}case"invalid_value":if(I.values.length===1)return`Ogiltig inmatning: förväntat ${q(I.values[0])}`;return`Ogiltigt val: förväntade en av ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`För stor(t): förväntade ${I.origin??"värdet"} att ha ${_}${I.maximum.toString()} ${N.unit??"element"}`;return`För stor(t): förväntat ${I.origin??"värdet"} att ha ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`För lite(t): förväntade ${I.origin??"värdet"} att ha ${_}${I.minimum.toString()} ${N.unit}`;return`För lite(t): förväntade ${I.origin??"värdet"} att ha ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Ogiltig sträng: måste börja med "${_.prefix}"`;if(_.format==="ends_with")return`Ogiltig sträng: måste sluta med "${_.suffix}"`;if(_.format==="includes")return`Ogiltig sträng: måste innehålla "${_.includes}"`;if(_.format==="regex")return`Ogiltig sträng: måste matcha mönstret "${_.pattern}"`;return`Ogiltig(t) ${D[_.format]??I.format}`}case"not_multiple_of":return`Ogiltigt tal: måste vara en multipel av ${I.divisor}`;case"unrecognized_keys":return`${I.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${O(I.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${I.origin??"värdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt värde i ${I.origin??"värdet"}`;default:return"Ogiltig input"}}};function rX(){return{localeError:Q7()}}var Y7=()=>{let $={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},map:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}};function v(I){return $[I]??null}let D={regex:"உள்ளீடு",email:"மின்னஞ்சல் முகவரி",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO தேதி நேரம்",date:"ISO தேதி",time:"ISO நேரம்",duration:"ISO கால அளவு",ipv4:"IPv4 முகவரி",ipv6:"IPv6 முகவரி",mac:"MAC முகவரி",cidrv4:"IPv4 வரம்பு",cidrv6:"IPv6 வரம்பு",base64:"base64-encoded சரம்",base64url:"base64url-encoded சரம்",json_string:"JSON சரம்",e164:"E.164 எண்",credit_card:"கடன் அட்டை எண்",currency_code:"நாணயக் குறியீடு",iban:"IBAN",jwt:"JWT",template_literal:"input"},g={nan:"NaN",number:"எண்",array:"அணி",null:"வெறுமை"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது instanceof ${I.expected}, பெறப்பட்டது ${b}`;return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${_}, பெறப்பட்டது ${b}`}case"invalid_value":if(I.values.length===1)return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${q(I.values[0])}`;return`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${O(I.values,"|")} இல் ஒன்று`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${I.origin??"மதிப்பு"} ${_}${I.maximum.toString()} ${N.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`;return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${I.origin??"மதிப்பு"} ${_}${I.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${I.origin} ${_}${I.minimum.toString()} ${N.unit} ஆக இருக்க வேண்டும்`;return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${I.origin} ${_}${I.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`தவறான சரம்: "${_.prefix}" இல் தொடங்க வேண்டும்`;if(_.format==="ends_with")return`தவறான சரம்: "${_.suffix}" இல் முடிவடைய வேண்டும்`;if(_.format==="includes")return`தவறான சரம்: "${_.includes}" ஐ உள்ளடக்க வேண்டும்`;if(_.format==="regex")return`தவறான சரம்: ${_.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`;return`தவறான ${D[_.format]??I.format}`}case"not_multiple_of":return`தவறான எண்: ${I.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${I.keys.length>1?"கள்":""}: ${O(I.keys,", ")}`;case"invalid_key":return`${I.origin} இல் தவறான விசை`;case"invalid_union":return"தவறான உள்ளீடு";case"invalid_element":return`${I.origin} இல் தவறான மதிப்பு`;default:return"தவறான உள்ளீடு"}}};function dX(){return{localeError:Y7()}}var G7=()=>{let $={string:{unit:"аломат",verb:"дошта бошад"},file:{unit:"байт",verb:"дошта бошад"},array:{unit:"унсур",verb:"дошта бошад"},set:{unit:"унсур",verb:"дошта бошад"},map:{unit:"сабт",verb:"дошта бошад"}};function v(I){return $[I]??null}let D={regex:"вуруд",email:"суроғаи email",url:"URL",emoji:"эмоҷи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"санаву вақти ISO",date:"санаи ISO",time:"вақти ISO",duration:"давомнокии ISO",ipv4:"суроғаи IPv4",ipv6:"суроғаи IPv6",mac:"суроғаи MAC",cidrv4:"маҳдудаи IPv4",cidrv6:"маҳдудаи IPv6",base64:"сатри дар формати base64",base64url:"сатри дар формати base64url",json_string:"сатри JSON",e164:"рақами E.164",credit_card:"рақами корти кредитӣ",currency_code:"рамзи асъор",iban:"IBAN",jwt:"JWT",template_literal:"вуруд"},g={nan:"NaN",number:"рақам",string:"сатр",array:"массив",object:"объект",date:"сана"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;return`Вуруди нодуруст: ${_} интизор мерафт, ${b} гирифта шуд`}case"invalid_value":if(I.values.length===1)return`Вуруди нодуруст: ${q(I.values[0])} интизор мерафт`;return`Интихоби нодуруст: яке аз ${O(I.values,"|")} интизор мерафт`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`Хеле калон: ${I.origin??"қимат"} бояд ${_}${I.maximum.toString()} ${N.unit} ${N.verb}`;return`Хеле калон: ${I.origin??"қимат"} бояд ${_}${I.maximum.toString()} бошад`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`Хеле хурд: ${I.origin} бояд ${_}${I.minimum.toString()} ${N.unit} ${N.verb}`;return`Хеле хурд: ${I.origin} бояд ${_}${I.minimum.toString()} бошад`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Сатри нодуруст: бояд бо "${_.prefix}" оғоз шавад`;if(_.format==="ends_with")return`Сатри нодуруст: бояд бо "${_.suffix}" анҷом ёбад`;if(_.format==="includes")return`Сатри нодуруст: бояд "${_.includes}"-ро дар бар гирад`;if(_.format==="regex")return`Сатри нодуруст: бояд ба намунаи ${_.pattern} мувофиқат кунад`;return`${D[_.format]??I.format}-и нодуруст`}case"not_multiple_of":return`Рақами нодуруст: бояд ба ${I.divisor} бе бақия тақсим шавад`;case"unrecognized_keys":return`Калид${I.keys.length>1?"ҳои":"и"} номаълум: ${O(I.keys,", ")}`;case"invalid_key":return`Калиди нодуруст дар ${I.origin}`;case"invalid_union":if(I.options&&Array.isArray(I.options)&&I.options.length>0)return`Қимати нодурусти дискриминатор: ${I.options.map((N)=>`'${N}'`).join(" | ")} интизор мерафт`;return"Вуруди нодуруст";case"invalid_element":return`Қимати нодуруст дар ${I.origin}`;default:return"Вуруди нодуруст"}}};function pX(){return{localeError:G7()}}var B7=()=>{let $={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"},map:{unit:"รายการ",verb:"ควรมี"}};function v(I){return $[I]??null}let D={regex:"ข้อมูลที่ป้อน",email:"ที่อยู่อีเมล",url:"URL",emoji:"อิโมจิ",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"วันที่เวลาแบบ ISO",date:"วันที่แบบ ISO",time:"เวลาแบบ ISO",duration:"ช่วงเวลาแบบ ISO",ipv4:"ที่อยู่ IPv4",ipv6:"ที่อยู่ IPv6",mac:"ที่อยู่ MAC",cidrv4:"ช่วง IP แบบ IPv4",cidrv6:"ช่วง IP แบบ IPv6",base64:"ข้อความแบบ Base64",base64url:"ข้อความแบบ Base64 สำหรับ URL",json_string:"ข้อความแบบ JSON",e164:"เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",credit_card:"หมายเลขบัตรเครดิต",currency_code:"รหัสสกุลเงิน",iban:"IBAN",jwt:"โทเคน JWT",template_literal:"ข้อมูลที่ป้อน"},g={nan:"NaN",number:"ตัวเลข",array:"อาร์เรย์ (Array)",null:"ไม่มีค่า (null)"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น instanceof ${I.expected} แต่ได้รับ ${b}`;return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${_} แต่ได้รับ ${b}`}case"invalid_value":if(I.values.length===1)return`ค่าไม่ถูกต้อง: ควรเป็น ${q(I.values[0])}`;return`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"ไม่เกิน":"น้อยกว่า",N=v(I.origin);if(N)return`เกินกำหนด: ${I.origin??"ค่า"} ควรมี${_} ${I.maximum.toString()} ${N.unit??"รายการ"}`;return`เกินกำหนด: ${I.origin??"ค่า"} ควรมี${_} ${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?"อย่างน้อย":"มากกว่า",N=v(I.origin);if(N)return`น้อยกว่ากำหนด: ${I.origin} ควรมี${_} ${I.minimum.toString()} ${N.unit}`;return`น้อยกว่ากำหนด: ${I.origin} ควรมี${_} ${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${_.prefix}"`;if(_.format==="ends_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${_.suffix}"`;if(_.format==="includes")return`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${_.includes}" อยู่ในข้อความ`;if(_.format==="regex")return`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${_.pattern}`;return`รูปแบบไม่ถูกต้อง: ${D[_.format]??I.format}`}case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${I.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${O(I.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${I.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${I.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}}};function cX(){return{localeError:B7()}}var j7=()=>{let $={string:{unit:"simwol",verb:"bolmaly"},file:{unit:"baýt",verb:"bolmaly"},array:{unit:"elementler",verb:"bolmaly"},set:{unit:"elementler",verb:"bolmaly"},map:{unit:"elementler",verb:"bolmaly"}};function v(I){return $[I]??null}let D={regex:"giriş",email:"e-poçta salgysy",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO sene we wagt",date:"ISO sene",time:"ISO wagt",duration:"ISO wagt aralygy",ipv4:"IPv4 salgysy",ipv6:"IPv6 salgysy",mac:"MAC salgysy",cidrv4:"IPv4 aralygy",cidrv6:"IPv6 aralygy",base64:"base64 bilen şifrlenen setir",base64url:"base64url bilen şifrlenen setir",json_string:"JSON setiri",e164:"E.164 nomeri",credit_card:"kredit kartynyň nomeri",currency_code:"walýuta kody",iban:"IBAN",jwt:"JWT",template_literal:"şablon"},g={nan:"NaN"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;return`Nädogry baha: garaşylan ${_} ýerine ${b} alyndy`}case"invalid_value":if(I.values.length===1)return`Nädogry baha: ${q(I.values[0])} bolmaly`;return`Nädogry saýlaw: aşakdakylardan biri bolmaly: ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`Has uly: garaşylýan ${I.origin??"baha"} ${_} ${I.maximum.toString()} ${N.unit??"element"}`;return`Has uly: garaşylýan ${I.origin??"baha"} ${_} ${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`Has kiçi: garaşylýan ${I.origin} ${_} ${I.minimum.toString()} ${N.unit}`;return`Has kiçi: garaşylýan ${I.origin} ${_} ${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Nädogry setir: "${_.prefix}" bilen başlamaly`;if(_.format==="ends_with")return`Nädogry setir: "${_.suffix}" bilen gutarmaly`;if(_.format==="includes")return`Nädogry setir: "${_.includes}" saklamaly`;if(_.format==="regex")return`Nädogry setir: ${_.pattern} nusga laýyk bolmaly`;return`Nädogry ${D[_.format]??I.format}`}case"not_multiple_of":return`Nädogry san: ${I.divisor} bilen galyndysyz bölünmeli`;case"unrecognized_keys":return`Tanalmaýan açar${I.keys.length>1?"lar":""}: ${O(I.keys,", ")}`;case"invalid_key":return`${I.origin} içinde nädogry açar`;case"invalid_union":return"Nädogry baha";case"invalid_element":return`${I.origin} içinde nädogry baha`;default:return"Nädogry baha"}}};function tX(){return{localeError:j7()}}var z7=()=>{let $={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"},map:{unit:"öğe",verb:"olmalı"}};function v(I){return $[I]??null}let D={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO süre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",mac:"MAC adresi",cidrv4:"IPv4 aralığı",cidrv6:"IPv6 aralığı",base64:"base64 ile şifrelenmiş metin",base64url:"base64url ile şifrelenmiş metin",json_string:"JSON dizesi",e164:"E.164 sayısı",credit_card:"kredi kartı numarası",currency_code:"para birimi kodu",iban:"IBAN",jwt:"JWT",template_literal:"Şablon dizesi"},g={nan:"NaN"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Geçersiz değer: beklenen instanceof ${I.expected}, alınan ${b}`;return`Geçersiz değer: beklenen ${_}, alınan ${b}`}case"invalid_value":if(I.values.length===1)return`Geçersiz değer: beklenen ${q(I.values[0])}`;return`Geçersiz seçenek: aşağıdakilerden biri olmalı: ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`Çok büyük: beklenen ${I.origin??"değer"} ${_}${I.maximum.toString()} ${N.unit??"öğe"}`;return`Çok büyük: beklenen ${I.origin??"değer"} ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`Çok küçük: beklenen ${I.origin} ${_}${I.minimum.toString()} ${N.unit}`;return`Çok küçük: beklenen ${I.origin} ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Geçersiz metin: "${_.prefix}" ile başlamalı`;if(_.format==="ends_with")return`Geçersiz metin: "${_.suffix}" ile bitmeli`;if(_.format==="includes")return`Geçersiz metin: "${_.includes}" içermeli`;if(_.format==="regex")return`Geçersiz metin: ${_.pattern} desenine uymalı`;return`Geçersiz ${D[_.format]??I.format}`}case"not_multiple_of":return`Geçersiz sayı: ${I.divisor} ile tam bölünebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${I.keys.length>1?"lar":""}: ${O(I.keys,", ")}`;case"invalid_key":return`${I.origin} içinde geçersiz anahtar`;case"invalid_union":return"Geçersiz değer";case"invalid_element":return`${I.origin} içinde geçersiz değer`;default:return"Geçersiz değer"}}};function oX(){return{localeError:z7()}}var K7=()=>{let $={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"},map:{unit:"елементів",verb:"матиме"}};function v(I){return $[I]??null}let D={regex:"вхідні дані",email:"адреса електронної пошти",url:"URL",emoji:"емодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"дата та час ISO",date:"дата ISO",time:"час ISO",duration:"тривалість ISO",ipv4:"адреса IPv4",ipv6:"адреса IPv6",mac:"адреса MAC",cidrv4:"діапазон IPv4",cidrv6:"діапазон IPv6",base64:"рядок у кодуванні base64",base64url:"рядок у кодуванні base64url",json_string:"рядок JSON",e164:"номер E.164",credit_card:"номер кредитної картки",currency_code:"код валюти",iban:"IBAN",jwt:"JWT",template_literal:"вхідні дані"},g={nan:"NaN",number:"число",array:"масив"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Неправильні вхідні дані: очікується instanceof ${I.expected}, отримано ${b}`;return`Неправильні вхідні дані: очікується ${_}, отримано ${b}`}case"invalid_value":if(I.values.length===1)return`Неправильні вхідні дані: очікується ${q(I.values[0])}`;return`Неправильна опція: очікується одне з ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`Занадто велике: очікується, що ${I.origin??"значення"} ${N.verb} ${_}${I.maximum.toString()} ${N.unit??"елементів"}`;return`Занадто велике: очікується, що ${I.origin??"значення"} буде ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`Занадто мале: очікується, що ${I.origin} ${N.verb} ${_}${I.minimum.toString()} ${N.unit}`;return`Занадто мале: очікується, що ${I.origin} буде ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Неправильний рядок: повинен починатися з "${_.prefix}"`;if(_.format==="ends_with")return`Неправильний рядок: повинен закінчуватися на "${_.suffix}"`;if(_.format==="includes")return`Неправильний рядок: повинен містити "${_.includes}"`;if(_.format==="regex")return`Неправильний рядок: повинен відповідати шаблону ${_.pattern}`;return`Неправильний ${D[_.format]??I.format}`}case"not_multiple_of":return`Неправильне число: повинно бути кратним ${I.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${I.keys.length>1?"і":""}: ${O(I.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${I.origin}`;case"invalid_union":return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${I.origin}`;default:return"Неправильні вхідні дані"}}};function $D(){return{localeError:K7()}}function aX(){return $D()}var O7=()=>{let $={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"},map:{unit:"آئٹمز",verb:"ہونا"}};function v(I){return $[I]??null}let D={regex:"ان پٹ",email:"ای میل ایڈریس",url:"یو آر ایل",emoji:"ایموجی",uuid:"یو یو آئی ڈی",uuidv4:"یو یو آئی ڈی وی 4",uuidv6:"یو یو آئی ڈی وی 6",nanoid:"نینو آئی ڈی",guid:"جی یو آئی ڈی",cuid:"سی یو آئی ڈی",cuid2:"سی یو آئی ڈی 2",ulid:"یو ایل آئی ڈی",xid:"ایکس آئی ڈی",ksuid:"کے ایس یو آئی ڈی",datetime:"آئی ایس او ڈیٹ ٹائم",date:"آئی ایس او تاریخ",time:"آئی ایس او وقت",duration:"آئی ایس او مدت",ipv4:"آئی پی وی 4 ایڈریس",ipv6:"آئی پی وی 6 ایڈریس",mac:"ایم اے سی ایڈریس",cidrv4:"آئی پی وی 4 رینج",cidrv6:"آئی پی وی 6 رینج",base64:"بیس 64 ان کوڈڈ سٹرنگ",base64url:"بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",json_string:"جے ایس او این سٹرنگ",e164:"ای 164 نمبر",credit_card:"کریڈٹ کارڈ نمبر",currency_code:"کرنسی کوڈ",iban:"IBAN",jwt:"جے ڈبلیو ٹی",template_literal:"ان پٹ"},g={nan:"NaN",number:"نمبر",array:"آرے",null:"نل"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`غلط ان پٹ: instanceof ${I.expected} متوقع تھا، ${b} موصول ہوا`;return`غلط ان پٹ: ${_} متوقع تھا، ${b} موصول ہوا`}case"invalid_value":if(I.values.length===1)return`غلط ان پٹ: ${q(I.values[0])} متوقع تھا`;return`غلط آپشن: ${O(I.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`بہت بڑا: ${I.origin??"ویلیو"} کے ${_}${I.maximum.toString()} ${N.unit??"عناصر"} ہونے متوقع تھے`;return`بہت بڑا: ${I.origin??"ویلیو"} کا ${_}${I.maximum.toString()} ہونا متوقع تھا`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`بہت چھوٹا: ${I.origin} کے ${_}${I.minimum.toString()} ${N.unit} ہونے متوقع تھے`;return`بہت چھوٹا: ${I.origin} کا ${_}${I.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`غلط سٹرنگ: "${_.prefix}" سے شروع ہونا چاہیے`;if(_.format==="ends_with")return`غلط سٹرنگ: "${_.suffix}" پر ختم ہونا چاہیے`;if(_.format==="includes")return`غلط سٹرنگ: "${_.includes}" شامل ہونا چاہیے`;if(_.format==="regex")return`غلط سٹرنگ: پیٹرن ${_.pattern} سے میچ ہونا چاہیے`;return`غلط ${D[_.format]??I.format}`}case"not_multiple_of":return`غلط نمبر: ${I.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${I.keys.length>1?"ز":""}: ${O(I.keys,"، ")}`;case"invalid_key":return`${I.origin} میں غلط کی`;case"invalid_union":return"غلط ان پٹ";case"invalid_element":return`${I.origin} میں غلط ویلیو`;default:return"غلط ان پٹ"}}};function eX(){return{localeError:O7()}}var H7=()=>{let $={string:{unit:"belgi",verb:"bo‘lishi kerak"},file:{unit:"bayt",verb:"bo‘lishi kerak"},array:{unit:"element",verb:"bo‘lishi kerak"},set:{unit:"element",verb:"bo‘lishi kerak"},map:{unit:"yozuv",verb:"bo‘lishi kerak"}};function v(I){return $[I]??null}let D={regex:"kirish",email:"elektron pochta manzili",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO sana va vaqti",date:"ISO sana",time:"ISO vaqt",duration:"ISO davomiylik",ipv4:"IPv4 manzil",ipv6:"IPv6 manzil",mac:"MAC manzil",cidrv4:"IPv4 diapazon",cidrv6:"IPv6 diapazon",base64:"base64 kodlangan satr",base64url:"base64url kodlangan satr",json_string:"JSON satr",e164:"E.164 raqam",credit_card:"kredit karta raqami",currency_code:"valyuta kodi",iban:"IBAN",jwt:"JWT",template_literal:"kirish"},g={nan:"NaN",number:"raqam",array:"massiv"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Noto‘g‘ri kirish: kutilgan instanceof ${I.expected}, qabul qilingan ${b}`;return`Noto‘g‘ri kirish: kutilgan ${_}, qabul qilingan ${b}`}case"invalid_value":if(I.values.length===1)return`Noto‘g‘ri kirish: kutilgan ${q(I.values[0])}`;return`Noto‘g‘ri variant: quyidagilardan biri kutilgan ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`Juda katta: kutilgan ${I.origin??"qiymat"} ${_}${I.maximum.toString()} ${N.unit} ${N.verb}`;return`Juda katta: kutilgan ${I.origin??"qiymat"} ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`Juda kichik: kutilgan ${I.origin} ${_}${I.minimum.toString()} ${N.unit} ${N.verb}`;return`Juda kichik: kutilgan ${I.origin} ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Noto‘g‘ri satr: "${_.prefix}" bilan boshlanishi kerak`;if(_.format==="ends_with")return`Noto‘g‘ri satr: "${_.suffix}" bilan tugashi kerak`;if(_.format==="includes")return`Noto‘g‘ri satr: "${_.includes}" ni o‘z ichiga olishi kerak`;if(_.format==="regex")return`Noto‘g‘ri satr: ${_.pattern} shabloniga mos kelishi kerak`;return`Noto‘g‘ri ${D[_.format]??I.format}`}case"not_multiple_of":return`Noto‘g‘ri raqam: ${I.divisor} ning karralisi bo‘lishi kerak`;case"unrecognized_keys":return`Noma’lum kalit${I.keys.length>1?"lar":""}: ${O(I.keys,", ")}`;case"invalid_key":return`${I.origin} dagi kalit noto‘g‘ri`;case"invalid_union":return"Noto‘g‘ri kirish";case"invalid_element":return`${I.origin} da noto‘g‘ri qiymat`;default:return"Noto‘g‘ri kirish"}}};function sX(){return{localeError:H7()}}var F7=()=>{let $={string:{unit:"ký tự",verb:"có"},file:{unit:"byte",verb:"có"},array:{unit:"phần tử",verb:"có"},set:{unit:"phần tử",verb:"có"},map:{unit:"phần tử",verb:"có"}};function v(I){return $[I]??null}let D={regex:"đầu vào",email:"địa chỉ email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ngày giờ ISO",date:"ngày ISO",time:"giờ ISO",duration:"khoảng thời gian ISO",ipv4:"địa chỉ IPv4",ipv6:"địa chỉ IPv6",mac:"địa chỉ MAC",cidrv4:"dải IPv4",cidrv6:"dải IPv6",base64:"chuỗi mã hóa base64",base64url:"chuỗi mã hóa base64url",json_string:"chuỗi JSON",e164:"số E.164",credit_card:"số thẻ tín dụng",currency_code:"mã tiền tệ",iban:"IBAN",jwt:"JWT",template_literal:"đầu vào"},g={nan:"NaN",number:"số",array:"mảng"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Đầu vào không hợp lệ: mong đợi instanceof ${I.expected}, nhận được ${b}`;return`Đầu vào không hợp lệ: mong đợi ${_}, nhận được ${b}`}case"invalid_value":if(I.values.length===1)return`Đầu vào không hợp lệ: mong đợi ${q(I.values[0])}`;return`Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`Quá lớn: mong đợi ${I.origin??"giá trị"} ${N.verb} ${_}${I.maximum.toString()} ${N.unit??"phần tử"}`;return`Quá lớn: mong đợi ${I.origin??"giá trị"} ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`Quá nhỏ: mong đợi ${I.origin} ${N.verb} ${_}${I.minimum.toString()} ${N.unit}`;return`Quá nhỏ: mong đợi ${I.origin} ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Chuỗi không hợp lệ: phải bắt đầu bằng "${_.prefix}"`;if(_.format==="ends_with")return`Chuỗi không hợp lệ: phải kết thúc bằng "${_.suffix}"`;if(_.format==="includes")return`Chuỗi không hợp lệ: phải bao gồm "${_.includes}"`;if(_.format==="regex")return`Chuỗi không hợp lệ: phải khớp với mẫu ${_.pattern}`;return`${D[_.format]??I.format} không hợp lệ`}case"not_multiple_of":return`Số không hợp lệ: phải là bội số của ${I.divisor}`;case"unrecognized_keys":return`Khóa không được nhận dạng: ${O(I.keys,", ")}`;case"invalid_key":return`Khóa không hợp lệ trong ${I.origin}`;case"invalid_union":return"Đầu vào không hợp lệ";case"invalid_element":return`Giá trị không hợp lệ trong ${I.origin}`;default:return"Đầu vào không hợp lệ"}}};function $2(){return{localeError:F7()}}var P7=()=>{let $={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"},map:{unit:"项",verb:"包含"}};function v(I){return $[I]??null}let D={regex:"输入",email:"电子邮件",url:"URL",emoji:"表情符号",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日期时间",date:"ISO日期",time:"ISO时间",duration:"ISO时长",ipv4:"IPv4地址",ipv6:"IPv6地址",mac:"MAC地址",cidrv4:"IPv4网段",cidrv6:"IPv6网段",base64:"base64编码字符串",base64url:"base64url编码字符串",json_string:"JSON字符串",e164:"E.164号码",credit_card:"信用卡号",currency_code:"货币代码",iban:"IBAN",jwt:"JWT",template_literal:"输入"},g={nan:"NaN",number:"数字",array:"数组",null:"空值(null)"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`无效输入:期望 instanceof ${I.expected},实际接收 ${b}`;return`无效输入:期望 ${_},实际接收 ${b}`}case"invalid_value":if(I.values.length===1)return`无效输入:期望 ${q(I.values[0])}`;return`无效选项:期望以下之一 ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`数值过大:期望 ${I.origin??"值"} ${_}${I.maximum.toString()} ${N.unit??"个元素"}`;return`数值过大:期望 ${I.origin??"值"} ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`数值过小:期望 ${I.origin} ${_}${I.minimum.toString()} ${N.unit}`;return`数值过小:期望 ${I.origin} ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`无效字符串:必须以 "${_.prefix}" 开头`;if(_.format==="ends_with")return`无效字符串:必须以 "${_.suffix}" 结尾`;if(_.format==="includes")return`无效字符串:必须包含 "${_.includes}"`;if(_.format==="regex")return`无效字符串:必须满足正则表达式 ${_.pattern}`;return`无效${D[_.format]??I.format}`}case"not_multiple_of":return`无效数字:必须是 ${I.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${O(I.keys,", ")}`;case"invalid_key":return`${I.origin} 中的键(key)无效`;case"invalid_union":return"无效输入";case"invalid_element":return`${I.origin} 中包含无效值(value)`;default:return"无效输入"}}};function v2(){return{localeError:P7()}}var w7=()=>{let $={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"},map:{unit:"項目",verb:"擁有"}};function v(I){return $[I]??null}let D={regex:"輸入",email:"郵件地址",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 日期時間",date:"ISO 日期",time:"ISO 時間",duration:"ISO 期間",ipv4:"IPv4 位址",ipv6:"IPv6 位址",mac:"MAC 位址",cidrv4:"IPv4 範圍",cidrv6:"IPv6 範圍",base64:"base64 編碼字串",base64url:"base64url 編碼字串",json_string:"JSON 字串",e164:"E.164 數值",credit_card:"信用卡號",currency_code:"貨幣代碼",iban:"IBAN",jwt:"JWT",template_literal:"輸入"},g={nan:"NaN"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`無效的輸入值:預期為 instanceof ${I.expected},但收到 ${b}`;return`無效的輸入值:預期為 ${_},但收到 ${b}`}case"invalid_value":if(I.values.length===1)return`無效的輸入值:預期為 ${q(I.values[0])}`;return`無效的選項:預期為以下其中之一 ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`數值過大:預期 ${I.origin??"值"} 應為 ${_}${I.maximum.toString()} ${N.unit??"個元素"}`;return`數值過大:預期 ${I.origin??"值"} 應為 ${_}${I.maximum.toString()}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`數值過小:預期 ${I.origin} 應為 ${_}${I.minimum.toString()} ${N.unit}`;return`數值過小:預期 ${I.origin} 應為 ${_}${I.minimum.toString()}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`無效的字串:必須以 "${_.prefix}" 開頭`;if(_.format==="ends_with")return`無效的字串:必須以 "${_.suffix}" 結尾`;if(_.format==="includes")return`無效的字串:必須包含 "${_.includes}"`;if(_.format==="regex")return`無效的字串:必須符合格式 ${_.pattern}`;return`無效的 ${D[_.format]??I.format}`}case"not_multiple_of":return`無效的數字:必須為 ${I.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${I.keys.length>1?"們":""}:${O(I.keys,"、")}`;case"invalid_key":return`${I.origin} 中有無效的鍵值`;case"invalid_union":return"無效的輸入值";case"invalid_element":return`${I.origin} 中有無效的值`;default:return"無效的輸入值"}}};function I2(){return{localeError:w7()}}var q7=()=>{let $={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"},map:{unit:"nkan",verb:"ní"}};function v(I){return $[I]??null}let D={regex:"ẹ̀rọ ìbáwọlé",email:"àdírẹ́sì ìmẹ́lì",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"àkókò ISO",date:"ọjọ́ ISO",time:"àkókò ISO",duration:"àkókò tó pé ISO",ipv4:"àdírẹ́sì IPv4",ipv6:"àdírẹ́sì IPv6",mac:"àdírẹ́sì MAC",cidrv4:"àgbègbè IPv4",cidrv6:"àgbègbè IPv6",base64:"ọ̀rọ̀ tí a kọ́ ní base64",base64url:"ọ̀rọ̀ base64url",json_string:"ọ̀rọ̀ JSON",e164:"nọ́mbà E.164",credit_card:"nọmba kaadi gbese",currency_code:"koodu owó",iban:"IBAN",jwt:"JWT",template_literal:"ẹ̀rọ ìbáwọlé"},g={nan:"NaN",number:"nọ́mbà",array:"akopọ"};return(I)=>{switch(I.code){case"invalid_type":{let _=g[I.expected]??I.expected,N=M(I.input),b=g[N]??N;if(/^[A-Z]/.test(I.expected))return`Ìbáwọlé aṣìṣe: a ní láti fi instanceof ${I.expected}, àmọ̀ a rí ${b}`;return`Ìbáwọlé aṣìṣe: a ní láti fi ${_}, àmọ̀ a rí ${b}`}case"invalid_value":if(I.values.length===1)return`Ìbáwọlé aṣìṣe: a ní láti fi ${q(I.values[0])}`;return`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${O(I.values,"|")}`;case"too_big":{let _=I.inclusive?"<=":"<",N=v(I.origin);if(N)return`Tó pọ̀ jù: a ní láti jẹ́ pé ${I.origin??"iye"} ${N.verb} ${_}${I.maximum} ${N.unit}`;return`Tó pọ̀ jù: a ní láti jẹ́ ${_}${I.maximum}`}case"too_small":{let _=I.inclusive?">=":">",N=v(I.origin);if(N)return`Kéré ju: a ní láti jẹ́ pé ${I.origin} ${N.verb} ${_}${I.minimum} ${N.unit}`;return`Kéré ju: a ní láti jẹ́ ${_}${I.minimum}`}case"invalid_format":{let _=I;if(_.format==="starts_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${_.prefix}"`;if(_.format==="ends_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${_.suffix}"`;if(_.format==="includes")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${_.includes}"`;if(_.format==="regex")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${_.pattern}`;return`Aṣìṣe: ${D[_.format]??I.format}`}case"not_multiple_of":return`Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${I.divisor}`;case"unrecognized_keys":return`Bọtìnì àìmọ̀: ${O(I.keys,", ")}`;case"invalid_key":return`Bọtìnì aṣìṣe nínú ${I.origin}`;case"invalid_union":return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣìṣe nínú ${I.origin}`;default:return"Ìbáwọlé aṣìṣe"}}};function _2(){return{localeError:q7()}}var TY,D2=Symbol("ZodOutput"),g2=Symbol("ZodInput");class N2{constructor(){this._map=new WeakMap,this._idmap=new Map}add($,...v){let D=v[0];if(this._map.set($,D),D&&typeof D==="object"&&"id"in D)this._idmap.set(D.id,$);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove($){let v=this._map.get($);if(v&&typeof v==="object"&&"id"in v)this._idmap.delete(v.id);return this._map.delete($),this}get($){let v=$._zod.parent;if(v){let D={...this.get(v)??{}};delete D.id;let g={...D,...this._map.get($)};return Object.keys(g).length?g:void 0}return this._map.get($)}has($){return this._map.has($)}}function qN(){return new N2}(TY=globalThis).__zod_globalRegistry??(TY.__zod_globalRegistry=qN());var j$=globalThis.__zod_globalRegistry;var T$=Symbol.for("zod.compile.invalid"),SY=Symbol.for("zod.compile.fallback");class Dv extends Error{constructor($="z.compile does not support async refinements, transforms, or checks"){super($);this.name="ZodCompileAsyncError"}}class c extends Error{constructor($,v=!0){super(`z.compile does not support ${$}; this schema must use the runtime parser`);this.name="ZodCompileUnsupportedError",this.islandable=v}}function T7($,v){try{return TN($,{assertOnly:!0})}catch{return v}}function X2($,v){try{let D=TN($),g=MN($,D);return g._zod.bag.validator=T7($,D),g}catch(D){if(v?.strict)throw D;return $}}function MN($,v){if(PN($))throw new c("a schema whose subtree contains a reference cycle");let D=a($),g=$._zod.run,I=g.__originalRun??g,_=(N,b)=>{if(b?.async||b?.direction==="backward"||b?.skipChecks||b?.[SY])return I(N,b);if(b&&wN(b,N.value))return I(N,b);let U=v(N.value);if(U!==T$)return N.value=U,N;if(b)b[SY]=!0;return I(N,b)};if(_.__originalRun=I,D._zod.bag.fallbackRun=I,D._zod.bag.validator=v,D._zod.run=_,!g.__originalRun)S7(D,$,v);return D}function S7($,v,D){let g=$,I=v;if(typeof I.safeParse==="function"){let _=I.safeParse;g.safeParse=(N,b)=>{let U=D(N);if(U!==T$)return{success:!0,data:U};return _(N,b)}}if(typeof I.parse==="function"){let _=I.parse;g.parse=(N,b)=>{let U=D(N);if(U!==T$)return U;return _(N,b)}}}function TN($,v){let D=!0;try{D=PN($)}catch{}if(D)throw new c("a schema whose subtree contains a reference cycle");let g={constants:new Map,constantCounter:0,varCounter:0,definite:!0},I=new M4(["input"]),_=I$(I,g,$,"input",!v?.assertOnly);I.write(_===null?"return true;":`return ${_};`);let N=["INVALID",...g.constants.keys()],b=[T$,...g.constants.values()],U=I.content.join(` +`),J=v?.debug?N.length>0?`// Constants: ${N.join(", ")} +${U}`:U:"",W=Function,Y=`return (input) => { +${U} +}`,B;try{B=new W(...N,Y)(...b)}catch(j){throw new c(`this schema (generated code failed to evaluate: ${j.message})`)}if(v?.debug)B.code=J;return B.definite=g.definite,B}function n($,v){for(let[g,I]of $.constants)if(I===v)return g;let D=`c${$.constantCounter++}`;return $.constants.set(D,v),D}function w6($,v){return $.definite=!1,n($,v)}function i($){return`v${$.varCounter++}`}function A7($,v){let D=$._zod.run({value:v,issues:[]},{});if(D&&typeof D.then==="function")return T$;let g=D;return g.issues.length===0?g.value:T$}function P$($,v,D,g,I=!0){let _=$.content.length,N=v.constants.size,b=v.constantCounter,U=v.varCounter;try{return I$($,v,D,g,I)}catch(J){if(!(J instanceof c)||!J.islandable)throw J;if($.content.length=_,v.constants.size>N){let W=Array.from(v.constants.keys()).slice(N);for(let Y of W)v.constants.delete(Y)}return v.constantCounter=b,v.varCounter=U,Z7($,v,D,g)}}function Z7($,v,D,g){v.definite=!1;let I=n(v,D),_=n(v,A7),N=i(v);return $.write(`const ${N} = ${_}(${I}, ${g});`),$.write(`if (${N} === INVALID) return INVALID;`),N}var L7=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function E7($,v,D,g){let I=D._zod.def.checks;if(!I||I.length===0)return g;let _=g;for(let N of I){let b=N._zod.def;if(b.when&&!L7.has(b.check))throw new c('check with a custom "when" condition');switch(b.check){case"greater_than":V7($,v,b,_);break;case"less_than":k7($,v,b,_);break;case"multiple_of":R7($,v,b,_);break;case"number_format":kY($,b,_);break;case"min_length":{let U=fv(b.minimum,"min_length"),J=b2($,v,_,`${_}.length >= ${U} && ${_}.length < ${b.minimum*2}`);$.write(`if (${J} < ${U}) return INVALID;`);break}case"max_length":{let U=fv(b.maximum,"max_length"),J=b2($,v,_,`${_}.length > ${U}`);$.write(`if (${J} > ${U}) return INVALID;`);break}case"length_equals":{let U=fv(b.length,"length_equals"),J=b2($,v,_,`${_}.length >= ${U} && ${_}.length <= ${b.length*2}`);$.write(`if (${J} !== ${U}) return INVALID;`);break}case"min_size":$.write(`if (${_}.size < ${fv(b.minimum,"min_size")}) return INVALID;`);break;case"max_size":$.write(`if (${_}.size > ${fv(b.maximum,"max_size")}) return INVALID;`);break;case"size_equals":$.write(`if (${_}.size !== ${fv(b.size,"size_equals")}) return INVALID;`);break;case"string_format":_=RY($,v,b,_);break;case"custom":_=i7($,v,N,_);break;case"bigint_format":C7($,b,_);break;case"mime_type":x7($,v,b,_);break;case"property":y7($,v,b,_);break;case"properties":f7($,v,b,_);break;case"overwrite":{let U=i(v);u7($,v,N,_,U),_=U;break}default:throw new c(`check type ${b.check}`)}}return _}function b2($,v,D,g){let I=n(v,K6),_=i(v);return $.write(`const ${_} = typeof ${D} === "string" && ${g} ? ${I}(${D}) : ${D}.length;`),_}function fv($,v){if(typeof $!=="number"||!Number.isFinite($))throw new c(`${v} bound of type ${typeof $}`);return`${$}`}function VY($,v){if(typeof v==="bigint")return`${v}n`;if(typeof v==="number"){if(Number.isNaN(v))throw new c("comparison check with NaN bound");return`${v}`}if(v instanceof Date){if(Number.isNaN(v.getTime()))throw new c("comparison check with Invalid Date bound");return n($,v)}throw new c(`comparison check bound of type ${typeof v}`)}function V7($,v,D,g){let I=D.inclusive?"<":"<=";$.write(`if (${g} ${I} ${VY(v,D.value)}) return INVALID;`)}function k7($,v,D,g){let I=D.inclusive?">":">=";$.write(`if (${g} ${I} ${VY(v,D.value)}) return INVALID;`)}function R7($,v,D,g){if(typeof D.value==="bigint"){if(D.value===BigInt(0))throw new c("multiple_of check with a zero divisor");$.write(`if (${g} % ${D.value}n !== 0n) return INVALID;`)}else{let I=n(v,F_);$.write(`if (${I}(${g}, ${fv(D.value,"multiple_of")}) !== 0) return INVALID;`)}}function kY($,v,D){let g=v.format;switch(g){case"safeint":$.write(`if (!Number.isSafeInteger(${D})) return INVALID;`);break;case"int32":$.write(`if (!Number.isInteger(${D}) || ${D} < -2147483648 || ${D} > 2147483647) return INVALID;`);break;case"uint32":$.write(`if (!Number.isInteger(${D}) || ${D} < 0 || ${D} > 4294967295) return INVALID;`);break;case"float32":$.write(`if (!Number.isFinite(${D}) || ${D} < -3.4028234663852886e38 || ${D} > 3.4028234663852886e38) return INVALID;`);break;case"float64":$.write(`if (!Number.isFinite(${D})) return INVALID;`);break;default:throw new c(`number format ${g}`)}}function C7($,v,D){let g=v.format;if(!g)return;switch(g){case"int64":$.write(`if (${D} < -9223372036854775808n || ${D} > 9223372036854775807n) return INVALID;`);break;case"uint64":$.write(`if (${D} < 0n || ${D} > 18446744073709551615n) return INVALID;`);break;default:throw new c(`bigint format ${g}`)}}function x7($,v,D,g){let I=D.mime;if(I&&I.length>0){let _=n(v,new Set(I));$.write(`if (!${_}.has(${g}.type)) return INVALID;`)}}function f7($,v,D,g){if(D.when)throw new c('check with a custom "when" condition');$.write(`if (${g} == null) return INVALID;`);let I=D.shape;for(let _ of Reflect.ownKeys(I)){let N=typeof _==="symbol"?n(v,_):q$(_),b=i(v);$.write(`const ${b} = ${g}[${N}];`),P$($,v,I[_],b,!1)}}function y7($,v,D,g){let I=`${g}[${JSON.stringify(D.property)}]`;I$($,v,D.schema,I)}function u7($,v,D,g,I){let _=D._zod.def.tx;if(!_)throw new c("overwrite check without a transform function");if(q6(_))throw new Dv("z.compile: async overwrite transforms are not supported");let N=n(v,_);$.write(`const ${I} = ${N}(${g});`)}function U2(){throw new y$}function W2($){this.issues.push($)}function i7($,v,D,g){let I=D._zod.def;if(I.fn){if(q6(I.fn))throw new Dv("z.compile: async .refine() predicates are not supported");let _=w6(v,I.fn),N=n(v,U2),b=i(v);return $.write(`const ${b} = ${_}(${g});`),$.write(`if (${b} instanceof Promise) ${N}();`),$.write(`if (!${b}) return INVALID;`),g}if(D._zod.check){if(q6(D._zod.check))throw new Dv("z.compile: async .superRefine() / check functions are not supported");let _=D._zod.check,b=w6(v,(J)=>{let W={value:J,issues:[],addIssue:W2};if(_(W)instanceof Promise)U2();return W.issues.length===0?W.value:T$}),U=i(v);return $.write(`const ${U} = ${b}(${g});`),$.write(`if (${U} === INVALID) return INVALID;`),U}throw new c("custom check without a predicate or check function")}var l7=new Set(["cidrv4","cuid","cuid2","date","datetime","duration","e164","email","emoji","ends_with","guid","includes","ipv4","ksuid","lowercase","mac","nanoid","regex","starts_with","time","ulid","uppercase","uuid","xid"]);function RY($,v,D,g,I=!0){let _=D.format;if(_==="base64"){let J=n(v,n_);return $.write(`if (!${J}(${g})) return INVALID;`),g}if(_==="base64url"){let J=n(v,XN);return $.write(`if (!${J}(${g})) return INVALID;`),g}if(_==="jwt"){let J=n(v,YN),W=n(v,D.alg??null);return $.write(`if (!${J}(${g}, ${W})) return INVALID;`),g}if(_==="ipv6"){let J=n(v,l_);return $.write(`if (!${J}(${g})) return INVALID;`),g}if(_==="cidrv6"){let J=n(v,UN);return $.write(`if (!${J}(${g})) return INVALID;`),g}if(_==="credit_card"){let J=n(v,WN);return $.write(`if (!${J}(${g})) return INVALID;`),g}if(_==="iban"){let J=n(v,QN);return $.write(`if (!${J}(${g})) return INVALID;`),g}let N=D;if(_==="url"||_==="httpurl"||N.normalize||N.hostname!==void 0||N.protocol!==void 0){let J=n(v,gN),W=n(v,D),Y=i(v),B=i(v);if($.write(`const ${Y} = ${g}.trim();`),$.write(`const ${B} = ${J}(${Y}, ${W});`),$.write(`if (typeof ${B} === "number") return INVALID;`),N.hostname!==void 0){let F=n(v,NN);$.write(`if (!${F}(${B}, ${W}.hostname)) return INVALID;`)}if(N.protocol!==void 0){let F=n(v,bN);$.write(`if (!${F}(${B}, ${W}.protocol)) return INVALID;`)}if(!I)return null;let j=i(v),K=N.normalize?`${B}.href`:`${n(v,i_)}(${Y})`;return $.write(`const ${j} = ${K};`),j}let b=D.fn;if(b){if(q6(b))throw new c(`async string format ${_}`);let J=n(v,b);return $.write(`if (!${J}(${g})) return INVALID;`),g}if(l7.has(_)&&D.pattern){let J=n(v,D.pattern);return $.write(`${J}.lastIndex = 0;`),$.write(`if (!${J}.test(${g})) return INVALID;`),g}let U=D.format;switch(U){case"regex":throw new c("regex format without a pattern");case"lowercase":$.write(`if (${g} !== ${g}.toLowerCase()) return INVALID;`);break;case"uppercase":$.write(`if (${g} !== ${g}.toUpperCase()) return INVALID;`);break;case"includes":$.write(`if (!${g}.includes(${q$(D.includes)})) return INVALID;`);break;case"starts_with":{let J=D.prefix;$.write(`if (${g}.slice(0, ${J.length}) !== ${q$(J)}) return INVALID;`);break}case"ends_with":{let J=D.suffix;$.write(`if (${g}.slice(-${J.length}) !== ${q$(J)}) return INVALID;`);break}default:throw new c(`string format ${U}`)}return g}function I$($,v,D,g,I=!0){let _=D._zod.def,N=_.type;if(_.coerce)throw new c(`coercion (z.coerce.${N}())`);let b=I||!!_.checks?.length,U;switch(N){case"string":U=n7($,v,D,g,b);break;case"number":U=m7($,D,g);break;case"boolean":U=h7($,g);break;case"bigint":U=r7($,D,g);break;case"symbol":U=d7($,g);break;case"undefined":U=p7($,g);break;case"null":U=c7($,g);break;case"any":case"unknown":U=g;break;case"never":$.write("return INVALID;"),U=g;break;case"void":U=t7($,g);break;case"nan":U=o7($,g);break;case"date":U=a7($,g);break;case"object":U=e7($,v,D,g,b);break;case"optional":U=s7($,v,D,g,b);break;case"nullable":U=Ij($,v,D,g,b);break;case"array":U=_j($,v,D,g,b);break;case"literal":U=Dj($,v,D,g);break;case"enum":U=gj($,v,D,g);break;case"readonly":{let J=ZY($,v,D,g),W=i(v);$.write(`const ${W} = Object.freeze(${J});`),U=W;break}case"success":ZY($,v,D,g),U="true";break;case"default":case"prefault":U=Nj($,v,D,g);break;case"nonoptional":U=bj($,v,D,g);break;case"tuple":U=Uj($,v,D,g);break;case"union":U=Jj($,v,D,g);break;case"intersection":U=Qj($,v,D,g);break;case"record":U=Yj($,v,D,g);break;case"map":U=Bj($,v,D,g);break;case"set":U=jj($,v,D,g);break;case"file":U=zj($,g);break;case"template_literal":U=Kj($,v,D,g);break;case"lazy":U=Oj($,v,D,g);break;case"pipe":U=Hj($,v,D,g);break;case"custom":U=Fj($,v,D,g);break;case"transform":U=qj($,v,D,g);break;case"catch":U=wj($,v,D,g);break;default:throw new c(`schema type ${N}`)}if(U===null)return null;return E7($,v,D,U)}function n7($,v,D,g,I=!0){$.write(`if (typeof ${g} !== "string") return INVALID;`);let _=D._zod.def;if(_.format===void 0)return g;return RY($,v,_,g,I)}function m7($,v,D){$.write(`if (typeof ${D} !== "number" || !Number.isFinite(${D})) return INVALID;`);let g=v._zod.def;if(g.check==="number_format"&&g.format)kY($,{format:g.format},D);return D}function h7($,v){return $.write(`if (typeof ${v} !== "boolean") return INVALID;`),v}function r7($,v,D){$.write(`if (typeof ${D} !== "bigint") return INVALID;`);let g=v._zod.def;if(g.format)switch(g.format){case"int64":$.write(`if (${D} < -9223372036854775808n || ${D} > 9223372036854775807n) return INVALID;`);break;case"uint64":$.write(`if (${D} < 0n || ${D} > 18446744073709551615n) return INVALID;`);break}return D}function d7($,v){return $.write(`if (typeof ${v} !== "symbol") return INVALID;`),v}function p7($,v){return $.write(`if (${v} !== undefined) return INVALID;`),v}function c7($,v){return $.write(`if (${v} !== null) return INVALID;`),v}function t7($,v){return $.write(`if (${v} !== undefined) return INVALID;`),v}function o7($,v){return $.write(`if (typeof ${v} !== "number" || !Number.isNaN(${v})) return INVALID;`),v}function a7($,v){return $.write(`if (!(${v} instanceof Date) || Number.isNaN(${v}.getTime())) return INVALID;`),v}function e7($,v,D,g,I=!0){let _=D._zod.def;$.write(`if (typeof ${g} !== "object" || ${g} === null || Array.isArray(${g})) return INVALID;`);let N=_.shape,b=Object.keys(N),U=Object.getOwnPropertySymbols(N),J=U.length?[...b,...U]:b,W=(Z)=>typeof Z==="symbol"?n(v,Z):q$(Z),Y=(Z)=>typeof Z==="symbol"?`[${W(Z)}]`:q$(Z),B=N;if(b.includes("__proto__"))throw new c('object shape key "__proto__"');let j=new Map;for(let Z of J){let f=B[Z],r=W(Z),t=i(v);if($.write(`const ${t} = ${g}[${r}];`),f._zod.optin!==void 0){let y=i(v);if($.write(`let ${y} = (() => {`),$.indented((o)=>{let C$=P$(o,v,f,t);o.write(`return ${C$};`)}),$.write("})();"),f._zod.optout==="optional")$.write(`if (${y} === INVALID) {`),$.indented((o)=>{o.write(`if (${r} in ${g}) return INVALID;`),o.write(`${y} = undefined;`)}),$.write("}");else $.write(`if (${y} === INVALID) return INVALID;`);j.set(Z,y)}else{if(vj(f))$.write(`if (!(${r} in ${g})) return INVALID;`);let y=P$($,v,f,t,I);if(y!==null)j.set(Z,y)}}let K=_.catchall,F="none";if(K){let Z=K._zod.def.type;if(Z==="never"){let f=b.map((r)=>`k !== ${q$(r)}`).join(" && ")||"true";$.write(`for (const k in ${g}) {`),$.indented((r)=>{r.write(`if (${f}) return INVALID;`)}),$.write("}")}else if((Z==="unknown"||Z==="any")&&!K._zod.def.checks?.length)F="passthrough";else F="schema"}let T=i(v),V=J.some((Z)=>AY(B[Z])||J2(B[Z]));if(!I){if(F==="schema"){let Z=b.length>0?n(v,new Set(b)):null;$.write(`for (const k in ${g}) {`),$.indented((f)=>{if(f.write('if (k === "__proto__") continue;'),Z)f.write(`if (${Z}.has(k)) continue;`);let r=i(v);f.write(`const ${r} = ${g}[k];`),P$(f,v,K,r,!1)}),$.write("}")}return null}if(!V){let Z=J.map((f)=>`${Y(f)}: ${j.get(f)}`).join(", ");$.write(`const ${T} = { ${Z} };`)}else{$.write(`const ${T} = {};`);for(let Z of J){let f=W(Z),r=j.get(Z);if(J2(B[Z]))$.write(`if (${f} in ${g}) ${T}[${f}] = ${r};`);else if(AY(B[Z]))$.write(`if (${r} !== undefined || ${f} in ${g}) ${T}[${f}] = ${r};`);else $.write(`${T}[${f}] = ${r};`)}}if(F!=="none"){let Z=b.length>0?n(v,new Set(b)):null;$.write(`for (const k in ${g}) {`),$.indented((f)=>{if(f.write('if (k === "__proto__") continue;'),Z)f.write(`if (${Z}.has(k)) continue;`);if(F==="passthrough")f.write(`${T}[k] = ${g}[k];`);else{let r=i(v);f.write(`const ${r} = ${g}[k];`);let t=P$(f,v,K,r);f.write(`${T}[k] = ${t};`)}}),$.write("}")}return T}function s7($,v,D,g,I=!0){let _=D._zod.def;if($j(D))return I$($,v,_.innerType,g,I);if(_.innerType._zod.optin==="defaulted"){let b=i(v),U=i(v);return $.write(`let ${b};`),$.write(`if (${g} === undefined) {`),$.indented((J)=>{J.write(`const ${U} = (() => {`),J.indented((W)=>{let Y=I$(W,v,_.innerType,g);W.write(`return ${Y};`)}),J.write("})();"),J.write(`if (${U} !== INVALID) ${b} = ${U};`)}),$.write("} else {"),$.indented((J)=>{let W=I$(J,v,_.innerType,g);J.write(`${b} = ${W};`)}),$.write("}"),b}let N=I?i(v):null;if(N)$.write(`let ${N};`);return $.write(`if (${g} !== undefined) {`),$.indented((b)=>{let U=I$(b,v,_.innerType,g,I);if(N&&U!==null)b.write(`${N} = ${U};`)}),$.write("}"),N}function $j($){return $._zod.traits?.has("$ZodExactOptional")===!0}function vj($){return $._zod.optin===void 0&&P6($)}function P6($){if($._zod.def.coerce)return!0;let v=$._zod.def;switch(v.type){case"any":case"unknown":case"undefined":case"void":case"default":case"prefault":case"transform":case"custom":case"lazy":return!0;case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"never":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":return!1;case"nonoptional":return v.innerType?P6(v.innerType):!1;case"literal":return!!v.values?.includes(void 0);case"enum":return!!$._zod.values?.has(void 0);case"optional":case"nullable":case"readonly":case"success":return v.innerType?P6(v.innerType):!0;case"catch":return!0;case"union":return v.options?v.options.some(P6):!0;case"intersection":if(!v.left||!v.right)return!0;return P6(v.left)&&P6(v.right);case"pipe":return v.in?P6(v.in):!0;default:return!0}}function J2($){return $._zod.optin==="optional"&&$._zod.optout==="optional"}function AY($){return($._zod.optin!=="defaulted"||$._zod.optout==="optional")&&Z4($)}function Z4($){let v=$._zod.def;switch(v.type){case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":case"never":case"success":return!1;case"literal":return!!v.values?.includes(void 0);case"enum":return!!$._zod.values?.has(void 0);case"optional":return!0;case"nullable":case"readonly":case"nonoptional":return v.innerType?Z4(v.innerType):!0;case"union":return v.options?v.options.some(Z4):!0;case"intersection":return!v.left||!v.right||Z4(v.left)||Z4(v.right);case"pipe":return v.out?Z4(v.out):!0;default:return!0}}function Ij($,v,D,g,I=!0){let _=D._zod.def,N=I?i(v):null;if(N)$.write(`let ${N} = null;`);return $.write(`if (${g} !== null) {`),$.indented((b)=>{let U=I$(b,v,_.innerType,g,I);if(N&&U!==null)b.write(`${N} = ${U};`)}),$.write("}"),N}function Q2($,v,D){for(let[g,I]of K4(v._zod.def.checks))$.write(`if (${D} > ${fv(g,I._zod.def.check)}) return INVALID;`)}function _j($,v,D,g,I=!0){let _=D._zod.def;$.write(`if (!Array.isArray(${g})) return INVALID;`),Q2($,D,`${g}.length`);let N=I?i(v):null,b=i(v),U=i(v);if(N)$.write(`const ${N} = new Array(${g}.length);`);return $.write(`for (let ${b} = 0; ${b} < ${g}.length; ${b}++) {`),$.indented((J)=>{J.write(`const ${U} = ${g}[${b}];`);let W=P$(J,v,_.element,U,I);if(N&&W!==null)J.write(`${N}[${b}] = ${W};`)}),$.write("}"),N}function Dj($,v,D,g){let _=D._zod.def.values;if(_.length!==1){let b=n(v,new Set(_));return $.write(`if (!${b}.has(${g})) return INVALID;`),g}let N=_[0];if(typeof N==="number"&&Number.isNaN(N)){let b=n(v,new Set(_));return $.write(`if (!${b}.has(${g})) return INVALID;`),g}if(typeof N==="string")$.write(`if (${g} !== ${q$(N)}) return INVALID;`);else if(typeof N==="number"||typeof N==="boolean")$.write(`if (${g} !== ${N}) return INVALID;`);else if(N===null)$.write(`if (${g} !== null) return INVALID;`);else if(N===void 0)$.write(`if (${g} !== undefined) return INVALID;`);else if(typeof N==="bigint")$.write(`if (${g} !== ${N}n) return INVALID;`);else throw new c(`literal type ${typeof N}`);return g}function gj($,v,D,g){let I=D._zod.values;if(!I)throw new c("enum schema without enumerated values");let _=n(v,I);return $.write(`if (!${_}.has(${g})) return INVALID;`),g}function ZY($,v,D,g){let I=D._zod.def;return I$($,v,I.innerType,g)}function Nj($,v,D,g){let I=D._zod.def,N=Object.getOwnPropertyDescriptor(D._zod.def,"defaultValue")?()=>D._zod.def.defaultValue:void 0;if(D._zod.def.type==="prefault"){if(!N)return I$($,v,I.innerType,g);let U=n(v,N),J=i(v);return $.write(`let ${J} = ${g};`),$.write(`if (${g} === undefined) ${J} = ${U}();`),I$($,v,I.innerType,J)}let b=i(v);if(N){let U=n(v,N),J=n(v,P_);$.write(`let ${b};`),$.write(`if (${g} === undefined) {`),$.indented((W)=>{W.write(`${b} = ${J}(${U}());`)}),$.write("} else {"),$.indented((W)=>{let Y=I$(W,v,I.innerType,g);W.write(`${b} = ${Y} === undefined ? ${J}(${U}()) : ${Y};`)}),$.write("}")}else $.write(`let ${b};`),$.write(`if (${g} !== undefined) {`),$.indented((U)=>{let J=I$(U,v,I.innerType,g);U.write(`${b} = ${J};`)}),$.write("}");return b}function bj($,v,D,g){let I=D._zod.def,_=I$($,v,I.innerType,g),N=i(v);return $.write(`const ${N} = ${_};`),$.write(`if (${N} === undefined) return INVALID;`),N}function Uj($,v,D,g){let I=D._zod.def,_=I.items,N=I.rest;$.write(`if (!Array.isArray(${g})) return INVALID;`);let b=LY(_,"optin"),U=LY(_,"optout");if(N)$.write(`if (${g}.length < ${b}) return INVALID;`);else $.write(`if (${g}.length < ${b} || ${g}.length > ${_.length}) return INVALID;`);let J=i(v);$.write(`const ${J} = [];`);for(let W=0;W<_.length;W++){let Y=_[W];if(W>=U)$.write(`if (${J}.length === ${W}) {`),$.indented((B)=>{B.write(`if (${W} < ${g}.length) {`),B.indented((j)=>{let K=i(v);j.write(`const ${K} = ${g}[${W}];`);let F=P$(j,v,Y,K);j.write(`${J}[${W}] = ${F};`)}),B.write("} else {"),B.indented((j)=>{if(J2(Y)){j.write(`${J}.length = ${W};`);return}let K=i(v),F=i(v);j.write(`const ${K} = undefined;`),j.write(`const ${F} = (() => {`),j.indented((T)=>{let V=P$(T,v,Y,K);T.write(`return ${V};`)}),j.write("})();"),j.write(`if (${F} === INVALID || ${F} === undefined) ${J}.length = ${W};`),j.write(`else ${J}[${W}] = ${F};`)}),B.write("}")}),$.write("}");else{let B=i(v);$.write(`const ${B} = ${g}[${W}];`);let j=P$($,v,Y,B);$.write(`${J}[${W}] = ${j};`)}}if(N){let W=i(v),Y=i(v);$.write(`for (let ${W} = ${_.length}; ${W} < ${g}.length; ${W}++) {`),$.indented((B)=>{B.write(`const ${Y} = ${g}[${W}];`);let j=P$(B,v,N,Y);B.write(`${J}[${W}] = ${j};`)}),$.write("}")}return J}function LY($,v){for(let D=$.length-1;D>=0;D--)if(!(v==="optin"?$[D]._zod.optin!==void 0:$[D]._zod.optout==="optional"))return D+1;return 0}function Jj($,v,D,g){let I=D._zod.def,_=I.options;if(I.discriminator)return Xj($,v,I,g);if(I.inclusive===!1)throw new c("exclusive unions (z.xor)");if(_.length===0)return $.write("return INVALID;"),g;if(_.length===1)return I$($,v,_[0],g);if(_.every((U)=>U._zod.def.type==="literal"&&!U._zod.def.checks?.length)){let U=new Set(_.flatMap((W)=>W._zod.def.values)),J=n(v,U);return $.write(`if (!${J}.has(${g})) return INVALID;`),g}let b=i(v);$.write(`let ${b};`);for(let U=0;U<_.length;U++){let J=_[U];if(U===0)$.write(`${b} = (() => {`);else $.write(`if (${b} === INVALID) ${b} = (() => {`);$.indented((W)=>{let Y=I$(W,v,J,g);W.write(`return ${Y};`)}),$.write("})();")}return $.write(`if (${b} === INVALID) return INVALID;`),b}function Xj($,v,D,g){if(D.unionFallback)throw new c("discriminated union with unionFallback");if(D.options.length===0)return $.write("return INVALID;"),g;let I=i(v),_=i(v);$.write(`const ${I} = ${g}?.[${q$(D.discriminator)}];`),$.write(`let ${_};`);let N=!0,b=new Set;for(let U of D.options){let J=U._zod.propValues?.[D.discriminator];if(!J||J.size===0)throw new c("discriminated union option without static discriminator values");for(let B of J){if(b.has(B))throw new c(`duplicate discriminator value ${String(B)}`);b.add(B)}let W=Array.from(J,(B)=>Wj(v,I,B)),Y=N?"if":"else if";$.write(`${Y} (${W.join(" || ")}) {`),$.indented((B)=>{let j=I$(B,v,U,g);B.write(`${_} = ${j};`)}),$.write("}"),N=!1}return $.write("else { return INVALID; }"),_}function Wj($,v,D){if(typeof D==="string")return`${v} === ${q$(D)}`;if(typeof D==="number"){if(Number.isNaN(D))return`Number.isNaN(${v})`;return`${v} === ${D}`}if(typeof D==="boolean")return`${v} === ${D}`;if(D===null)return`${v} === null`;if(D===void 0)return`${v} === undefined`;if(typeof D==="bigint")return`${v} === ${D}n`;if(typeof D==="symbol"){let g=n($,D);return`${v} === ${g}`}throw new c(`literal discriminator value ${String(D)}`)}function Qj($,v,D,g){let I=D._zod.def;v.definite=!1;let _=P$($,v,I.left,g),N=P$($,v,I.right,g),b=n(v,T4),U=i(v);return $.write(`const ${U} = ${b}(${_}, ${N});`),$.write(`if (!${U}.valid) return INVALID;`),`${U}.data`}function Yj($,v,D,g){let I=D._zod.def,_=n(v,h$);$.write(`if (!${_}(${g})) return INVALID;`);let N=i(v),b=i(v),U=i(v);$.write(`const ${N} = {};`);let J=I,W=J.partial?void 0:I.keyType._zod.values;if(W){let j=[];for(let F of W){if(!(typeof F==="string"||typeof F==="number"||typeof F==="symbol"))throw new c(`record key value ${String(F)}`);let T=typeof F==="number"?F.toString():F;if(T==="__proto__")throw new c('record key "__proto__"');j.push(T);let V=n(v,F),Z=I$($,v,I.keyType,V),f=i(v);$.write(`const ${f} = ${g}[${Gj(v,T)}];`);let r=P$($,v,I.valueType,f);$.write(`${N}[${Z}] = ${r};`)}let K=n(v,new Set(j));return $.write(`for (const ${b} in ${g}) {`),$.indented((F)=>{if(F.write(`if (${K}.has(${b})) continue;`),J.mode==="loose")F.write(`if (${b} !== "__proto__") ${N}[${b}] = ${g}[${b}];`);else F.write("return INVALID;")}),$.write("}"),N}let Y=I.keyType._zod.def;if(!(Y.type==="string"&&Y.format===void 0&&!Y.coerce&&(Y.checks?.length??0)===0)){let j=I.mode==="loose",K=TN(I.keyType);if(K.definite===!1)v.definite=!1;let F=n(v,K),T=n(v,_v),V=i(v);return EY($,v,g,b,(Z)=>{if(Z.write(`let ${V} = ${F}(${b});`),Z.write(`if (${V} === INVALID && typeof ${b} === "string" && ${T}.test(${b})) ${V} = ${F}(Number(${b}));`),j)Z.write(`if (${V} === INVALID) { ${N}[${b}] = ${g}[${b}]; continue; }`);else Z.write(`if (${V} === INVALID) return INVALID;`);Z.write(`if (${V} === "__proto__") continue;`);let f=i(v);Z.write(`const ${f} = ${g}[${b}];`);let r=P$(Z,v,I.valueType,f);Z.write(`${N}[${V}] = ${r};`)}),N}return EY($,v,g,b,(j)=>{j.write(`const ${U} = ${g}[${b}];`);let K=P$(j,v,I.valueType,U);j.write(`${N}[${b}] = ${K};`)},"return INVALID;"),N}function EY($,v,D,g,I,_){let N=n(v,Object.prototype.propertyIsEnumerable),b=i(v),U=i(v),J=i(v);$.write(`const ${b} = Object.getOwnPropertySymbols(${D});`),$.write(`const ${U} = Object.getOwnPropertyNames(${D});`),$.write(`for (let ${J} = 0; ${J} < ${U}.length; ${J}++) {`),$.indented((W)=>{W.write(`const ${g} = ${U}[${J}];`),W.write(`if (${g} === "__proto__" || !${N}.call(${D}, ${g})) continue;`),I(W)}),$.write("}"),$.write(`for (let ${J} = 0; ${J} < ${b}.length; ${J}++) {`),$.indented((W)=>{if(W.write(`const ${g} = ${b}[${J}];`),W.write(`if (!${N}.call(${D}, ${g})) continue;`),_)W.write(_);else I(W)}),$.write("}")}function Gj($,v){if(typeof v==="string")return q$(v);return n($,v)}function Bj($,v,D,g){let I=D._zod.def;$.write(`if (!(${g} instanceof Map)) return INVALID;`),Q2($,D,`${g}.size`);let _=i(v),N=i(v),b=i(v);return $.write(`const ${_} = new Map();`),$.write(`for (const [${N}, ${b}] of ${g}) {`),$.indented((U)=>{let J=I$(U,v,I.keyType,N),W=I$(U,v,I.valueType,b);U.write(`${_}.set(${J}, ${W});`)}),$.write("}"),_}function jj($,v,D,g){let I=D._zod.def;$.write(`if (!(${g} instanceof Set)) return INVALID;`),Q2($,D,`${g}.size`);let _=i(v),N=i(v);return $.write(`const ${_} = new Set();`),$.write(`for (const ${N} of ${g}) {`),$.indented((b)=>{let U=I$(b,v,I.valueType,N);b.write(`${_}.add(${U});`)}),$.write("}"),_}function zj($,v){return $.write(`if (!(${v} instanceof File)) return INVALID;`),v}function Kj($,v,D,g){$.write(`if (typeof ${g} !== "string") return INVALID;`);let I=D._zod.pattern;if(I){let _=n(v,I);$.write(`${_}.lastIndex = 0;`),$.write(`if (!${_}.test(${g})) return INVALID;`)}return g}function Oj($,v,D,g){let I=D._zod.def,_=w6(v,I.getter),N=n(v,{parser:null});$.write(`if (!${N}.parser) {`),$.indented((U)=>{U.write(`const inner = ${_}();`),U.write(`${N}.parser = function(input) {`),U.indented((J)=>{J.write("const result = inner._zod.run({ value: input, issues: [] }, {});"),J.write("return result.issues.length === 0 ? result.value : INVALID;")}),U.write("};")}),$.write("}");let b=i(v);return $.write(`const ${b} = ${N}.parser(${g});`),$.write(`if (${b} === INVALID) return INVALID;`),b}function Hj($,v,D,g){let I=D._zod.def,_=I$($,v,I.in,g);if(I.transform){if(q6(I.transform))throw new Dv("z.compile: async transforms in pipes are not supported");let N=I.transform,U=w6(v,(W)=>{let Y={value:W,issues:[],addIssue:W2},B=N(W,Y);if(B instanceof Promise)return T$;return Y.issues.length===0?B:T$}),J=i(v);return $.write(`const ${J} = ${U}(${_});`),$.write(`if (${J} === INVALID) return INVALID;`),I$($,v,I.out,J)}else return I$($,v,I.out,_)}function q6($){return typeof $==="function"&&($.constructor.name==="AsyncFunction"||$[Symbol.toStringTag]==="AsyncFunction")}function Fj($,v,D,g){let I=D._zod.def;if(I.fn){if(q6(I.fn))throw new Dv("z.compile: async custom predicates are not supported");let _=w6(v,I.fn),N=n(v,U2),b=i(v);$.write(`const ${b} = ${_}(${g});`),$.write(`if (${b} instanceof Promise) ${N}();`),$.write(`if (!${b}) return INVALID;`)}else throw new c("custom schema without a predicate function");return g}function Pj($,v,D){let g=$._zod.run({value:D,issues:[]},{});if(g&&typeof g.then==="function")return T$;let I=g;if(I.issues.length===0)return I.value;return v()}function wj($,v,D,g){let I=D._zod.def;if(!I.catchValue[xg])throw new c("catch with a callback (only a constant catch value compiles)",!1);let _=i(v);$.write(`let ${_} = (() => {`),$.indented((J)=>{let W=P$(J,v,I.innerType,g);J.write(`return ${W};`)}),$.write("})();");let N=n(v,I.innerType),b=w6(v,I.catchValue),U=n(v,Pj);return $.write(`if (${_} === INVALID) {`),$.indented((J)=>{J.write(`${_} = ${U}(${N}, ${b}, ${g});`),J.write(`if (${_} === INVALID) return INVALID;`)}),$.write("}"),_}function qj($,v,D,g){let I=D._zod.def;if(I.transform){if(q6(I.transform))throw new Dv("z.compile: async transforms are not supported");let _=I.transform,b=w6(v,(J)=>{let W={value:J,issues:[],addIssue:W2},Y=_(J,W);if(Y instanceof Promise)return T$;return W.issues.length===0?Y:T$}),U=i(v);return $.write(`const ${U} = ${b}(${g});`),$.write(`if (${U} === INVALID) return INVALID;`),U}return g}function SN($){if($.checks)$.checks=[...$.checks];return $}function Y2($,v){return new $(SN({type:"string",...A(v)}))}function G2($,v){return new $(SN({type:"string",coerce:!0,...A(v)}))}function AN($,v){return new $({type:"string",format:"email",check:"string_format",abort:!1,...A(v)})}function ZN($,v){return new $({type:"string",format:"guid",check:"string_format",abort:!1,...A(v)})}function LN($,v){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,...A(v)})}function EN($,v){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...A(v)})}function VN($,v){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...A(v)})}function kN($,v){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...A(v)})}function ID($,v){return new $({type:"string",format:"url",check:"string_format",abort:!1,...A(v)})}function RN($,v){return new $({type:"string",format:"emoji",check:"string_format",abort:!1,...A(v)})}function CN($,v){return new $({type:"string",format:"nanoid",check:"string_format",abort:!1,...A(v)})}function xN($,v){return new $({type:"string",format:"cuid",check:"string_format",abort:!1,...A(v)})}function fN($,v){return new $({type:"string",format:"cuid2",check:"string_format",abort:!1,...A(v)})}function yN($,v){return new $({type:"string",format:"ulid",check:"string_format",abort:!1,...A(v)})}function uN($,v){return new $({type:"string",format:"xid",check:"string_format",abort:!1,...A(v)})}function iN($,v){return new $({type:"string",format:"ksuid",check:"string_format",abort:!1,...A(v)})}function lN($,v){return new $({type:"string",format:"ipv4",check:"string_format",abort:!1,...A(v)})}function nN($,v){return new $({type:"string",format:"ipv6",check:"string_format",abort:!1,...A(v)})}function B2($,v){return new $({type:"string",format:"mac",check:"string_format",abort:!1,...A(v)})}function mN($,v){return new $({type:"string",format:"cidrv4",check:"string_format",abort:!1,...A(v)})}function hN($,v){return new $({type:"string",format:"cidrv6",check:"string_format",abort:!1,...A(v)})}function rN($,v){return new $({type:"string",format:"base64",check:"string_format",abort:!1,...A(v)})}function dN($,v){return new $({type:"string",format:"base64url",check:"string_format",abort:!1,...A(v)})}function pN($,v){return new $({type:"string",format:"e164",check:"string_format",abort:!1,...A(v)})}function j2($,v){return new $({type:"string",format:"credit_card",check:"string_format",abort:!1,...A(v)})}function z2($,v){return new $({type:"string",format:"iban",check:"string_format",abort:!1,...A(v)})}function cN($,v){return new $({type:"string",format:"jwt",check:"string_format",abort:!1,...A(v)})}var K2={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function _D($,v){return new $({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...A(v)})}function DD($,v){return new $({type:"string",format:"date",check:"string_format",...A(v)})}function gD($,v){return new $({type:"string",format:"time",check:"string_format",precision:null,...A(v)})}function ND($,v){return new $({type:"string",format:"duration",check:"string_format",...A(v)})}function O2($,v){return new $(SN({type:"number",checks:[],...A(v)}))}function H2($,v){return new $(SN({type:"number",coerce:!0,checks:[],...A(v)}))}function F2($,v){return new $({type:"number",check:"number_format",abort:!1,format:"safeint",...A(v)})}function P2($,v){return new $({type:"number",check:"number_format",abort:!1,format:"float32",...A(v)})}function w2($,v){return new $({type:"number",check:"number_format",abort:!1,format:"float64",...A(v)})}function q2($,v){return new $({type:"number",check:"number_format",abort:!1,format:"int32",...A(v)})}function M2($,v){return new $({type:"number",check:"number_format",abort:!1,format:"uint32",...A(v)})}function T2($,v){return new $({type:"boolean",...A(v)})}function S2($,v){return new $({type:"boolean",coerce:!0,...A(v)})}function A2($,v){return new $({type:"bigint",...A(v)})}function Z2($,v){return new $({type:"bigint",coerce:!0,...A(v)})}function L2($,v){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...A(v)})}function E2($,v){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...A(v)})}function V2($,v){return new $({type:"symbol",...A(v)})}function k2($,v){return new $({type:"undefined",...A(v)})}function R2($,v){return new $({type:"null",...A(v)})}function C2($){return new $({type:"any"})}function x2($){return new $({type:"unknown"})}function f2($,v){return new $({type:"never",...A(v)})}function y2($,v){return new $({type:"void",...A(v)})}function u2($,v){return new $({type:"date",...A(v)})}function i2($,v){return new $({type:"date",coerce:!0,...A(v)})}function l2($,v){return new $({type:"nan",...A(v)})}function gv($,v){return new eg({check:"less_than",...A(v),value:$,inclusive:!1})}function u$($,v){return new eg({check:"less_than",...A(v),value:$,inclusive:!0})}function Nv($,v){return new sg({check:"greater_than",...A(v),value:$,inclusive:!1})}function i$($,v){return new sg({check:"greater_than",...A(v),value:$,inclusive:!0})}function tN($){return Nv(0,$)}function oN($){return gv(0,$)}function aN($){return u$(0,$)}function eN($){return i$(0,$)}function yv($,v){return new BJ({check:"multiple_of",...A(v),value:$})}function uv($,v){return new KJ({check:"max_size",...A(v),maximum:$})}function bv($,v){return new OJ({check:"min_size",...A(v),minimum:$})}function M6($,v){return new HJ({check:"size_equals",...A(v),size:$})}function T6($,v){return new FJ({check:"max_length",...A(v),maximum:$})}function Hv($,v){return new PJ({check:"min_length",...A(v),minimum:$})}function S6($,v){return new wJ({check:"length_equals",...A(v),length:$})}function L4($,v){return new qJ({check:"string_format",format:"regex",...A(v),pattern:$})}function E4($){return new MJ({check:"string_format",format:"lowercase",...A($)})}function V4($){return new TJ({check:"string_format",format:"uppercase",...A($)})}function k4($,v){return new SJ({check:"string_format",format:"includes",...A(v),includes:$})}function R4($,v){return new AJ({check:"string_format",format:"starts_with",...A(v),prefix:$})}function C4($,v){return new ZJ({check:"string_format",format:"ends_with",...A(v),suffix:$})}function sN($,v,D){return new LJ({check:"property",property:$,schema:v,...A(D)})}function x4($,v){return new EJ({check:"properties",shape:$,...A(v)})}function f4($,v){return new VJ({check:"mime_type",mime:$,...A(v)})}function a$($){return new kJ({check:"overwrite",tx:$})}function y4($){return a$((v)=>v.normalize($))}function u4(){return a$(($)=>$.trim())}function i4(){return a$(($)=>$.toLowerCase())}function l4(){return a$(($)=>$.toUpperCase())}function n4(){return a$(($)=>KU($))}function n2($,v,D){return new $({type:"array",element:v,...A(D)})}function Mj($,v,D){return new $({type:"union",options:v,...A(D)})}function Tj($,v,D){return new $({type:"union",options:v,inclusive:!1,...A(D)})}function Sj($,v,D,g){return new $({type:"union",options:D,discriminator:v,...A(g)})}function Aj($,v,D){return new $({type:"intersection",left:v,right:D})}function Zj($,v,D,g){let I=D instanceof m;return new $({type:"tuple",items:v,rest:I?D:null,...A(I?g:D)})}function Lj($,v,D,g){return new $({type:"record",keyType:v,valueType:D,...A(g)})}function Ej($,v,D,g){return new $({type:"map",keyType:v,valueType:D,...A(g)})}function Vj($,v,D){return new $({type:"set",valueType:v,...A(D)})}function kj($,v,D){let g=Array.isArray(v)?Object.fromEntries(v.map((I)=>[I,I])):v;return new $({type:"enum",entries:g,...A(D)})}function Rj($,v,D){return new $({type:"enum",entries:v,...A(D)})}function Cj($,v,D){return new $({type:"literal",values:Array.isArray(v)?v:[v],...A(D)})}function m2($,v){return new $({type:"file",...A(v)})}function xj($,v){return new $({type:"transform",transform:v})}function fj($,v){return new $({type:"optional",innerType:v})}function yj($,v){return new $({type:"nullable",innerType:v})}function uj($,v,D){return new $({type:"default",innerType:v,get defaultValue(){return typeof D==="function"?D():P_(D)}})}function ij($,v,D){return new $({type:"nonoptional",innerType:v,...A(D)})}function lj($,v){return new $({type:"success",innerType:v})}function nj($,v,D){return new $({type:"catch",innerType:v,catchValue:typeof D==="function"?D:qU(D)})}function mj($,v,D){return new $({type:"pipe",in:v,out:D})}function hj($,v){return new $({type:"readonly",innerType:v})}function rj($,v,D){return new $({type:"template_literal",parts:v,...A(D)})}function dj($,v){return new $({type:"lazy",getter:v})}function pj($,v){return new $({type:"promise",innerType:v})}function h2($,v,D){let g=A(D);return g.abort??(g.abort=!0),new $({type:"custom",check:"custom",fn:v,...g})}function r2($,v,D){return new $({type:"custom",check:"custom",fn:v,...A(D)})}function d2($,v){let D=CY((g)=>{return g.addIssue=(I)=>{if(typeof I==="string")g.issues.push(O4(I,g.value,D._zod.def));else{let _=I;if(_.fatal)_.continue=!1;if(_.code??(_.code="custom"),!("input"in _))_.input=g.value;_.inst??(_.inst=D),_.continue??(_.continue=!D._zod.def.abort),g.issues.push(O4(_))}},$(g.value,g)},v);return D}function CY($,v){let D=new v$({check:"custom",...A(v)});return D._zod.check=$,D}function p2($){let v=new v$({check:"describe"});return v._zod.onattach=[(D)=>{let g=j$.get(D)??{};j$.add(D,{...g,description:$})}],v._zod.check=()=>{},v}function c2($){let v=new v$({check:"meta"});return v._zod.onattach=[(D)=>{let g=j$.get(D)??{};j$.add(D,{...g,...$})}],v._zod.check=()=>{},v}function t2($,v){let D=A(v),g=D.truthy??["true","1","yes","on","y","enabled"],I=D.falsy??["false","0","no","off","n","disabled"];if(D.case!=="sensitive")g=g.map((j)=>typeof j==="string"?j.toLowerCase():j),I=I.map((j)=>typeof j==="string"?j.toLowerCase():j);let _=new Set(g),N=new Set(I),b=$.Codec??d_,U=$.Boolean??h_,W=new($.String??F6)({type:"string",error:D.error}),Y=new U({type:"boolean",error:D.error}),B=new b({type:"pipe",in:W,out:Y,transform:(j,K)=>{let F=j;if(D.case!=="sensitive")F=F.toLowerCase();if(_.has(F))return!0;else if(N.has(F))return!1;else return K.issues.push({code:"invalid_value",expected:"stringbool",values:[..._,...N],input:K.value,inst:B,continue:!1}),{}},reverseTransform:(j,K)=>{if(j===!0)return g[0]||"true";else return I[0]||"false"},error:D.error});return B._zod.bag.truthy=g,B._zod.bag.falsy=I,B._zod.bag.case=D.case??"insensitive",B}function A6($,v,D,g={}){let I=A(g),_={check:"string_format",type:"string",format:v,fn:typeof D==="function"?D:(b)=>D.test(b),...I};if(D instanceof RegExp)_.pattern=D;return new $(_)}function bD($,...v){for(let D of v)for(let g of Reflect.ownKeys(D))if(Object.prototype.propertyIsEnumerable.call(D,g))B$($,g,D[g]);return $}function iv($){let v=$?.target??"draft-2020-12";if(v==="draft-4")v="draft-04";if(v==="draft-7")v="draft-07";return{processors:$.processors??{},metadataRegistry:$?.metadata??j$,target:v,unrepresentable:$?.unrepresentable??"throw",override:$?.override??(()=>{}),io:$?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:$?.cycles??"ref",reused:$?.reused??"inline",intersections:[],deferred:[],external:$?.external??void 0}}function J$($,v,D,g,I){let _=typeof v.unrepresentable==="function"?v.unrepresentable({zodSchema:$,path:g.path,message:I}):v.unrepresentable;if(_==="any")return!1;if(_===void 0||_==="throw")throw Error(I);return Object.assign(D,_),!0}function s($,v,D={path:[],schemaPath:[]}){var g;let I=$._zod.def,_=v.seen.get($);if(_){if(_.count++,D.schemaPath.includes($))_.cycle=D.path;return _.schema}let N={schema:{},count:1,cycle:void 0,path:D.path};v.seen.set($,N),v.sharedDefsExtractedFor=void 0,v.sharedEmitDoneFor=void 0;let b=$._zod.toJSONSchema?.();if(b)N.schema=b;else{let W={...D,schemaPath:[...D.schemaPath,$],path:D.path};if($._zod.processJSONSchema)$._zod.processJSONSchema(v,N.schema,W);else{let B=N.schema,j=v.processors[I.type];if(!j)throw Error(`[toJSONSchema]: Non-representable type encountered: ${I.type}`);j($,v,B,W)}let Y=$._zod.parent;if(Y){if(!N.ref)N.ref=Y;s(Y,v,W),v.seen.get(Y).isParent=!0}}let U=v.metadataRegistry.get($);if(U)bD(N.schema,U);if(v.io==="input"&&S$($))delete N.schema.examples,delete N.schema.default;if(v.io==="input"&&"_prefault"in N.schema)(g=N.schema).default??(g.default=N.schema._prefault);return delete N.schema._prefault,v.seen.get($).schema}function xY($){return $.replace(/~/g,"~0").replace(/\//g,"~1")}function lv($,v){let D=$.seen.get(v);if(!D)throw Error("Unprocessed schema. This is a bug in Zod.");if($.external&&$.sharedDefsExtractedFor===$.external)return;let g=new Map;for(let N of $.seen.entries()){let b=$.metadataRegistry.get(N[0])?.id;if(b){let U=g.get(b);if(U&&U!==N[0])throw Error(`Duplicate schema id "${b}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);g.set(b,N[0])}}let I=(N)=>{let b=$.target==="draft-2020-12"?"$defs":"definitions";if($.external){let Y=$.external.registry.get(N[0])?.id,B=$.external.uri??((K)=>K);if(Y)return{ref:B(Y)};let j=N[1].defId??N[1].schema.id??`schema${$.counter++}`;return N[1].defId=j,{defId:j,ref:`${B("__shared")}#/${b}/${xY(j)}`}}let U="#",J=`${U}/${b}/`;if(N[1]===D&&!N[1].schema.id)return{ref:U};let W=N[1].schema.id??`__schema${$.counter++}`;return{defId:W,ref:J+xY(W)}},_=(N)=>{if(N[1].schema.$ref)return;let b=N[1],{ref:U,defId:J}=I(N);if(b.def={...b.schema},J)b.defId=J;let W=b.schema;for(let Y in W)delete W[Y];W.$ref=U};if($.cycles==="throw")for(let N of $.seen.entries()){let b=N[1];if(b.cycle)throw Error(`Cycle detected: #/${b.cycle?.join("/")}/ + +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let N of $.seen.entries()){let b=N[1];if(v===N[0]){_(N);continue}if($.external){let J=$.external.registry.get(N[0])?.id;if(v!==N[0]&&J){_(N);continue}}if($.metadataRegistry.get(N[0])?.id){_(N);continue}if(b.cycle){_(N);continue}if(b.count>1){if($.reused==="ref")_(N)}}if($.external)$.sharedDefsExtractedFor=$.external}function uY($){let v=$.anyOf;if(!Array.isArray(v)||v.length===0||$.type!==void 0)return;let D=[];for(let g of v){if(!g||typeof g!=="object")return;uY(g);let I=Object.keys(g);if(I.length!==1||I[0]!=="type")return;let _=g.type;for(let N of Array.isArray(_)?_:[_]){if(typeof N!=="string")return;if(!D.includes(N))D.push(N)}}delete $.anyOf,$.type=D.length===1?D[0]:D}var iY=new Set(["type","properties","required","additionalProperties"]),fY=["oneOf","anyOf"];function yY($){let v=$.additionalProperties;if(v===void 0||v===!1||typeof v!=="object"||v===null)return null;return Object.keys(v).length?v:null}function o2($){let v=[];for(let _ of $){if(typeof _!=="object"||_.type!=="object")return null;for(let N in _)if(!iY.has(N))return null;v.push(_)}let D={},g=new Set;for(let _ of v){for(let N in _.properties){if(Object.prototype.hasOwnProperty.call(D,N))continue;let b=[];for(let J of v){let W=J.properties?.[N]??yY(J);if(W===null||W===void 0)continue;if(!b.some((Y)=>JSON.stringify(Y)===JSON.stringify(W)))b.push(W)}let U=b.length===1?b[0]:o2(b)??{allOf:b};B$(D,N,U)}for(let N of _.required??[])g.add(N)}let I={type:"object",properties:D};if(g.size)I.required=[...g];if(v.every((_)=>_.additionalProperties===!1))I.additionalProperties=!1;else{let _=[];for(let N of v){let b=yY(N);if(b&&!_.some((U)=>JSON.stringify(U)===JSON.stringify(b)))_.push(b)}if(_.length===1)I.additionalProperties=_[0];else if(_.length>1)I.additionalProperties={allOf:_}}return I}function cj($){let v=$.allOf;if(!Array.isArray(v)||v.length<2)return;for(let I of iY)if(I in $)return;let D=v.filter((I)=>fY.some((_)=>Array.isArray(I[_]))),g=null;if(!D.length)g=o2(v);else{let I=D[0],_=fY.find((U)=>Array.isArray(I[U]));if(Object.keys(I).length!==1)return;let N=v.filter((U)=>U!==I),b=I[_].map((U)=>o2([...N,U]));if(b.some((U)=>!U))return;g={[_]:b}}if(!g)return;delete $.allOf,bD($,g)}function nv($,v){let D=$.seen.get(v);if(!D)throw Error("Unprocessed schema. This is a bug in Zod.");let g=(b)=>{let U=$.seen.get(b);if(U.ref===null)return;let J=U.def??U.schema,W={...J},Y=U.ref;if(U.ref=null,Y){g(Y);let j=$.seen.get(Y),K=j.schema;if(K.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))J.allOf=J.allOf??[],J.allOf.push(K);else bD(J,K);if(bD(J,W),b._zod.parent===Y)for(let T in J){if(T==="$ref"||T==="allOf")continue;if(!(T in W))delete J[T]}if(K.$ref&&j.def)for(let T in J){if(T==="$ref"||T==="allOf")continue;if(T in j.def&&JSON.stringify(J[T])===JSON.stringify(j.def[T]))delete J[T]}}let B=b._zod.parent;if(B&&B!==Y){g(B);let j=$.seen.get(B);if(j?.schema.$ref){if(J.$ref=j.schema.$ref,j.def)for(let K in J){if(K==="$ref"||K==="allOf")continue;if(K in j.def&&JSON.stringify(J[K])===JSON.stringify(j.def[K]))delete J[K]}}}$.override({zodSchema:b,jsonSchema:J,path:U.path??[]})};if(!$.external||$.sharedEmitDoneFor!==$.external){for(let b of[...$.seen.entries()].reverse())g(b[0]);if($.target!=="openapi-3.0")for(let b of $.seen.entries())uY(b[1].def??b[1].schema);for(let b of $.deferred)b();if($.intersections.length){let b=new Map;for(let U of $.seen.values())for(let J of[U.schema,U.def]){let W=J?.allOf;if(!Array.isArray(W))continue;let Y=b.get(W);if(Y)Y.push(J);else b.set(W,[J])}for(let U of $.intersections)for(let J of b.get(U)??[])cj(J)}}let I={};if($.target==="draft-2020-12")I.$schema="https://json-schema.org/draft/2020-12/schema";else if($.target==="draft-07")I.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="draft-04")I.$schema="http://json-schema.org/draft-04/schema#";else if($.target==="openapi-3.0");if($.external?.uri){let b=$.external.registry.get(v)?.id;if(!b)throw Error("Schema is missing an `id` property");I.$id=$.external.uri(b)}bD(I,D.defId?D.schema:D.def??D.schema);let _=$.metadataRegistry.get(v)?.id;if(_!==void 0&&I.id===_)delete I.id;let N=$.external?.defs??{};if(!$.external||$.sharedEmitDoneFor!==$.external)for(let b of $.seen.entries()){let U=b[1];if(U.def&&U.defId){if(U.def.id===U.defId)delete U.def.id;B$(N,U.defId,U.def)}}if($.external)$.sharedEmitDoneFor=$.external;if($.external);else if(Object.keys(N).length>0)if($.target==="draft-2020-12")I.$defs=N;else I.definitions=N;try{let b=JSON.parse(JSON.stringify(I));return Object.defineProperty(b,"~standard",{value:{...v["~standard"],jsonSchema:{input:m4(v,"input",$.processors),output:m4(v,"output",$.processors)}},enumerable:!1,writable:!1}),b}catch(b){throw Error("Error converting schema to JSON.")}}function S$($,v){let D=v??{seen:new Set};if(D.seen.has($))return!1;D.seen.add($);let g=$._zod.def;if(g.type==="transform")return!0;if(g.type==="array")return S$(g.element,D);if(g.type==="set")return S$(g.valueType,D);if(g.type==="lazy")return S$(g.getter(),D);if(g.type==="promise"||g.type==="optional"||g.type==="nonoptional"||g.type==="nullable"||g.type==="readonly"||g.type==="default"||g.type==="prefault"||g.type==="catch")return S$(g.innerType,D);if(g.type==="intersection")return S$(g.left,D)||S$(g.right,D);if(g.type==="record"||g.type==="map")return S$(g.keyType,D)||S$(g.valueType,D);if(g.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;return S$(g.in,D)||S$(g.out,D)}if(g.type==="object"){for(let I in g.shape)if(S$(g.shape[I],D))return!0;return!1}if(g.type==="union"){for(let I of g.options)if(S$(I,D))return!0;return!1}if(g.type==="tuple"){for(let I of g.items)if(S$(I,D))return!0;if(g.rest&&S$(g.rest,D))return!0;return!1}return!1}var a2=($,v={})=>(D)=>{let g=iv({...D,processors:v});return s($,g),lv(g,$),nv(g,$)},m4=($,v,D={})=>(g)=>{let{libraryOptions:I,target:_}=g??{},N=iv({...I??{},target:_,io:v,processors:D});return s($,N),lv(N,$),nv(N,$)};var h4=($,v,D)=>{if($[v]===void 0||D>$[v])$[v]=D},r4=($,v,D)=>{if($[v]===void 0||D<$[v])$[v]=D},lY=($,v)=>{h4($,"minimum",v),r4($,"maximum",v)},rY=($,v)=>{if($.multipleOf??($.multipleOf=[]),!$.multipleOf.includes(v))$.multipleOf.push(v)},dY=($,v)=>{$.patterns??($.patterns=new Set),$.patterns.add(v)},pY=($,v)=>{$.mime=$.mime?$.mime.filter((D)=>v.includes(D)):[...v]},cY=($,v)=>{if($.format=v,v.includes("int"))$.isInt=!0},nY=($,v)=>h4($,"minimum",v.minimum),mY=($,v)=>r4($,"maximum",v.maximum),hY=($)=>(v,D)=>{cY(v,D.format);let[g,I]=$[D.format];h4(v,"minimum",g),r4(v,"maximum",I)},tj={greater_than:($,v)=>h4($,v.inclusive?"minimum":"exclusiveMinimum",v.value),less_than:($,v)=>r4($,v.inclusive?"maximum":"exclusiveMaximum",v.value),multiple_of:($,v)=>rY($,v.value),number_format:hY(q_),bigint_format:hY(M_),min_length:nY,max_length:mY,length_equals:($,v)=>lY($,v.length),min_size:nY,max_size:mY,size_equals:($,v)=>lY($,v.size),string_format:($,v)=>{if(cY($,v.format),v.pattern)dY($,v.pattern);if(v.format==="base64"||v.format==="base64url")$.contentEncoding=v.format;if(v.local||v.precision===-1)$.laxFormat=!0},mime_type:($,v)=>pY($,v.mime)};function X$($){let v={},D=$._zod.def,g=$._zod.traits.has("$ZodCheck")?[$,...D.checks??[]]:D.checks??[];for(let _ of g)tj[_._zod.def.check]?.(v,_._zod.def);let I=$._zod.bag;if(I.minimum!==void 0)h4(v,"minimum",I.minimum);if(I.exclusiveMinimum!==void 0)h4(v,"exclusiveMinimum",I.exclusiveMinimum);if(I.maximum!==void 0)r4(v,"maximum",I.maximum);if(I.exclusiveMaximum!==void 0)r4(v,"exclusiveMaximum",I.exclusiveMaximum);if(I.multipleOf!==void 0)rY(v,I.multipleOf);if(I.format!==void 0){if(v.format??(v.format=I.format),I.format.includes("int"))v.isInt=!0}if(I.mime)pY(v,I.mime);for(let _ of I.patterns??[])dY(v,_);return v}var oj={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},aj=new Map([[JN,tU],[m_,oU]]),tY=($)=>aj.get($)??$,$W=($,v,D,g)=>{let I=D;I.type="string";let{minimum:_,maximum:N,format:b,patterns:U,contentEncoding:J,laxFormat:W}=X$($);if(typeof _==="number")I.minLength=_;if(typeof N==="number")I.maxLength=N;if(b){if(I.format=oj[b]??b,I.format==="")delete I.format;if(b==="time"||W)delete I.format}if(J)I.contentEncoding=J;if(U&&U.size>0){let Y=[...U].map(tY);if(Y.length===1)I.pattern=Y[0].source;else if(Y.length>1)I.allOf=[...Y.map((B)=>({...v.target==="draft-07"||v.target==="draft-04"||v.target==="openapi-3.0"?{type:"string"}:{},pattern:B.source}))]}},vW=($,v,D,g)=>{let I=D,{minimum:_,maximum:N,multipleOf:b,exclusiveMaximum:U,exclusiveMinimum:J,isInt:W}=X$($);I.type=W?"integer":"number";let Y=typeof J==="number"&&J>=(_??Number.NEGATIVE_INFINITY),B=typeof U==="number"&&U<=(N??Number.POSITIVE_INFINITY),j=v.target==="draft-04"||v.target==="openapi-3.0";if(Y)if(j)I.minimum=J,I.exclusiveMinimum=!0;else I.exclusiveMinimum=J;else if(typeof _==="number")I.minimum=_;if(B)if(j)I.maximum=U,I.exclusiveMaximum=!0;else I.exclusiveMaximum=U;else if(typeof N==="number")I.maximum=N;if(b){let K=new Set;for(let V of b)if(Number.isFinite(V)&&V!==0)K.add(Math.abs(V));else J$($,v,I,g,`A multipleOf divisor of ${V} cannot be represented in JSON Schema`);let[F,...T]=K;if(F!==void 0)I.multipleOf=F;if(T.length)I.allOf=[...I.allOf??[],...T.map((V)=>({multipleOf:V}))]}},IW=($,v,D,g)=>{D.type="boolean"},_W=($,v,D,g)=>{J$($,v,D,g,"BigInt cannot be represented in JSON Schema")},DW=($,v,D,g)=>{J$($,v,D,g,"Symbols cannot be represented in JSON Schema")},gW=($,v,D,g)=>{if(v.target==="openapi-3.0")D.type="string",D.nullable=!0,D.enum=[null];else D.type="null"},NW=($,v,D,g)=>{J$($,v,D,g,"Undefined cannot be represented in JSON Schema")},bW=($,v,D,g)=>{J$($,v,D,g,"Void cannot be represented in JSON Schema")},UW=($,v,D,g)=>{D.not={}},JW=($,v,D,g)=>{},XW=($,v,D,g)=>{},WW=($,v,D,g)=>{J$($,v,D,g,"Date cannot be represented in JSON Schema")},QW=($,v,D,g)=>{let I=$._zod.def,_=G4(I.entries);if(_.length===0){D.not={};return}if(_.every((N)=>typeof N==="number"))D.type="number";if(_.every((N)=>typeof N==="string"))D.type="string";D.enum=_},YW=($,v,D,g)=>{let I=$._zod.def;if(I.values.length===0){D.not={};return}let _=[];for(let N of I.values)if(N===void 0){if(J$($,v,D,g,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof N==="bigint"){if(J$($,v,D,g,"BigInt literals cannot be represented in JSON Schema"))return;_.push(Number(N))}else _.push(N);if(_.length===0);else if(_.length===1){let N=_[0];if(D.type=N===null?"null":typeof N,v.target==="draft-04"||v.target==="openapi-3.0")D.enum=[N];else D.const=N}else{if(_.every((N)=>typeof N==="number"))D.type="number";if(_.every((N)=>typeof N==="string"))D.type="string";if(_.every((N)=>typeof N==="boolean"))D.type="boolean";if(_.every((N)=>N===null))D.type="null";D.enum=_}},GW=($,v,D,g)=>{J$($,v,D,g,"NaN cannot be represented in JSON Schema")},BW=($,v,D,g)=>{let I=D,_=$._zod.pattern;if(!_)throw Error("Pattern not found in template literal");I.type="string",I.pattern=_.source},jW=($,v,D,g)=>{let I=D;I.type="string",I.format="binary",I.contentEncoding="binary";let{minimum:_,maximum:N,mime:b}=X$($);if(_!==void 0)I.minLength=_;if(N!==void 0)I.maxLength=N;if(!b)return;if(b.length===0)I.not={};else if(b.length===1)I.contentMediaType=b[0];else I.anyOf=b.map((U)=>({contentMediaType:U}))},zW=($,v,D,g)=>{D.type="boolean"},KW=($,v,D,g)=>{J$($,v,D,g,"Custom types cannot be represented in JSON Schema")},OW=($,v,D,g)=>{J$($,v,D,g,"Function types cannot be represented in JSON Schema")},HW=($,v,D,g)=>{J$($,v,D,g,"Transforms cannot be represented in JSON Schema")},FW=($,v,D,g)=>{J$($,v,D,g,"Map cannot be represented in JSON Schema")},PW=($,v,D,g)=>{J$($,v,D,g,"Set cannot be represented in JSON Schema")},wW=($,v,D,g)=>{let I=D,_=$._zod.def,{minimum:N,maximum:b}=X$($);if(typeof N==="number")I.minItems=N;if(typeof b==="number")I.maxItems=b;I.type="array",I.items=s(_.element,v,{...g,path:[...g.path,"items"]})};function UD($){let v=$._zod.def;if(v.type==="pipe"&&v.in._zod.traits.has("$ZodTransform"))return UD(v.out);if(v.type==="catch")return UD(v.innerType);return $._zod.optin}var qW=($,v,D,g)=>{let I=D,_=$._zod.def,N=_.shape;if(Object.getOwnPropertySymbols(N).length&&J$($,v,I,g,"Symbol keys cannot be represented in JSON Schema"))return;I.type="object",I.properties={};for(let J in N)B$(I.properties,J,s(N[J],v,{...g,path:[...g.path,"properties",J]}));let U=[];for(let J of Object.keys(N)){let W=_.shape[J];if(v.io==="input"?UD(W)===void 0:W._zod.optout===void 0)U.push(J)}if(U.length>0)I.required=U;if(_.catchall?._zod.def.type==="never")I.additionalProperties=!1;else if(!_.catchall){if(v.io==="output")I.additionalProperties=!1}else if(_.catchall)I.additionalProperties=s(_.catchall,v,{...g,path:[...g.path,"additionalProperties"]})},vb=($,v,D,g)=>{let I=$._zod.def,_=I.inclusive===!1,N=I.options.map((b,U)=>s(b,v,{...g,path:[...g.path,_?"oneOf":"anyOf",U]}));if(_)D.oneOf=N;else D.anyOf=N},MW=($,v,D,g)=>{let I=$._zod.def,_=s(I.left,v,{...g,path:[...g.path,"allOf",0]}),N=s(I.right,v,{...g,path:[...g.path,"allOf",1]}),b=(J)=>("allOf"in J)&&Object.keys(J).length===1,U=[...b(_)?_.allOf:[_],...b(N)?N.allOf:[N]];D.allOf=U,v.intersections.push(U)},TW=($,v,D,g)=>{let I=D,_=$._zod.def;I.type="array";let N=v.target==="draft-2020-12"?"prefixItems":"items",b=v.target==="draft-2020-12"?"items":v.target==="openapi-3.0"?"items":"additionalItems",U=_.items.map((F,T)=>s(F,v,{...g,path:[...g.path,N,T]})),J=_.rest?s(_.rest,v,{...g,path:[...g.path,b,...v.target==="openapi-3.0"?[_.items.length]:[]]}):null,W=_.items.length;while(W>0){let F=_.items[W-1];if(!(v.io==="input"?UD(F)!==void 0:F._zod.optout==="optional"))break;W--}let Y=_.items.length,B=!_.rest;if(v.target==="draft-2020-12"){if(I.prefixItems=U,B)I.items=!1;else if(J)I.items=J;if(W>0)I.minItems=W;if(B)I.maxItems=Y}else if(v.target==="openapi-3.0"){if(I.items={anyOf:U},J)I.items.anyOf.push(J);if(W>0)I.minItems=W;if(B)I.maxItems=Y}else{if(I.items=U,B)I.additionalItems=!1;else if(J)I.additionalItems=J;if(W>0)I.minItems=W;if(B)I.maxItems=Y}let{minimum:j,maximum:K}=X$($);if(typeof j==="number")I.minItems=j;if(typeof K==="number")I.maxItems=K};function e2($,v,D){if(v.$ref){if(D.has(v))return v;D.add(v);let K=$.get(v)?.def;if(!K)return v;let F=e2($,K,D);return F===K?v:F}for(let K of["anyOf","oneOf"]){let F=v[K];if(!Array.isArray(F))continue;let T=F.map((V)=>e2($,V,D));if(T.some((V,Z)=>V!==F[Z]))v={...v,[K]:T}}let g=Array.isArray(v.type)?v.type:[v.type],I=!g.includes("string")&&g.some((K)=>K==="number"||K==="integer"),_=v.enum??(v.const!==void 0?[v.const]:void 0);if(!I&&!_?.some((K)=>typeof K==="number"))return v;let{minimum:N,maximum:b,exclusiveMinimum:U,exclusiveMaximum:J,multipleOf:W,format:Y,id:B,...j}=v;if(j.enum)j.enum=j.enum.map((K)=>typeof K==="number"?String(K):K);else if(typeof j.const==="number")j.const=String(j.const);if(!I)return j;if(j.type="string",!_)j.pattern=(g.includes("number")?_v:x_).source;return j}var s2=new WeakMap;function ej($){let v=new Map;for(let g of $.seen.values())if(g.def&&!v.has(g.schema))v.set(g.schema,g);let D=new Map;for(let g of s2.get($)??[]){let I=$.seen.get(g),_=(I?.def??I?.schema)?.propertyNames;if(!_||_===!0||D.has(_))continue;let N=e2(v,_,new Set);if(N!==_)D.set(_,N)}if(!D.size)return;for(let g of $.seen.values())for(let I of[g.schema,g.def]){let _=I&&D.get(I.propertyNames);if(_)I.propertyNames=_}}var SW=($,v,D,g)=>{let I=D,_=$._zod.def;I.type="object";let N=_.keyType,b=X$(N).patterns;if(_.mode==="loose"&&b&&b.size>0){let W=s(_.valueType,v,{...g,path:[...g.path,"patternProperties","*"]});I.patternProperties={};for(let Y of b)B$(I.patternProperties,tY(Y).source,W)}else{if(v.target==="draft-07"||v.target==="draft-2020-12"){I.propertyNames=s(_.keyType,v,{...g,path:[...g.path,"propertyNames"]});let W=s2.get(v);if(!W)W=[],s2.set(v,W),v.deferred.push(()=>ej(v));W.push($)}I.additionalProperties=s(_.valueType,v,{...g,path:[...g.path,"additionalProperties"]})}let U=N._zod.values,J=v.io==="input"&&UD(_.valueType)!==void 0;if(U&&!_.partial&&!J){let W=[...U].filter((Y)=>typeof Y==="string"||typeof Y==="number");if(W.length>0)I.required=W.map(String)}},AW=($,v,D,g)=>{let I=$._zod.def,_=s(I.innerType,v,g),N=v.seen.get($);if(v.target==="openapi-3.0")N.ref=I.innerType,D.nullable=!0;else D.anyOf=[_,{type:"null"}]},ZW=($,v,D,g)=>{let I=$._zod.def;s(I.innerType,v,g);let _=v.seen.get($);_.ref=I.innerType},LW=Symbol();function oY($,v,D,g,I){let _=!1,N=JSON.stringify($,(b,U)=>{if(typeof U!=="bigint")return U;return _=!0,null});if(!_)return JSON.parse(N);return J$(v,D,g,I,"BigInt defaults cannot be represented in JSON Schema"),LW}var EW=($,v,D,g)=>{let I=$._zod.def;s(I.innerType,v,g);let _=v.seen.get($);_.ref=I.innerType;let N=oY(I.defaultValue,$,v,D,g);if(N!==LW)D.default=N},VW=($,v,D,g)=>{let I=$._zod.def;s(I.innerType,v,g);let _=v.seen.get($);if(_.ref=I.innerType,v.io!=="input")return;let N=oY(I.defaultValue,$,v,D,g);if(N!==LW)D._prefault=N},kW=($,v,D,g)=>{let I=$._zod.def;s(I.innerType,v,g);let _=v.seen.get($);_.ref=I.innerType;let N;try{N=I.catchValue(void 0)}catch{J$($,v,D,g,"Dynamic catch values are not supported in JSON Schema");return}D.default=N},RW=($,v,D,g)=>{let I=$._zod.def,_=I.in._zod.traits.has("$ZodTransform"),N=v.io==="input"?_?I.out:I.in:I.out;s(N,v,g);let b=v.seen.get($);b.ref=N},CW=($,v,D,g)=>{let I=$._zod.def;s(I.innerType,v,g);let _=v.seen.get($);_.ref=I.innerType,D.readOnly=!0},xW=($,v,D,g)=>{let I=$._zod.def;s(I.innerType,v,g);let _=v.seen.get($);_.ref=I.innerType},Ib=($,v,D,g)=>{let I=$._zod.def;s(I.innerType,v,g);let _=v.seen.get($);_.ref=I.innerType},fW=($,v,D,g)=>{let I=$._zod.innerType;s(I,v,g);let _=v.seen.get($);_.ref=I},$b={string:$W,number:vW,boolean:IW,bigint:_W,symbol:DW,null:gW,undefined:NW,void:bW,never:UW,any:JW,unknown:XW,date:WW,enum:QW,literal:YW,nan:GW,template_literal:BW,file:jW,success:zW,custom:KW,function:OW,transform:HW,map:FW,set:PW,array:wW,object:qW,union:vb,intersection:MW,tuple:TW,record:SW,nullable:AW,nonoptional:ZW,default:EW,prefault:VW,catch:kW,pipe:RW,readonly:CW,promise:xW,optional:Ib,lazy:fW};function Z6($,v){if("_idmap"in $){let g=$,I=iv({...v,processors:$b}),_={};for(let U of g._idmap.entries()){let[J,W]=U;s(W,I)}let N={},b={registry:g,uri:v?.uri,defs:_};I.external=b;for(let U of g._idmap.entries()){let[J,W]=U;lv(I,W),B$(N,J,nv(I,W))}if(Object.keys(_).length>0){let U=I.target==="draft-2020-12"?"$defs":"definitions";N.__shared={[U]:_}}return{schemas:N}}let D=iv({...v,processors:$b});return s($,D),lv(D,$),nv(D,$)}class yW{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter($){this.ctx.counter=$}get seen(){return this.ctx.seen}constructor($){let v=$?.target??"draft-2020-12";if(v==="draft-4")v="draft-04";if(v==="draft-7")v="draft-07";this.ctx=iv({processors:$b,target:v,...$?.metadata&&{metadata:$.metadata},...$?.unrepresentable&&{unrepresentable:$.unrepresentable},...$?.override&&{override:$.override},...$?.io&&{io:$.io}})}process($,v={path:[],schemaPath:[]}){return s($,this.ctx,v)}emit($,v){if(v){if(v.cycles)this.ctx.cycles=v.cycles;if(v.reused)this.ctx.reused=v.reused;if(v.external)this.ctx.external=v.external}this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,lv(this.ctx,$);let D=nv(this.ctx,$),{"~standard":g,...I}=D;return I}}var aY={};var s4={};zv(s4,{xor:()=>n8,xid:()=>W8,void:()=>y8,uuidv7:()=>D8,uuidv6:()=>_8,uuidv4:()=>I8,uuid:()=>v8,url:()=>t4,unknown:()=>x,union:()=>E,undefined:()=>f8,ulid:()=>X8,uint64:()=>C8,uint32:()=>V8,tuple:()=>WQ,transform:()=>Zb,templateLiteral:()=>$G,symbol:()=>x8,superRefine:()=>xQ,success:()=>o8,stringbool:()=>UG,stringFormat:()=>q8,string:()=>X,strictObject:()=>l8,set:()=>d8,refine:()=>CQ,record:()=>L,readonly:()=>LQ,promise:()=>vG,preprocess:()=>Pv,prefault:()=>PQ,pipe:()=>Nb,partialRecord:()=>m8,optional:()=>C,object:()=>G,number:()=>S,nullish:()=>t8,nullable:()=>XD,null:()=>Jv,nonoptional:()=>wQ,never:()=>Ab,nativeEnum:()=>p8,nanoid:()=>b8,nan:()=>a8,meta:()=>NG,map:()=>r8,mac:()=>G8,looseRecord:()=>h8,looseObject:()=>u,literal:()=>P,lazy:()=>cv,ksuid:()=>Q8,keyof:()=>i8,jwt:()=>w8,json:()=>JG,ipv6:()=>B8,ipv4:()=>Y8,invertCodec:()=>s8,intersection:()=>e$,int64:()=>R8,int32:()=>E8,int:()=>gb,instanceof:()=>bG,iban:()=>P8,httpUrl:()=>g8,hostname:()=>M8,hex:()=>T8,hash:()=>A8,guid:()=>$8,function:()=>IG,float64:()=>L8,float32:()=>Z8,file:()=>c8,exactOptional:()=>zQ,enum:()=>l,emoji:()=>N8,email:()=>Jb,e164:()=>H8,discriminatedUnion:()=>pv,describe:()=>gG,date:()=>u8,custom:()=>DG,currencyCode:()=>S8,cuid2:()=>J8,cuid:()=>U8,creditCard:()=>F8,codec:()=>e8,cidrv6:()=>z8,cidrv4:()=>j8,check:()=>_G,catch:()=>TQ,boolean:()=>k,bigint:()=>k8,base64url:()=>O8,base64:()=>K8,array:()=>H,any:()=>Sb,_function:()=>IG,_default:()=>HQ,_ZodString:()=>bb,ZodXor:()=>bQ,ZodXID:()=>jb,ZodVoid:()=>gQ,ZodUnknown:()=>_Q,ZodUnion:()=>GD,ZodUndefined:()=>$Q,ZodUUID:()=>Uv,ZodURL:()=>WD,ZodULID:()=>Bb,ZodType:()=>h,ZodTuple:()=>XQ,ZodTransform:()=>jQ,ZodTemplateLiteral:()=>EQ,ZodSymbol:()=>sW,ZodSuccess:()=>qQ,ZodStringFormat:()=>$$,ZodString:()=>c4,ZodSet:()=>YQ,ZodRecord:()=>d4,ZodReadonly:()=>ZQ,ZodPromise:()=>kQ,ZodPreprocess:()=>AQ,ZodPrefault:()=>FQ,ZodPipe:()=>jD,ZodOptional:()=>BD,ZodObject:()=>YD,ZodNumberFormat:()=>V6,ZodNumber:()=>o4,ZodNullable:()=>KQ,ZodNull:()=>vQ,ZodNonOptional:()=>Eb,ZodNever:()=>DQ,ZodNanoID:()=>Qb,ZodNaN:()=>SQ,ZodMap:()=>QQ,ZodMAC:()=>oW,ZodLiteral:()=>GQ,ZodLazy:()=>VQ,ZodKSUID:()=>zb,ZodJWT:()=>Mb,ZodIntersection:()=>JQ,ZodInstanceOf:()=>fQ,ZodISOTime:()=>rv,ZodISODuration:()=>dv,ZodISODateTime:()=>mv,ZodISODate:()=>hv,ZodIPv6:()=>Ob,ZodIPv4:()=>Kb,ZodIBAN:()=>eW,ZodGUID:()=>Xb,ZodFunction:()=>RQ,ZodFile:()=>BQ,ZodExactOptional:()=>Lb,ZodEnum:()=>p4,ZodEmoji:()=>Wb,ZodEmail:()=>Ub,ZodE164:()=>qb,ZodDiscriminatedUnion:()=>UQ,ZodDefault:()=>OQ,ZodDate:()=>QD,ZodCustomStringFormat:()=>E6,ZodCustom:()=>KD,ZodCreditCard:()=>aW,ZodCodec:()=>zD,ZodCatch:()=>MQ,ZodCUID2:()=>Gb,ZodCUID:()=>Yb,ZodCIDRv6:()=>Fb,ZodCIDRv4:()=>Hb,ZodBoolean:()=>a4,ZodBigIntFormat:()=>Tb,ZodBigInt:()=>e4,ZodBase64URL:()=>wb,ZodBase64:()=>Pb,ZodArray:()=>NQ,ZodAny:()=>IQ});var _b={};zv(_b,{uppercase:()=>V4,trim:()=>u4,toUpperCase:()=>l4,toLowerCase:()=>i4,startsWith:()=>R4,slugify:()=>n4,size:()=>M6,regex:()=>L4,property:()=>sN,properties:()=>x4,positive:()=>tN,overwrite:()=>a$,normalize:()=>y4,nonpositive:()=>aN,nonnegative:()=>eN,negative:()=>oN,multipleOf:()=>yv,minSize:()=>bv,minLength:()=>Hv,mime:()=>f4,maxSize:()=>uv,maxLength:()=>T6,lte:()=>u$,lt:()=>gv,lowercase:()=>E4,length:()=>S6,includes:()=>k4,gte:()=>i$,gt:()=>Nv,endsWith:()=>C4});var eY=new WeakSet([Object.prototype,Error.prototype]);function Db($,v,D){Object.defineProperty($,v,{configurable:!0,enumerable:!1,get(){let g=D(this);return Object.defineProperty(this,v,{value:g,configurable:!0,writable:!0}),g},set(g){Object.defineProperty(this,v,{value:g,configurable:!0,writable:!0})}})}var sY=($,v)=>{ZU.init($,v),$.name="ZodError";let D=Object.getPrototypeOf($);if(eY.has(D))return;eY.add(D),Db(D,"format",(g)=>(I)=>V_(g,I)),Db(D,"flatten",(g)=>(I)=>E_(g,I)),Db(D,"addIssue",(g)=>(I)=>{g.issues.push(I),g.message=JSON.stringify(g.issues,B4,2)}),Db(D,"addIssues",(g)=>(I)=>{g.issues.push(...I),g.message=JSON.stringify(g.issues,B4,2)}),Object.defineProperty(D,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}})},$z=z("ZodError",sY),R$=z("ZodError",sY,void 0,{Parent:Error});var uW=H4(R$),iW=F4(R$),JD=P4(R$),lW=w4(R$),nW=ig(R$),mW=lg(R$),hW=ng(R$),rW=mg(R$),dW=hg(R$),pW=rg(R$),cW=dg(R$),tW=pg(R$);function Iz(){if(!Q$.localeError)N$(a_())}function L6(){if(!Q$.memoizer)N$({memoizer:o_()})}var h=z("ZodType",($,v)=>{return Iz(),m.init($,v),$.def=v,$.type=v.type,$},{check(...$){let v=this.def;return this.clone(w.mergeDefs(v,{checks:[...v.checks??[],...$.map((D)=>typeof D==="function"?{_zod:{check:D,def:{check:"custom"},onattach:[]}}:D)]}),{parent:!0})},with(...$){return this.check(...$)},clone($,v){return a(this,$,v)},brand(){return this},register($,v){return $.add(this,v),this},refine($,v){return this.check(CQ($,v))},superRefine($,v){return this.check(xQ($,v))},overwrite($){return this.check(a$($))},optional(){return C(this)},exactOptional(){return zQ(this)},nullable(){return XD(this)},nullish(){return C(XD(this))},nonoptional($){return wQ(this,$)},array(){return H(this)},or($){return E([this,$])},and($){return e$(this,$)},transform($){return Nb(this,Zb($))},default($){return HQ(this,$)},prefault($){return PQ(this,$)},catch($){return TQ(this,$)},pipe($){return Nb(this,$)},readonly(){return LQ(this)},describe($){let v=this.clone();return j$.add(v,{description:$}),v},meta(...$){if($.length===0)return j$.get(this);let v=this.clone();return j$.add(v,$[0]),v},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply($,...v){return v.length===0?$(this):$(this,...v)},get "~standard"(){return w.hide(this,"~standard",{...DN(this),jsonSchema:{input:m4(this,"input"),output:m4(this,"output")}})},set "~standard"($){w.own(this,"~standard",$)},parse:function $(v,D){return uW(this,v,D,{callee:$})},parseAsync:async function $(v,D){return await iW(this,v,D,{callee:$})},safeParse($,v){return JD(this,$,v)},async safeParseAsync($,v){return lW(this,$,v)},get spa(){return this?.safeParseAsync},set spa($){w.own(this,"spa",$)},validate($,v){return k_(this,$,v)},validateAsync($,v){return R_(this,$,v)},encode:function $(v,D){return nW(this,v,D,{callee:$})},decode:function $(v,D){return mW(this,v,D,{callee:$})},encodeAsync:async function $(v,D){return await hW(this,v,D,{callee:$})},decodeAsync:async function $(v,D){return await rW(this,v,D,{callee:$})},safeEncode($,v){return dW(this,$,v)},safeDecode($,v){return pW(this,$,v)},async safeEncodeAsync($,v){return cW(this,$,v)},async safeDecodeAsync($,v){return tW(this,$,v)},toJSONSchema($){return a2(this,{})($)},get description(){return j$.get(this)?.description},get _def(){return this._zod.def}}),bb=z("_ZodString",($,v)=>{F6.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>$W($,D,g,I)},w.derived({format:($)=>X$($).format??null,minLength:($)=>X$($).minimum??null,maxLength:($)=>X$($).maximum??null},{regex(...$){return this.check(L4(...$))},includes(...$){return this.check(k4(...$))},startsWith(...$){return this.check(R4(...$))},endsWith(...$){return this.check(C4(...$))},min(...$){return this.check(Hv(...$))},max(...$){return this.check(T6(...$))},length(...$){return this.check(S6(...$))},nonempty(...$){return this.check(Hv(1,...$))},lowercase($){return this.check(E4($))},uppercase($){return this.check(V4($))},trim(){return this.check(u4())},normalize(...$){return this.check(y4(...$))},toLowerCase(){return this.check(i4())},toUpperCase(){return this.check(l4())},slugify(){return this.check(n4())}})),c4=z("ZodString",($,v)=>{F6.init($,v),bb.init($,v)},{email($){return this.check(AN(Ub,$))},url($){return this.check(ID(WD,$))},jwt($){return this.check(cN(Mb,$))},emoji($){return this.check(RN(Wb,$))},guid($){return this.check(ZN(Xb,$))},uuid($){return this.check(LN(Uv,$))},uuidv4($){return this.check(EN(Uv,$))},uuidv6($){return this.check(VN(Uv,$))},uuidv7($){return this.check(kN(Uv,$))},nanoid($){return this.check(CN(Qb,$))},cuid($){return this.check(xN(Yb,$))},cuid2($){return this.check(fN(Gb,$))},ulid($){return this.check(yN(Bb,$))},base64($){return this.check(rN(Pb,$))},base64url($){return this.check(dN(wb,$))},xid($){return this.check(uN(jb,$))},ksuid($){return this.check(iN(zb,$))},ipv4($){return this.check(lN(Kb,$))},ipv6($){return this.check(nN(Ob,$))},cidrv4($){return this.check(mN(Hb,$))},cidrv6($){return this.check(hN(Fb,$))},e164($){return this.check(pN(qb,$))},datetime($){return this.check(_D(mv,$))},date($){return this.check(DD(hv,$))},time($){return this.check(gD(rv,$))},duration($){return this.check(ND(dv,$))}});function X($){return Y2(c4,$)}var $$=z("ZodStringFormat",($,v)=>{e.init($,v),bb.init($,v)}),mv=z("ZodISODateTime",($,v)=>{tJ.init($,v),$$.init($,v)}),hv=z("ZodISODate",($,v)=>{oJ.init($,v),$$.init($,v)}),rv=z("ZodISOTime",($,v)=>{aJ.init($,v),$$.init($,v)}),dv=z("ZodISODuration",($,v)=>{eJ.init($,v),$$.init($,v)}),Ub=z("ZodEmail",($,v)=>{yJ.init($,v),$$.init($,v)});function Jb($){return AN(Ub,$)}var Xb=z("ZodGUID",($,v)=>{xJ.init($,v),$$.init($,v)});function $8($){return ZN(Xb,$)}var Uv=z("ZodUUID",($,v)=>{fJ.init($,v),$$.init($,v)});function v8($){return LN(Uv,$)}function I8($){return EN(Uv,$)}function _8($){return VN(Uv,$)}function D8($){return kN(Uv,$)}var WD=z("ZodURL",($,v)=>{lJ.init($,v),$$.init($,v)});function t4($){return ID(WD,$)}function g8($){return ID(WD,{protocol:C_,hostname:eU,...w.normalizeParams($)})}var Wb=z("ZodEmoji",($,v)=>{nJ.init($,v),$$.init($,v)});function N8($){return RN(Wb,$)}var Qb=z("ZodNanoID",($,v)=>{mJ.init($,v),$$.init($,v)});function b8($){return CN(Qb,$)}var Yb=z("ZodCUID",($,v)=>{hJ.init($,v),$$.init($,v)});function U8($){return xN(Yb,$)}var Gb=z("ZodCUID2",($,v)=>{rJ.init($,v),$$.init($,v)});function J8($){return fN(Gb,$)}var Bb=z("ZodULID",($,v)=>{dJ.init($,v),$$.init($,v)});function X8($){return yN(Bb,$)}var jb=z("ZodXID",($,v)=>{pJ.init($,v),$$.init($,v)});function W8($){return uN(jb,$)}var zb=z("ZodKSUID",($,v)=>{cJ.init($,v),$$.init($,v)});function Q8($){return iN(zb,$)}var Kb=z("ZodIPv4",($,v)=>{sJ.init($,v),$$.init($,v)});function Y8($){return lN(Kb,$)}var oW=z("ZodMAC",($,v)=>{v0.init($,v),$$.init($,v)});function G8($){return B2(oW,$)}var Ob=z("ZodIPv6",($,v)=>{$0.init($,v),$$.init($,v)});function B8($){return nN(Ob,$)}var Hb=z("ZodCIDRv4",($,v)=>{I0.init($,v),$$.init($,v)});function j8($){return mN(Hb,$)}var Fb=z("ZodCIDRv6",($,v)=>{_0.init($,v),$$.init($,v)});function z8($){return hN(Fb,$)}var Pb=z("ZodBase64",($,v)=>{D0.init($,v),$$.init($,v)});function K8($){return rN(Pb,$)}var wb=z("ZodBase64URL",($,v)=>{g0.init($,v),$$.init($,v)});function O8($){return dN(wb,$)}var qb=z("ZodE164",($,v)=>{N0.init($,v),$$.init($,v)});function H8($){return pN(qb,$)}var aW=z("ZodCreditCard",($,v)=>{b0.init($,v),$$.init($,v)});function F8($){return j2(aW,$)}var eW=z("ZodIBAN",($,v)=>{U0.init($,v),$$.init($,v)});function P8($){return z2(eW,$)}var Mb=z("ZodJWT",($,v)=>{J0.init($,v),$$.init($,v)});function w8($){return cN(Mb,$)}var E6=z("ZodCustomStringFormat",($,v)=>{X0.init($,v),$$.init($,v)});function q8($,v,D={}){return A6(E6,$,v,D)}function M8($){return A6(E6,"hostname",aU,$)}function T8($){return A6(E6,"hex",QJ,$)}function S8($){return A6(E6,"currency_code",$J,$)}function A8($,v){let D=v?.enc??"hex",g=`${$}_${D}`,I=d$[g];if(!I)throw Error(`Unrecognized hash format: ${g}`);return A6(E6,g,I,v)}var o4=z("ZodNumber",($,v)=>{GN.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>vW($,D,g,I),$.isFinite=!0},w.derived({minValue:($)=>{let{minimum:v,exclusiveMinimum:D}=X$($);return Math.max(v??Number.NEGATIVE_INFINITY,D??Number.NEGATIVE_INFINITY)},maxValue:($)=>{let{maximum:v,exclusiveMaximum:D}=X$($);return Math.min(v??Number.POSITIVE_INFINITY,D??Number.POSITIVE_INFINITY)},isInt:($)=>{let{isInt:v,multipleOf:D}=X$($);return!!v||!!D?.some(Number.isSafeInteger)},format:($)=>X$($).format??null},{gt($,v){return this.check(Nv($,v))},gte($,v){return this.check(i$($,v))},min($,v){return this.check(i$($,v))},lt($,v){return this.check(gv($,v))},lte($,v){return this.check(u$($,v))},max($,v){return this.check(u$($,v))},int($){return this.check(gb($))},safe($){return this.check(gb($))},positive($){return this.check(Nv(0,$))},nonnegative($){return this.check(i$(0,$))},negative($){return this.check(gv(0,$))},nonpositive($){return this.check(u$(0,$))},multipleOf($,v){return this.check(yv($,v))},step($,v){return this.check(yv($,v))},finite(){return this}}));function S($){return O2(o4,$)}var V6=z("ZodNumberFormat",($,v)=>{W0.init($,v),o4.init($,v)});function gb($){return F2(V6,$)}function Z8($){return P2(V6,$)}function L8($){return w2(V6,$)}function E8($){return q2(V6,$)}function V8($){return M2(V6,$)}var a4=z("ZodBoolean",($,v)=>{h_.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>IW($,D,g,I)});function k($){return T2(a4,$)}var e4=z("ZodBigInt",($,v)=>{BN.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>_W($,D,g,I)},w.derived({minValue:($)=>X$($).minimum??null,maxValue:($)=>X$($).maximum??null,format:($)=>X$($).format??null},{gte($,v){return this.check(i$($,v))},min($,v){return this.check(i$($,v))},gt($,v){return this.check(Nv($,v))},lt($,v){return this.check(gv($,v))},lte($,v){return this.check(u$($,v))},max($,v){return this.check(u$($,v))},positive($){return this.check(Nv(BigInt(0),$))},negative($){return this.check(gv(BigInt(0),$))},nonpositive($){return this.check(u$(BigInt(0),$))},nonnegative($){return this.check(i$(BigInt(0),$))},multipleOf($,v){return this.check(yv($,v))}}));function k8($){return A2(e4,$)}var Tb=z("ZodBigIntFormat",($,v)=>{Q0.init($,v),e4.init($,v)});function R8($){return L2(Tb,$)}function C8($){return E2(Tb,$)}var sW=z("ZodSymbol",($,v)=>{Y0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>DW($,D,g,I)});function x8($){return V2(sW,$)}var $Q=z("ZodUndefined",($,v)=>{G0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>NW($,D,g,I)});function f8($){return k2($Q,$)}var vQ=z("ZodNull",($,v)=>{B0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>gW($,D,g,I)});function Jv($){return R2(vQ,$)}var IQ=z("ZodAny",($,v)=>{j0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>JW($,D,g,I)});function Sb(){return C2(IQ)}var _Q=z("ZodUnknown",($,v)=>{z0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>XW($,D,g,I)});function x(){return x2(_Q)}var DQ=z("ZodNever",($,v)=>{K0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>UW($,D,g,I)});function Ab($){return f2(DQ,$)}var gQ=z("ZodVoid",($,v)=>{O0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>bW($,D,g,I)});function y8($){return y2(gQ,$)}var QD=z("ZodDate",($,v)=>{H0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>WW($,D,g,I),$.min=(D,g)=>$.check(i$(D,g)),$.max=(D,g)=>$.check(u$(D,g))},w.derived({minDate:($)=>{let{minimum:v}=X$($);return v?new Date(v):null},maxDate:($)=>{let{maximum:v}=X$($);return v?new Date(v):null}},{}));function u8($){return u2(QD,$)}var NQ=z("ZodArray",($,v)=>{L6(),P0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>wW($,D,g,I),$.element=v.element},{min($,v){return this.check(Hv($,v))},nonempty($){return this.check(Hv(1,$))},max($,v){return this.check(T6($,v))},length($,v){return this.check(S6($,v))},unwrap(){return this.element}});function H($,v){return n2(NQ,$,v)}function i8($){let v=$._zod.def.shape;return l(Object.keys(v))}var YD=z("ZodObject",($,v)=>{L6(),w0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>qW($,D,g,I),w.installLazyProp($,"shape",(D)=>D._zod.def.shape,!1)},{keyof(){return l(Object.keys(this._zod.def.shape))},catchall($){return this.clone(w.mergeDefs(this._zod.def,{catchall:$}))},passthrough(){return this.clone(w.mergeDefs(this._zod.def,{catchall:x()}))},loose(){return this.clone(w.mergeDefs(this._zod.def,{catchall:x()}))},strict(){return this.clone(w.mergeDefs(this._zod.def,{catchall:Ab()}))},strip(){return this.clone(w.mergeDefs(this._zod.def,{catchall:void 0}))},extend($){return w.extend(this,$)},safeExtend($){return w.safeExtend(this,$)},merge($){return w.merge(this,$)},pick($){return w.pick(this,$)},omit($){return w.omit(this,$)},partial(...$){return w.partial(BD,this,$[0])},exactPartial(...$){return w.partial(Lb,this,$[0],"exactPartial")},required(...$){return w.required(Eb,this,$[0])}});function G($,v){let D={type:"object",shape:$??{},...w.normalizeParams(v)};return new YD(D)}function l8($,v){return new YD({type:"object",shape:$,catchall:Ab(),...w.normalizeParams(v)})}function u($,v){return new YD({type:"object",shape:$,catchall:x(),...w.normalizeParams(v)})}var GD=z("ZodUnion",($,v)=>{r_.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>vb($,D,g,I),$.options=v.options});function E($,v){return new GD({type:"union",options:$,...w.normalizeParams(v)})}var bQ=z("ZodXor",($,v)=>{GD.init($,v),q0.init($,v),$._zod.processJSONSchema=(D,g,I)=>vb($,D,g,I),$.options=v.options});function n8($,v){return new bQ({type:"union",options:$,inclusive:!1,...w.normalizeParams(v)})}var UQ=z("ZodDiscriminatedUnion",($,v)=>{GD.init($,v),T0.init($,v)});function pv($,v,D){return new UQ({type:"union",options:v,discriminator:$,...w.normalizeParams(D)})}var JQ=z("ZodIntersection",($,v)=>{S0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>MW($,D,g,I)});function e$($,v){return new JQ({type:"intersection",left:$,right:v})}var XQ=z("ZodTuple",($,v)=>{L6(),jN.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>TW($,D,g,I)},{rest($){return this.clone({...this._zod.def,rest:$})},partial(){let $=this._zod.def;if($.checks?.length)throw Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...$,items:$.items.map((v)=>new BD({type:"optional",innerType:v}))})}});function WQ($,v,D){let g=v instanceof m,I=g?D:v;return new XQ({type:"tuple",items:$,rest:g?v:null,...w.normalizeParams(I)})}var d4=z("ZodRecord",($,v)=>{L6(),A0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>SW($,D,g,I),$.keyType=v.keyType,$.valueType=v.valueType});function L($,v,D){if(!v||!v._zod)return new d4({type:"record",keyType:X(),valueType:$,...w.normalizeParams(v)});return new d4({type:"record",keyType:$,valueType:v,...w.normalizeParams(D)})}function m8($,v,D){return new d4({type:"record",keyType:$,valueType:v,...w.normalizeParams(D),partial:!0})}function h8($,v,D){return new d4({type:"record",keyType:$,valueType:v,mode:"loose",...w.normalizeParams(D)})}var QQ=z("ZodMap",($,v)=>{L6(),Z0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>FW($,D,g,I),$.keyType=v.keyType,$.valueType=v.valueType,$.min=(...D)=>$.check(bv(...D)),$.nonempty=(D)=>$.check(bv(1,D)),$.max=(...D)=>$.check(uv(...D)),$.size=(...D)=>$.check(M6(...D))});function r8($,v,D){return new QQ({type:"map",keyType:$,valueType:v,...w.normalizeParams(D)})}var YQ=z("ZodSet",($,v)=>{L6(),L0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>PW($,D,g,I),$.min=(...D)=>$.check(bv(...D)),$.nonempty=(D)=>$.check(bv(1,D)),$.max=(...D)=>$.check(uv(...D)),$.size=(...D)=>$.check(M6(...D))});function d8($,v){return new YQ({type:"set",valueType:$,...w.normalizeParams(v)})}var p4=z("ZodEnum",($,v)=>{E0.init($,v),h.init($,v),$._zod.processJSONSchema=(g,I,_)=>QW($,g,I,_),$.enum=v.entries,$.options=[...$._zod.values];let D=new Set(Object.keys(v.entries));$.extract=(g,I)=>{let _={};for(let N of g)if(D.has(N))_[N]=v.entries[N];else throw Error(`Key ${N} not found in enum`);return new p4({...v,checks:[],...w.normalizeParams(I),entries:_})},$.exclude=(g,I)=>{let _={...v.entries};for(let N of g)if(D.has(N))delete _[N];else throw Error(`Key ${N} not found in enum`);return new p4({...v,checks:[],...w.normalizeParams(I),entries:_})}});function l($,v){let D=Array.isArray($)?Object.fromEntries($.map((g)=>[g,g])):$;return new p4({type:"enum",entries:D,...w.normalizeParams(v)})}function p8($,v){return new p4({type:"enum",entries:$,...w.normalizeParams(v)})}var GQ=z("ZodLiteral",($,v)=>{V0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>YW($,D,g,I),$.values=new Set(v.values),Object.defineProperty($,"value",{get(){if(v.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return v.values[0]}})});function P($,v){return new GQ({type:"literal",values:Array.isArray($)?$:[$],...w.normalizeParams(v)})}var BQ=z("ZodFile",($,v)=>{k0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>jW($,D,g,I),$.min=(D,g)=>$.check(bv(D,g)),$.max=(D,g)=>$.check(uv(D,g)),$.mime=(D,g)=>$.check(f4(Array.isArray(D)?D:[D],g))});function c8($){return m2(BQ,$)}var jQ=z("ZodTransform",($,v)=>{L6(),R0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>HW($,D,g,I),$._zod.parse=(D,g)=>{if(g.direction==="backward")throw new O6($.constructor.name);D.addIssue=(_)=>{if(typeof _==="string")D.issues.push(w.issue(_,D.value,v));else{let N=_;if(N.fatal)N.continue=!1;if(N.code??(N.code="custom"),!("input"in N))N.input=D.value;N.inst??(N.inst=$),D.issues.push(w.issue(N))}};let I=v.transform(D.value,D);if(I instanceof Promise)return I.then((_)=>{return D.value=_,D});return D.value=I,D}});function Zb($){return new jQ({type:"transform",transform:$})}var BD=z("ZodOptional",($,v)=>{zN.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>Ib($,D,g,I),$.unwrap=()=>$._zod.def.innerType});function C($){return new BD({type:"optional",innerType:$})}var Lb=z("ZodExactOptional",($,v)=>{C0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>Ib($,D,g,I),$.unwrap=()=>$._zod.def.innerType});function zQ($){return new Lb({type:"optional",innerType:$})}var KQ=z("ZodNullable",($,v)=>{x0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>AW($,D,g,I),$.unwrap=()=>$._zod.def.innerType});function XD($){return new KQ({type:"nullable",innerType:$})}function t8($){return C(XD($))}var OQ=z("ZodDefault",($,v)=>{f0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>EW($,D,g,I),$.unwrap=()=>$._zod.def.innerType,$.removeDefault=$.unwrap});function HQ($,v){return new OQ({type:"default",innerType:$,get defaultValue(){return typeof v==="function"?v():w.shallowClone(v)}})}var FQ=z("ZodPrefault",($,v)=>{y0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>VW($,D,g,I),$.unwrap=()=>$._zod.def.innerType});function PQ($,v){return new FQ({type:"prefault",innerType:$,get defaultValue(){return typeof v==="function"?v():w.shallowClone(v)}})}var Eb=z("ZodNonOptional",($,v)=>{u0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>ZW($,D,g,I),$.unwrap=()=>$._zod.def.innerType});function wQ($,v){return new Eb({type:"nonoptional",innerType:$,...w.normalizeParams(v)})}var qQ=z("ZodSuccess",($,v)=>{i0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>zW($,D,g,I),$.unwrap=()=>$._zod.def.innerType});function o8($){return new qQ({type:"success",innerType:$})}var MQ=z("ZodCatch",($,v)=>{l0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>kW($,D,g,I),$.unwrap=()=>$._zod.def.innerType,$.removeCatch=$.unwrap});function TQ($,v){return new MQ({type:"catch",innerType:$,catchValue:typeof v==="function"?v:w.constantCatch(v)})}var SQ=z("ZodNaN",($,v)=>{n0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>GW($,D,g,I)});function a8($){return l2(SQ,$)}var jD=z("ZodPipe",($,v)=>{KN.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>RW($,D,g,I),$.in=v.in,$.out=v.out});function Nb($,v){return new jD({type:"pipe",in:$,out:v})}var zD=z("ZodCodec",($,v)=>{jD.init($,v),d_.init($,v)});function e8($,v,D){return new zD({type:"pipe",in:$,out:v,transform:D.decode,reverseTransform:D.encode})}function s8($){let v=$._zod.def;return new zD({type:"pipe",in:v.out,out:v.in,transform:v.reverseTransform,reverseTransform:v.transform})}var AQ=z("ZodPreprocess",($,v)=>{jD.init($,v),m0.init($,v)}),ZQ=z("ZodReadonly",($,v)=>{h0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>CW($,D,g,I),$.unwrap=()=>$._zod.def.innerType});function LQ($){return new ZQ({type:"readonly",innerType:$})}var EQ=z("ZodTemplateLiteral",($,v)=>{r0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>BW($,D,g,I)});function $G($,v){return new EQ({type:"template_literal",parts:$,...w.normalizeParams(v)})}var VQ=z("ZodLazy",($,v)=>{p_.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>fW($,D,g,I),$.unwrap=()=>$._zod.def.getter()});function cv($){return new VQ({type:"lazy",getter:$})}var kQ=z("ZodPromise",($,v)=>{p0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>xW($,D,g,I),$.unwrap=()=>$._zod.def.innerType});function vG($){return new kQ({type:"promise",innerType:$})}var RQ=z("ZodFunction",($,v)=>{d0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>OW($,D,g,I)});function IG($){return new RQ({type:"function",input:Array.isArray($?.input)?WQ($?.input):$?.input??H(x()),output:$?.output??x()})}var KD=z("ZodCustom",($,v)=>{c0.init($,v),h.init($,v),$._zod.processJSONSchema=(D,g,I)=>KW($,D,g,I)});function _G($){let v=new v$({check:"custom"});return v._zod.check=$,v}function DG($,v){return h2(KD,$??(()=>!0),v)}function CQ($,v={}){return r2(KD,$,v)}function xQ($,v){return d2($,v)}var gG=p2,NG=c2,fQ=z("ZodInstanceOf",($,v)=>{KD.init($,v)},{properties($,v){return this.check(x4($,v))}});function bG($,v={}){let D=new fQ({type:"custom",check:"custom",fn:(g)=>g instanceof $,abort:!0,...w.normalizeParams(v)});return D._zod.bag.Class=$,D._zod.check=(g)=>{if(!(g.value instanceof $))g.issues.push({code:"invalid_type",expected:$.name,input:g.value,inst:D,path:[...D._zod.def.path??[]]})},D}var UG=(...$)=>t2({Codec:zD,Boolean:a4,String:c4},...$);function JG($){let v=cv(()=>{return E([X($),S(),k(),Jv(),H(v),L(X(),v)])});return v}function Pv($,v){return new AQ({type:"pipe",in:Zb($),out:v})}var uQ={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function _z($){N$({customError:$})}function Dz(){return N$().customError}var yQ;(function($){})(yQ||(yQ={}));var p$={};zv(p$,{time:()=>bz,duration:()=>Uz,datetime:()=>gz,date:()=>Nz,ZodISOTime:()=>rv,ZodISODuration:()=>dv,ZodISODateTime:()=>mv,ZodISODate:()=>hv});function gz($){return _D(mv,$)}function Nz($){return DD(hv,$)}function bz($){return gD(rv,$)}function Uz($){return ND(dv,$)}var R={...s4,..._b,iso:p$},Jz=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function Xz($,v){let D=$.$schema;if(D==="https://json-schema.org/draft/2020-12/schema")return"draft-2020-12";if(D==="http://json-schema.org/draft-07/schema#")return"draft-7";if(D==="http://json-schema.org/draft-04/schema#")return"draft-4";return v??"draft-2020-12"}function XG($,v){return $.map((D,g)=>gg).check((g)=>{let I=g.value;if(typeof I!=="object"||I===null||Array.isArray(I))return;let _=Object.getOwnPropertyNames(I);if(v.minProperties!==void 0&&_.length=${v.minProperties} properties`,input:I,inst:$,continue:!0});if(v.maxProperties!==void 0&&_.length>v.maxProperties)g.issues.push({origin:"object",code:"too_big",maximum:v.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${v.maxProperties} properties`,input:I,inst:$,continue:!0});if(v.keySchema)for(let N of _){let b=v.keySchema.safeParse(N);if(b.success)continue;g.issues.push({code:"invalid_key",origin:"record",issues:b.error.issues,input:N,path:[N],continue:!0})}}).pipe($)}function iQ($,v){if($===null)return"z";let D=typeof $;if(D!=="object"){if(D==="number"&&Number.isNaN($))return null;let g=String($);return`${D[0]}${g.length}:${g}`}if(v.has($))return null;v.add($);try{if(Array.isArray($)){let _=[];for(let N of $){let b=iQ(N,v);if(b===null)return null;_.push(b)}return`a${_.length}:[${_.join(",")}]`}let g=Object.keys($).sort(),I=[];for(let _ of g){let N=iQ($[_],v);if(N===null)return null;I.push(`${_.length}:${_}=${N}`)}return`o${I.length}:{${I.join(",")}}`}finally{v.delete($)}}var Gz=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),Bz=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function OD($){if(typeof $!=="object"||$===null)return!1;if(Array.isArray($))return $.some(OD);if(typeof $.$ref==="string")return!0;return Object.entries($).some(([v,D])=>{if(Gz.has(v))return OD(D);if(!Bz.has(v)||typeof D!=="object"||D===null)return!1;return Object.values(D).some(OD)})}function WG($){return $===1?"element":"elements"}function jz($,v){return R.transform((g)=>g).check((g)=>{let I=g.value;if(!Array.isArray(I))return;if(v.uniqueItems===!0){let _=new Map;for(let N=0;N=N)break;if(b<_)g.issues.push({code:"custom",message:`Array must contain at least ${_} matching ${WG(_)}; found ${b}`,input:I,continue:!0});if(v.maxContains!==void 0&&b>v.maxContains)g.issues.push({code:"custom",message:`Array must contain at most ${v.maxContains} matching ${WG(v.maxContains)}`,input:I,continue:!0})}}).pipe($)}function QG($,v){if($===!1)return;if($===void 0||$===!0)return R.any();return A$($,v)}var zz=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function YG($,v){if($.not!==void 0){if(typeof $.not==="object"&&Object.keys($.not).length===0)return R.never();throw Error("not is not supported in Zod (except { not: {} } for never)")}if($.unevaluatedItems!==void 0)throw Error("unevaluatedItems is not supported");if($.unevaluatedProperties!==void 0)throw Error("unevaluatedProperties is not supported");if($.if!==void 0||$.then!==void 0||$.else!==void 0)throw Error("Conditional schemas (if/then/else) are not supported");if($.dependentSchemas!==void 0||$.dependentRequired!==void 0)throw Error("dependentSchemas and dependentRequired are not supported");if($.$ref){let I=$.$ref;if(v.refs.has(I))return v.refs.get(I);if(v.processing.has(I))return R.lazy(()=>{if(!v.refs.has(I))throw Error(`Circular reference not resolved: ${I}`);return v.refs.get(I)});v.processing.add(I);let _=Qz(I,v),N=A$(_,v);return v.refs.set(I,N),v.processing.delete(I),N}if($.enum!==void 0){let I=$.enum;if(v.version==="openapi-3.0"&&$.nullable===!0&&I.length===1&&I[0]===null)return R.null();if(I.length===0)return R.never();if(I.length===1)return R.literal(I[0]);if(I.every((N)=>typeof N==="string"))return R.enum(I);let _=I.map((N)=>R.literal(N));if(_.length<2)return _[0];return R.union([_[0],_[1],..._.slice(2)])}if($.const!==void 0)return R.literal($.const);let D=$.type;if(Array.isArray(D)){let I=D.map((_)=>{let N={...$,type:_};return YG(N,v)});if(I.length===0)return R.never();if(I.length===1)return I[0];return R.union(I)}if(!D)return R.any();let g;switch(D){case"string":{let I=R.string();if($.format){let _=$.format;if(_==="email")I=I.check(R.email());else if(_==="uri"||_==="uri-reference")I=I.check(R.url());else if(_==="uuid"||_==="guid")I=I.check(R.uuid());else if(_==="date-time")I=I.check(R.iso.datetime({offset:!0}));else if(_==="date")I=I.check(R.iso.date());else if(_==="time")I=I.check(R.regex(zz));else if(_==="duration")I=I.check(R.iso.duration());else if(_==="hostname")I=I.check(R.hostname());else if(_==="ipv4")I=I.check(R.ipv4());else if(_==="ipv6")I=I.check(R.ipv6());else if(_==="mac")I=I.check(R.mac());else if(_==="cidr")I=I.check(R.cidrv4());else if(_==="cidr-v6")I=I.check(R.cidrv6());else if(_==="base64")I=I.check(R.base64());else if(_==="base64url")I=I.check(R.base64url());else if(_==="e164")I=I.check(R.e164());else if(_==="credit_card")I=I.check(R.creditCard());else if(_==="iban")I=I.check(R.iban());else if(_==="jwt")I=I.check(R.jwt());else if(_==="emoji")I=I.check(R.emoji());else if(_==="nanoid")I=I.check(R.nanoid());else if(_==="cuid")I=I.check(R.cuid());else if(_==="cuid2")I=I.check(R.cuid2());else if(_==="ulid")I=I.check(R.ulid());else if(_==="xid")I=I.check(R.xid());else if(_==="ksuid")I=I.check(R.ksuid())}if(typeof $.minLength==="number")I=I.min($.minLength);if(typeof $.maxLength==="number")I=I.max($.maxLength);if($.pattern)I=I.regex(new RegExp($.pattern));g=I;break}case"number":case"integer":{let I=D==="integer"?R.number().int():R.number();if(typeof $.minimum==="number"&&$.exclusiveMinimum!==!0)I=I.min($.minimum);if(typeof $.maximum==="number"&&$.exclusiveMaximum!==!0)I=I.max($.maximum);if(typeof $.exclusiveMinimum==="number")I=I.gt($.exclusiveMinimum);else if($.exclusiveMinimum===!0&&typeof $.minimum==="number")I=I.gt($.minimum);if(typeof $.exclusiveMaximum==="number")I=I.lt($.exclusiveMaximum);else if($.exclusiveMaximum===!0&&typeof $.maximum==="number")I=I.lt($.maximum);if(typeof $.multipleOf==="number")I=I.multipleOf($.multipleOf);g=I;break}case"boolean":{g=R.boolean();break}case"null":{g=R.null();break}case"object":{let I={},_=$.properties||{},N=new Set($.required||[]),b=typeof $.additionalProperties==="object"?A$($.additionalProperties,v):void 0;for(let[Y,B]of Object.entries(_)){let j=A$(B,v);B$(I,Y,N.has(Y)?j:j.optional())}if($.patternProperties){let Y=$.patternProperties,B=Object.keys(Y),j=[];for(let F of B){let T=A$(Y[F],v),V=R.string().regex(new RegExp(F));j.push(R.looseRecord(V,T))}let K=[];if(Object.keys(I).length>0)K.push(R.object(I).passthrough());if(K.push(...j),K.length===0)g=R.object({}).passthrough();else if(K.length===1)g=K[0];else{let F=R.intersection(K[0],K[1]);for(let T=2;Tnew RegExp(Z)),V=g;g=g.check((Z)=>{if(!h$(Z.value))return;let f=[];for(let r of Object.keys(Z.value)){if(F.includes(r))continue;if(T.some((t)=>t.test(r)))continue;f.push(r)}if(f.length)Z.issues.push({code:"unrecognized_keys",keys:f,input:Z.value,inst:V})})}}else{let Y=R.object(I);if($.additionalProperties===!1)g=Y.strict();else if(b)g=Y.catchall(b);else g=Y.passthrough()}let U=$.propertyNames!==void 0&&$.propertyNames!==!0,J=typeof $.minProperties==="number"?$.minProperties:void 0,W=typeof $.maxProperties==="number"?$.maxProperties:void 0;if(U||J!==void 0||W!==void 0){let Y;if(U){let B=typeof $.propertyNames==="object"&&$.propertyNames.type===void 0?{type:"string",...$.propertyNames}:$.propertyNames;Y=A$(B,v)}g=Yz(g,{keySchema:Y,minProperties:J,maxProperties:W})}break}case"array":{let{prefixItems:I,items:_}=$;if(I&&Array.isArray(I)){let N=typeof $.minItems==="number"?$.minItems:0,b=I.map((Y)=>A$(Y,v)),U=XG(b,N),J=!Array.isArray(_)?QG(_,v):void 0,W=R.tuple(U);if(g=J?W.rest(J):W,typeof $.minItems==="number")g=g.check(R.minLength($.minItems));if(typeof $.maxItems==="number")g=g.check(R.maxLength($.maxItems))}else if(Array.isArray(_)){let N=typeof $.minItems==="number"?$.minItems:0,b=_.map((Y)=>A$(Y,v)),U=XG(b,N),J=QG($.additionalItems,v),W=R.tuple(U);if(g=J?W.rest(J):W,typeof $.minItems==="number")g=g.check(R.minLength($.minItems));if(typeof $.maxItems==="number")g=g.check(R.maxLength($.maxItems))}else if(_!==void 0){let N=A$(_,v),b=R.array(N);if(typeof $.minItems==="number")b=b.min($.minItems);if(typeof $.maxItems==="number")b=b.max($.maxItems);g=b}else g=R.array(R.any());if($.uniqueItems===!0||$.contains!==void 0)g=jz(g,{uniqueItems:$.uniqueItems===!0,containsSchema:$.contains!==void 0?A$($.contains,v):void 0,minContains:typeof $.minContains==="number"?$.minContains:void 0,maxContains:typeof $.maxContains==="number"?$.maxContains:void 0});break}default:throw Error(`Unsupported type: ${D}`)}return g}function A$($,v){if(typeof $==="boolean")return $?R.any():R.never();let D=YG($,v),g=$.type||$.enum!==void 0||$.const!==void 0;if($.anyOf&&Array.isArray($.anyOf)){let b=$.anyOf.map((J)=>A$(J,v)),U=R.union(b);D=g?R.intersection(D,U):U}if($.oneOf&&Array.isArray($.oneOf)){let b=$.oneOf.map((J)=>A$(J,v)),U=R.xor(b);D=g?R.intersection(D,U):U}if($.allOf&&Array.isArray($.allOf))if($.allOf.length===0)D=g?D:R.any();else{let b=g?D:A$($.allOf[0],v),U=g?0:1;for(let J=U;J<$.allOf.length;J++)b=R.intersection(b,A$($.allOf[J],v));D=b}if($.nullable===!0&&v.version==="openapi-3.0")D=R.nullable(D);if($.readOnly===!0)D=R.readonly(D);if($.default!==void 0)D=D.default($.default);let I={},_=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let b of _)if(b in $)I[b]=$[b];let N=["contentEncoding","contentMediaType","contentSchema"];for(let b of N)if(b in $)I[b]=$[b];if($.type==="object"&&$.$ref===void 0){if($.propertyNames!==void 0&&!OD($.propertyNames))I.propertyNames=$.propertyNames;for(let b of["minProperties","maxProperties"])if($[b]!==void 0)I[b]=$[b]}if($.type==="array"&&$.$ref===void 0){if($.contains!==void 0&&!OD($.contains))I.contains=$.contains;for(let b of["uniqueItems","minContains","maxContains"])if($[b]!==void 0)I[b]=$[b]}for(let b of Object.keys($))if(!Jz.has(b))B$(I,b,$[b]);if(Object.keys(I).length>0)v.registry.add(D,I);if($.description)D=D.describe($.description);return D}function GG($,v){if(typeof $==="boolean")return $?R.any():R.never();let D;try{D=JSON.parse(JSON.stringify($))}catch{throw Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let g=Xz(D,v?.defaultTarget),I=D.$defs||D.definitions||{},_={version:g,defs:I,refs:new Map,processing:new Set,rootSchema:D,registry:v?.registry??j$};return A$(D,_)}var BG=Symbol("z.visit/resolving");function HD($,v){let D=typeof v==="function"?v:(N,b)=>{let U=v[N._zod.def.type];return U?U(N,b):N},g=new Map;function I(N){let b=g.get(N);if(b===BG)return new p_({type:"lazy",getter:()=>g.get(N)});if(b!==void 0)return b;g.set(N,BG);let U=_(N),J=D(U,U!==N);return g.set(N,J),J}function _(N){let b=N._zod.def,U=b.type;switch(U){case"object":{let J=b.shape,W=Object.keys(J),Y=!1,B={};for(let K of W){let F=I(J[K]);if(F!==J[K])Y=!0;B[K]=F}let j=b.catchall;if(b.catchall){if(j=I(b.catchall),j!==b.catchall)Y=!0}return Y?a(N,{...b,shape:B,catchall:j}):N}case"array":{let J=I(b.element);return J===b.element?N:a(N,{...b,element:J})}case"tuple":{let J=b.items,W=!1,Y=[];for(let j of J){let K=I(j);if(K!==j)W=!0;Y.push(K)}let B=b.rest;if(b.rest){if(B=I(b.rest),B!==b.rest)W=!0}return W?a(N,{...b,items:Y,rest:B}):N}case"record":case"map":{let J=I(b.keyType),W=I(b.valueType);return J===b.keyType&&W===b.valueType?N:a(N,{...b,keyType:J,valueType:W})}case"set":{let J=I(b.valueType);return J===b.valueType?N:a(N,{...b,valueType:J})}case"union":{let J=b.options,W=!1,Y=[];for(let B of J){let j=I(B);if(j!==B)W=!0;Y.push(j)}return W?a(N,{...b,options:Y}):N}case"intersection":{let J=I(b.left),W=I(b.right);return J===b.left&&W===b.right?N:a(N,{...b,left:J,right:W})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let J=I(b.innerType);return J===b.innerType?N:a(N,{...b,innerType:J})}case"pipe":{let J=I(b.in),W=I(b.out);return J===b.in&&W===b.out?N:a(N,{...b,in:J,out:W})}case"function":{let J=I(b.input),W=I(b.output);return J===b.input&&W===b.output?N:a(N,{...b,input:J,output:W})}case"lazy":{let J=b.getter,{_cachedInner:W,...Y}=b;return a(N,{...Y,getter:()=>I(J())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return N;default:return N}}return I($)}function jG($){return HD($,{object:(v)=>v.partial(),union:(v)=>{let D=v._zod.def;return D.discriminator===void 0?v:E(D.options)}})}function Kz($,v){if(!v?.length)return $;let D=$._zod.def;return a($,o$(D,{checks:[...D.checks??[],...v]}),{parent:!0})}function zG($){return Kz($.out,$.checks)}function Oz($){return $.in._zod.traits.has("$ZodTransform")?zG($):$.in}function KG($){return HD($,{pipe:(v)=>Oz(v._zod.def),default:(v,D)=>D?C(v._zod.def.innerType):v,catch:(v,D)=>D?v._zod.def.innerType:v})}function OG($){return HD($,{pipe:(v)=>zG(v._zod.def),prefault:(v,D)=>D?v._zod.def.innerType:v})}var FD={};zv(FD,{string:()=>Hz,number:()=>Fz,date:()=>qz,boolean:()=>Pz,bigint:()=>wz});function Hz($){return G2(c4,$)}function Fz($){return H2(o4,$)}function Pz($){return S2(a4,$)}function wz($){return Z2(e4,$)}function qz($){return i2(QD,$)}var Vb="2025-11-25";var kb=[Vb,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Rb="io.modelcontextprotocol/related-task",k6="io.modelcontextprotocol/protocolVersion",$I="io.modelcontextprotocol/clientInfo",ov="io.modelcontextprotocol/serverInfo",R6="io.modelcontextprotocol/clientCapabilities",Cb="io.modelcontextprotocol/subscriptionId",vI="io.modelcontextprotocol/logLevel";var C6="2.0";var wv=cv(()=>E([X(),S(),k(),Jv(),L(X(),wv),H(wv)])),_$=L(X(),wv),xb=H(wv),II=E([X(),S().int()]),_I=X(),PD=G({ttl:S().optional()}),wD=G({taskId:X()}),DI=u({progressToken:II.optional(),[Rb]:wD.optional()}),G$=G({_meta:DI.optional()}),av=G$.extend({task:PD.optional()}),D$=G({method:X(),params:G$.loose().optional()}),w$=G({_meta:DI.optional()}),z$=G({method:X(),params:w$.loose().optional()}),gI=u({get[ov](){return Wv.optional().catch(void 0)}}),g$=u({_meta:gI.optional()}),s$=E([X(),S().int()]),NI=G({jsonrpc:P(C6),id:s$,...D$.shape}).strict(),bI=G({jsonrpc:P(C6),...z$.shape}).strict(),x6=G({jsonrpc:P(C6),id:s$,result:g$}).strict(),f6=G({jsonrpc:P(C6),id:s$.optional(),error:G({code:S().int(),message:X(),data:x().optional()})}).strict(),y6=E([NI,bI,x6,f6]),fb=E([x6,f6]),ev=g$.strict(),qD=w$.extend({requestId:s$.optional(),reason:X().optional()}),UI=z$.extend({method:P("notifications/cancelled"),params:qD}),MD=G({src:X(),mimeType:X().optional(),sizes:H(X()).optional(),theme:l(["light","dark"]).optional()}),qv=G({icons:H(MD).optional()}),Xv=G({name:X(),title:X().optional()}),Wv=Xv.extend({...Xv.shape,...qv.shape,version:X(),websiteUrl:X().optional(),description:X().optional()}),Tz=e$(G({applyDefaults:k().optional()}),_$),Sz=Pv(($)=>{if($&&typeof $==="object"&&!Array.isArray($)&&Object.keys($).length===0)return{form:{}};return $},e$(G({form:Tz.optional(),url:_$.optional()}),_$.optional())),yb=u({list:_$.optional(),cancel:_$.optional(),requests:u({sampling:u({createMessage:_$.optional()}).optional(),elicitation:u({create:_$.optional()}).optional()}).optional()}),ub=u({list:_$.optional(),cancel:_$.optional(),requests:u({tools:u({call:_$.optional()}).optional()}).optional()}),TD=G({experimental:L(X(),_$).optional(),sampling:G({context:_$.optional(),tools:_$.optional()}).optional(),elicitation:Sz.optional(),roots:G({listChanged:k().optional()}).optional(),tasks:yb.optional(),extensions:L(X(),_$).optional()}),SD=G$.extend({protocolVersion:X(),capabilities:TD,clientInfo:Wv}),AD=D$.extend({method:P("initialize"),params:SD}),JI=G({experimental:L(X(),_$).optional(),logging:_$.optional(),completions:_$.optional(),prompts:G({listChanged:k().optional()}).optional(),resources:G({subscribe:k().optional(),listChanged:k().optional()}).optional(),tools:G({listChanged:k().optional()}).optional(),tasks:ub.optional(),extensions:L(X(),_$).optional()}),ZD=g$.extend({protocolVersion:X(),capabilities:JI,serverInfo:Wv,instructions:X().optional()}),LD=z$.extend({method:P("notifications/initialized"),params:w$.optional()}),ED=D$.extend({method:P("server/discover"),params:G$.optional()}),XI=g$.extend({supportedVersions:H(X()),capabilities:JI,instructions:X().optional()}),WI=D$.extend({method:P("ping"),params:G$.optional()}),VD=G({progress:S(),total:C(S()),message:C(X())}),kD=G({...w$.shape,...VD.shape,progressToken:II}),QI=z$.extend({method:P("notifications/progress"),params:kD}),RD=G$.extend({cursor:_I.optional()}),Mv=D$.extend({params:RD.optional()}),Tv=g$.extend({nextCursor:_I.optional()}),YI=G({uri:X(),mimeType:C(X()),_meta:L(X(),x()).optional()}),GI=YI.extend({text:X()}),nQ=X().refine(($)=>{try{return atob($),!0}catch{return!1}},{message:"Invalid Base64 string"}),BI=YI.extend({blob:nQ}),Sv=l(["user","assistant"]),Qv=G({audience:H(Sv).optional(),priority:S().min(0).max(1).optional(),lastModified:p$.datetime({offset:!0}).optional()}),jI=G({...Xv.shape,...qv.shape,uri:X(),description:C(X()),mimeType:C(X()),size:C(S()),annotations:Qv.optional(),_meta:C(u({}))}),CD=G({...Xv.shape,...qv.shape,uriTemplate:X(),description:C(X()),mimeType:C(X()),annotations:Qv.optional(),_meta:C(u({}))}),xD=Mv.extend({method:P("resources/list")}),fD=Tv.extend({resources:H(jI)}),yD=Mv.extend({method:P("resources/templates/list")}),uD=Tv.extend({resourceTemplates:H(CD)}),u6=G$.extend({uri:X()}),iD=u6,lD=D$.extend({method:P("resources/read"),params:iD}),nD=g$.extend({contents:H(E([GI,BI]))}),mD=z$.extend({method:P("notifications/resources/list_changed"),params:w$.optional()}),hD=u6,rD=D$.extend({method:P("resources/subscribe"),params:hD}),dD=u6,pD=D$.extend({method:P("resources/unsubscribe"),params:dD}),zI=G({toolsListChanged:k().optional(),promptsListChanged:k().optional(),resourcesListChanged:k().optional(),resourceSubscriptions:H(X()).optional()}),cD=G$.extend({notifications:zI}),tD=D$.extend({method:P("subscriptions/listen"),params:cD}),oD=w$.extend({notifications:zI}),aD=z$.extend({method:P("notifications/subscriptions/acknowledged"),params:oD}),eD=gI.extend({[Cb]:s$}),sD=g$.extend({_meta:eD}),$1=w$.extend({uri:X()}),v1=z$.extend({method:P("notifications/resources/updated"),params:$1}),I1=G({name:X(),description:C(X()),required:C(k())}),_1=G({...Xv.shape,...qv.shape,description:C(X()),arguments:C(H(I1)),_meta:C(u({}))}),D1=Mv.extend({method:P("prompts/list")}),g1=Tv.extend({prompts:H(_1)}),N1=G$.extend({name:X(),arguments:L(X(),X()).optional()}),b1=D$.extend({method:P("prompts/get"),params:N1}),i6=G({type:P("text"),text:X(),annotations:Qv.optional(),_meta:L(X(),x()).optional()}),l6=G({type:P("image"),data:nQ,mimeType:X(),annotations:Qv.optional(),_meta:L(X(),x()).optional()}),n6=G({type:P("audio"),data:nQ,mimeType:X(),annotations:Qv.optional(),_meta:L(X(),x()).optional()}),U1=G({type:P("tool_use"),name:X(),id:X(),input:L(X(),x()),_meta:L(X(),x()).optional()}),m6=G({type:P("resource"),resource:E([GI,BI]),annotations:Qv.optional(),_meta:L(X(),x()).optional()}),h6=jI.extend({type:P("resource_link")}),Yv=E([i6,l6,n6,h6,m6]),J1=G({role:Sv,content:Yv}),X1=g$.extend({description:X().optional(),messages:H(J1)}),W1=z$.extend({method:P("notifications/prompts/list_changed"),params:w$.optional()}),Q1=G({title:X().optional(),readOnlyHint:k().optional(),destructiveHint:k().optional(),idempotentHint:k().optional(),openWorldHint:k().optional()}),Y1=G({taskSupport:l(["required","optional","forbidden"]).optional()}),sv=G({...Xv.shape,...qv.shape,description:X().optional(),inputSchema:G({type:P("object"),properties:L(X(),wv).optional(),required:H(X()).optional()}).catchall(x()),outputSchema:u({$schema:X().optional()}).optional(),annotations:Q1.optional(),execution:Y1.optional(),_meta:L(X(),x()).optional()}),G1=Mv.extend({method:P("tools/list")}),B1=Tv.extend({tools:H(sv)}),$6=g$.extend({content:H(Yv).default([]),structuredContent:x().optional(),isError:k().optional()}),ib=$6.or(g$.extend({toolResult:x()})),j1=av.extend({name:X(),arguments:L(X(),x()).optional()}),z1=D$.extend({method:P("tools/call"),params:j1}),K1=z$.extend({method:P("notifications/tools/list_changed"),params:w$.optional()}),lb=G({autoRefresh:k().default(!0),debounceMs:S().int().nonnegative().default(300)}),KI=l(["debug","info","notice","warning","error","critical","alert","emergency"]),O1=G$.extend({level:KI}),H1=D$.extend({method:P("logging/setLevel"),params:O1}),F1=w$.extend({level:KI,logger:X().optional(),data:x()}),P1=z$.extend({method:P("notifications/message"),params:F1}),w1=G({name:X().optional()}),q1=G({hints:H(w1).optional(),costPriority:S().min(0).max(1).optional(),speedPriority:S().min(0).max(1).optional(),intelligencePriority:S().min(0).max(1).optional()}),M1=G({mode:l(["auto","required","none"]).optional()}),T1=G({type:P("tool_result"),toolUseId:X().describe("The unique identifier for the corresponding tool call."),content:H(Yv),structuredContent:x().optional(),isError:k().optional(),_meta:L(X(),x()).optional()}),S1=pv("type",[i6,l6,n6]),tv=pv("type",[i6,l6,n6,U1,T1]),A1=G({role:Sv,content:E([tv,H(tv)]),_meta:L(X(),x()).optional()}),Z1=av.extend({messages:H(A1),modelPreferences:q1.optional(),systemPrompt:X().optional(),includeContext:l(["none","thisServer","allServers"]).optional(),temperature:S().optional(),maxTokens:S().int(),stopSequences:H(X()).optional(),metadata:_$.optional(),tools:H(sv).optional(),toolChoice:M1.optional()}),L1=D$.extend({method:P("sampling/createMessage"),params:Z1}),E1=g$.extend({model:X(),stopReason:C(l(["endTurn","stopSequence","maxTokens"]).or(X())),role:Sv,content:S1}),V1=g$.extend({model:X(),stopReason:C(l(["endTurn","stopSequence","maxTokens","toolUse"]).or(X())),role:Sv,content:E([tv,H(tv)])}),OI=G({type:P("boolean"),title:X().optional(),description:X().optional(),default:k().optional()}),r6=G({type:P("string"),title:X().optional(),description:X().optional(),minLength:S().optional(),maxLength:S().optional(),format:l(["email","uri","date","date-time"]).optional(),default:X().optional()}),d6=G({type:l(["number","integer"]),title:X().optional(),description:X().optional(),minimum:S().optional(),maximum:S().optional(),default:S().optional()}),HI=G({type:P("string"),title:X().optional(),description:X().optional(),enum:H(X()),default:X().optional()}),FI=G({type:P("string"),title:X().optional(),description:X().optional(),oneOf:H(G({const:X(),title:X()})),default:X().optional()}),PI=G({type:P("string"),title:X().optional(),description:X().optional(),enum:H(X()),enumNames:H(X()).optional(),default:X().optional()}),k1=E([HI,FI]),wI=G({type:P("array"),title:X().optional(),description:X().optional(),minItems:S().optional(),maxItems:S().optional(),items:G({type:P("string"),enum:H(X())}),default:H(X()).optional()}),qI=G({type:P("array"),title:X().optional(),description:X().optional(),minItems:S().optional(),maxItems:S().optional(),items:G({anyOf:H(G({const:X(),title:X()}))}),default:H(X()).optional()}),R1=E([wI,qI]),C1=E([PI,k1,R1]),MI=E([C1,OI,r6,d6]),p6=av.extend({mode:P("form").optional(),message:X(),requestedSchema:G({type:P("object"),properties:L(X(),MI),required:H(X()).optional()}).catchall(x())}),x1=av.extend({mode:P("url"),message:X(),elicitationId:X(),url:X().url()}),f1=E([p6,x1]),y1=D$.extend({method:P("elicitation/create"),params:f1}),u1=w$.extend({elicitationId:X()}),i1=z$.extend({method:P("notifications/elicitation/complete"),params:u1}),l1=g$.extend({action:l(["accept","decline","cancel"]),content:Pv(($)=>$===null?void 0:$,L(X(),E([X(),S(),k(),H(X())])).optional())}),n1=G({type:P("ref/resource"),uri:X()}),m1=G({type:P("ref/prompt"),name:X()}),h1=G$.extend({ref:E([m1,n1]),argument:G({name:X(),value:X()}),context:G({arguments:L(X(),X()).optional()}).optional()}),r1=D$.extend({method:P("completion/complete"),params:h1}),d1=g$.extend({completion:u({values:H(X()).max(100),total:C(S().int()),hasMore:C(k())})}),p1=G({uri:X().startsWith("file://"),name:X().optional(),_meta:L(X(),x()).optional()}),c1=D$.extend({method:P("roots/list"),params:G$.optional()}),t1=g$.extend({roots:H(p1)}),o1=z$.extend({method:P("notifications/roots/list_changed"),params:w$.optional()}),nb=u({ttl:S().optional(),pollInterval:S().optional()}),a1=l(["working","input_required","completed","failed","cancelled"]),Av=G({taskId:X(),status:a1,ttl:E([S(),Jv()]),createdAt:X(),lastUpdatedAt:X(),pollInterval:C(S()),statusMessage:C(X())}),mb=g$.extend({task:Av}),e1=w$.merge(Av),hb=z$.extend({method:P("notifications/tasks/status"),params:e1}),rb=D$.extend({method:P("tasks/get"),params:G$.extend({taskId:X()})}),db=g$.merge(Av),pb=D$.extend({method:P("tasks/result"),params:G$.extend({taskId:X()})}),cb=g$.loose(),tb=Mv.extend({method:P("tasks/list")}),ob=Tv.extend({tasks:H(Av)}),ab=D$.extend({method:P("tasks/cancel"),params:G$.extend({taskId:X()})}),eb=g$.merge(Av),sb=E([WI,AD,ED,r1,H1,b1,D1,xD,yD,lD,rD,pD,tD,z1,G1]),$U=E([UI,QI,LD,o1]),vU=E([ev,E1,V1,l1,t1]),IU=E([WI,L1,y1,c1]),_U=E([UI,QI,P1,v1,mD,K1,W1,aD,i1]),DU=E([ev,ZD,XI,d1,X1,g1,fD,uD,nD,$6,B1,sD]),Y$=t4().superRefine(($,v)=>{if(!URL.canParse($))return v.addIssue({code:uQ.custom,message:"URL must be parseable",fatal:!0}),L_}).refine(($)=>{let v=new URL($);return v.protocol!=="javascript:"&&v.protocol!=="data:"&&v.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),s1=u({resource:X().url(),authorization_servers:H(Y$).optional(),jwks_uri:X().url().optional(),scopes_supported:H(X()).optional(),bearer_methods_supported:H(X()).optional(),resource_signing_alg_values_supported:H(X()).optional(),resource_name:X().optional(),resource_documentation:X().optional(),resource_policy_uri:X().url().optional(),resource_tos_uri:X().url().optional(),tls_client_certificate_bound_access_tokens:k().optional(),authorization_details_types_supported:H(X()).optional(),dpop_signing_alg_values_supported:H(X()).optional(),dpop_bound_access_tokens_required:k().optional()}),TI=u({issuer:X(),authorization_endpoint:Y$,token_endpoint:Y$,registration_endpoint:Y$.optional(),scopes_supported:H(X()).optional(),response_types_supported:H(X()),response_modes_supported:H(X()).optional(),grant_types_supported:H(X()).optional(),token_endpoint_auth_methods_supported:H(X()).optional(),token_endpoint_auth_signing_alg_values_supported:H(X()).optional(),service_documentation:Y$.optional(),revocation_endpoint:Y$.optional(),revocation_endpoint_auth_methods_supported:H(X()).optional(),revocation_endpoint_auth_signing_alg_values_supported:H(X()).optional(),introspection_endpoint:X().optional(),introspection_endpoint_auth_methods_supported:H(X()).optional(),introspection_endpoint_auth_signing_alg_values_supported:H(X()).optional(),code_challenge_methods_supported:H(X()).optional(),client_id_metadata_document_supported:k().optional(),authorization_response_iss_parameter_supported:k().optional().catch(void 0)}),$g=u({issuer:X(),authorization_endpoint:Y$,token_endpoint:Y$,userinfo_endpoint:Y$.optional(),jwks_uri:Y$,registration_endpoint:Y$.optional(),scopes_supported:H(X()).optional(),response_types_supported:H(X()),response_modes_supported:H(X()).optional(),grant_types_supported:H(X()).optional(),acr_values_supported:H(X()).optional(),subject_types_supported:H(X()),id_token_signing_alg_values_supported:H(X()),id_token_encryption_alg_values_supported:H(X()).optional(),id_token_encryption_enc_values_supported:H(X()).optional(),userinfo_signing_alg_values_supported:H(X()).optional(),userinfo_encryption_alg_values_supported:H(X()).optional(),userinfo_encryption_enc_values_supported:H(X()).optional(),request_object_signing_alg_values_supported:H(X()).optional(),request_object_encryption_alg_values_supported:H(X()).optional(),request_object_encryption_enc_values_supported:H(X()).optional(),token_endpoint_auth_methods_supported:H(X()).optional(),token_endpoint_auth_signing_alg_values_supported:H(X()).optional(),display_values_supported:H(X()).optional(),claim_types_supported:H(X()).optional(),claims_supported:H(X()).optional(),service_documentation:X().optional(),claims_locales_supported:H(X()).optional(),ui_locales_supported:H(X()).optional(),claims_parameter_supported:k().optional(),request_parameter_supported:k().optional(),request_uri_parameter_supported:k().optional(),require_request_uri_registration:k().optional(),op_policy_uri:Y$.optional(),op_tos_uri:Y$.optional(),client_id_metadata_document_supported:k().optional(),authorization_response_iss_parameter_supported:k().optional().catch(void 0)}),vg=G({...$g.shape,...TI.pick({code_challenge_methods_supported:!0}).shape}),Ig=G({access_token:X(),id_token:X().optional(),token_type:X(),expires_in:FD.number().optional(),scope:X().optional(),refresh_token:X().optional()}).strip(),_g=G({issued_token_type:P("urn:ietf:params:oauth:token-type:id-jag"),access_token:X(),token_type:X().optional(),expires_in:S().optional(),scope:X().optional()}).strip(),Dg=G({error:X(),error_description:X().optional(),error_uri:X().optional()}),lQ=Y$.optional().or(P("").transform(()=>{return})),gg=G({redirect_uris:H(Y$),token_endpoint_auth_method:X().optional(),grant_types:H(X()).optional(),response_types:H(X()).optional(),application_type:X().optional(),client_name:X().optional(),client_uri:Y$.optional(),logo_uri:lQ,scope:X().optional(),contacts:H(X()).optional(),tos_uri:lQ,policy_uri:X().optional(),jwks_uri:Y$.optional(),jwks:Sb().optional(),software_id:X().optional(),software_version:X().optional(),software_statement:X().optional()}).strip(),Ng=G({client_id:X(),client_secret:X().optional(),client_id_issued_at:S().optional(),client_secret_expires_at:S().optional()}).strip(),bg=gg.merge(Ng),gU=G({error:X(),error_description:X().optional()}).strip(),NU=G({token:X(),token_type_hint:X().optional()}).strip();var cQ=Symbol.for("mcp.sdk.errorBrands");function t6($,v){let D=new Set,g=v;while(typeof g==="function"){let I=g.mcpBrand;if(Object.prototype.hasOwnProperty.call(g,"mcpBrand")&&typeof I==="string")D.add(I);g=Object.getPrototypeOf(g)}if(D.size===0)return;Object.defineProperty($,cQ,{value:D,enumerable:!1,configurable:!0})}function l$($,v){try{if(typeof v==="object"&&v!==null&&Object.prototype.hasOwnProperty.call($,"mcpBrand")&&typeof $.mcpBrand==="string"&&Object.prototype.hasOwnProperty.call(v,cQ)){let D=v[cQ];if(D&&typeof D.has==="function"&&D.has($.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call($,v)}var Az=class $ extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](v){return l$(this,v)}static isInstance(v){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return l$(this,v)}constructor(v,D,g){super(D);this.code=v,this.errorUri=g,this.name="OAuthError",t6(this,new.target)}toResponseObject(){let v={error:this.code,error_description:this.message};if(this.errorUri)v.error_uri=this.errorUri;return v}static fromResponse(v){return new $(v.error,v.error_description??v.error,v.error_uri)}},K$=function($){return $.NotConnected="NOT_CONNECTED",$.AlreadyConnected="ALREADY_CONNECTED",$.NotInitialized="NOT_INITIALIZED",$.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",$.RequestTimeout="REQUEST_TIMEOUT",$.ConnectionClosed="CONNECTION_CLOSED",$.SendFailed="SEND_FAILED",$.InvalidResult="INVALID_RESULT",$.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",$.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",$.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",$.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",$.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",$.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",$.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",$.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",$.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",$.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",$.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",$}({}),U$=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance]($){return l$(this,$)}static isInstance($){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return l$(this,$)}constructor($,v,D){super(v);this.code=$,this.data=D,this.name="SdkError",t6(this,new.target)}},Zz=class extends U${static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor($,v,D){super($,v,D);this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};var Lz="2026-07-28";function uG($){return $>=Lz}function iG($){let v=$.structuredContent;if(v===void 0)return $;if(!(typeof v!=="object"||v===null||Array.isArray(v)))return $;if($.content?.some((D)=>D.type==="text")??!1)return $;return{...$,content:[...$.content??[],{type:"text",text:JSON.stringify(v)}]}}var lG=["task","inputRequests","requestState"];function Ez($){if($===null||typeof $!=="object"||Array.isArray($)||$.content!==void 0||lG.some((v)=>(v in $)))return $;return{...$,content:[]}}function Vz(){let $=cv(()=>E([X(),S(),k(),Jv(),L(X(),$),H($)])),v=L(X(),$),D=E([X(),S().int()]),g=X(),I=G({ttl:S().optional()}),_=G({taskId:X()}),N=u({progressToken:D.optional(),"io.modelcontextprotocol/related-task":_.optional()}),b=G({_meta:N.optional()}),U=b.extend({task:I.optional()}),J=G({method:X(),params:b.loose().optional()}),W=G({_meta:N.optional()}),Y=G({method:X(),params:W.loose().optional()}),B=u({_meta:N.optional()}),j=E([X(),S().int()]),K=B.strict(),F=W.extend({requestId:j.optional(),reason:X().optional()}),T=Y.extend({method:P("notifications/cancelled"),params:F}),V=G({src:X(),mimeType:X().optional(),sizes:H(X()).optional(),theme:l(["light","dark"]).optional()}),Z=G({icons:H(V).optional()}),f=G({name:X(),title:X().optional()}),r=f.extend({...f.shape,...Z.shape,version:X(),websiteUrl:X().optional(),description:X().optional()}),t=e$(G({applyDefaults:k().optional()}),v),y=Pv((F$)=>{if(F$&&typeof F$==="object"&&!Array.isArray(F$)&&Object.keys(F$).length===0)return{form:{}};return F$},e$(G({form:t.optional(),url:v.optional()}),v.optional())),o=u({list:v.optional(),cancel:v.optional(),requests:u({sampling:u({createMessage:v.optional()}).optional(),elicitation:u({create:v.optional()}).optional()}).optional()}),C$=u({list:v.optional(),cancel:v.optional(),requests:u({tools:u({call:v.optional()}).optional()}).optional()}),W$=G({experimental:L(X(),v).optional(),sampling:G({context:v.optional(),tools:v.optional()}).optional(),elicitation:y.optional(),roots:G({listChanged:k().optional()}).optional(),tasks:o.optional(),extensions:L(X(),v).optional()}),n$=b.extend({protocolVersion:X(),capabilities:W$,clientInfo:r}),$v=J.extend({method:P("initialize"),params:n$}),v6=G({experimental:L(X(),v).optional(),logging:v.optional(),completions:v.optional(),prompts:G({listChanged:k().optional()}).optional(),resources:G({subscribe:k().optional(),listChanged:k().optional()}).optional(),tools:G({listChanged:k().optional()}).optional(),tasks:C$.optional(),extensions:L(X(),v).optional()}),I6=B.extend({protocolVersion:X(),capabilities:v6,serverInfo:r,instructions:X().optional()}),o6=Y.extend({method:P("notifications/initialized"),params:W.optional()}),Zv=J.extend({method:P("ping"),params:b.optional()}),_6=G({progress:S(),total:C(S()),message:C(X())}),vv=G({...W.shape,..._6.shape,progressToken:D}),Lv=Y.extend({method:P("notifications/progress"),params:vv}),a6=b.extend({cursor:g.optional()}),Bv=J.extend({params:a6.optional()}),jv=B.extend({nextCursor:g.optional()}),e6=G({uri:X(),mimeType:C(X()),_meta:L(X(),x()).optional()}),s6=e6.extend({text:X()}),D6=X().refine((F$)=>{try{return atob(F$),!0}catch{return!1}},{message:"Invalid Base64 string"}),$4=e6.extend({blob:D6}),Iv=l(["user","assistant"]),c$=G({audience:H(Iv).optional(),priority:S().min(0).max(1).optional(),lastModified:p$.datetime({offset:!0}).optional()}),g6=G({...f.shape,...Z.shape,uri:X(),description:C(X()),mimeType:C(X()),size:C(S()),annotations:c$.optional(),_meta:C(u({}))}),AI=G({...f.shape,...Z.shape,uriTemplate:X(),description:C(X()),mimeType:C(X()),annotations:c$.optional(),_meta:C(u({}))}),ZI=Bv.extend({method:P("resources/list")}),LI=jv.extend({resources:H(g6)}),Ev=Bv.extend({method:P("resources/templates/list")}),v4=jv.extend({resourceTemplates:H(AI)}),N6=b.extend({uri:X()}),EI=N6,VI=J.extend({method:P("resources/read"),params:EI}),kI=B.extend({contents:H(E([s6,$4]))}),RI=Y.extend({method:P("notifications/resources/list_changed"),params:W.optional()}),CI=N6,xI=J.extend({method:P("resources/subscribe"),params:CI}),fI=N6,yI=J.extend({method:P("resources/unsubscribe"),params:fI}),uI=W.extend({uri:X()}),iI=Y.extend({method:P("notifications/resources/updated"),params:uI}),lI=G({name:X(),description:C(X()),required:C(k())}),nI=G({...f.shape,...Z.shape,description:C(X()),arguments:C(H(lI)),_meta:C(u({}))}),mI=Bv.extend({method:P("prompts/list")}),hI=jv.extend({prompts:H(nI)}),rI=b.extend({name:X(),arguments:L(X(),X()).optional()}),dI=J.extend({method:P("prompts/get"),params:rI}),b6=G({type:P("text"),text:X(),annotations:c$.optional(),_meta:L(X(),x()).optional()}),U6=G({type:P("image"),data:D6,mimeType:X(),annotations:c$.optional(),_meta:L(X(),x()).optional()}),J6=G({type:P("audio"),data:D6,mimeType:X(),annotations:c$.optional(),_meta:L(X(),x()).optional()}),pI=G({type:P("tool_use"),name:X(),id:X(),input:L(X(),x()),_meta:L(X(),x()).optional()}),Vv=G({type:P("resource"),resource:E([s6,$4]),annotations:c$.optional(),_meta:L(X(),x()).optional()}),cI=g6.extend({type:P("resource_link")}),m$=E([b6,U6,J6,cI,Vv]),I4=G({role:Iv,content:m$}),_4=B.extend({description:X().optional(),messages:H(I4)}),X6=Y.extend({method:P("notifications/prompts/list_changed"),params:W.optional()}),tI=G({title:X().optional(),readOnlyHint:k().optional(),destructiveHint:k().optional(),idempotentHint:k().optional(),openWorldHint:k().optional()}),D4=G({taskSupport:l(["required","optional","forbidden"]).optional()}),W6=G({...f.shape,...Z.shape,description:X().optional(),inputSchema:G({type:P("object"),properties:L(X(),$).optional(),required:H(X()).optional()}).catchall(x()),outputSchema:G({type:P("object"),properties:L(X(),$).optional(),required:H(X()).optional()}).catchall(x()).optional(),annotations:tI.optional(),execution:D4.optional(),_meta:L(X(),x()).optional()}),g4=Bv.extend({method:P("tools/list")}),N4=jv.extend({tools:H(W6)}),b4=B.extend({content:H(m$),structuredContent:L(X(),x()).optional(),isError:k().optional()}),H$=U.extend({name:X(),arguments:L(X(),x()).optional()}),oI=J.extend({method:P("tools/call"),params:H$}),Bg=Y.extend({method:P("notifications/tools/list_changed"),params:W.optional()}),U4=l(["debug","info","notice","warning","error","critical","alert","emergency"]),aI=b.extend({level:U4}),eI=J.extend({method:P("logging/setLevel"),params:aI}),sI=W.extend({level:U4,logger:X().optional(),data:x()}),$_=Y.extend({method:P("notifications/message"),params:sI}),v_=G({name:X().optional()}),I_=G({hints:H(v_).optional(),costPriority:S().min(0).max(1).optional(),speedPriority:S().min(0).max(1).optional(),intelligencePriority:S().min(0).max(1).optional()}),__=G({mode:l(["auto","required","none"]).optional()}),jg=G({type:P("tool_result"),toolUseId:X().describe("The unique identifier for the corresponding tool call."),content:H(m$),structuredContent:G({}).loose().optional(),isError:k().optional(),_meta:L(X(),x()).optional()}),D_=pv("type",[b6,U6,J6]),kv=pv("type",[b6,U6,J6,pI,jg]),g_=G({role:Iv,content:E([kv,H(kv)]),_meta:L(X(),x()).optional()}),N_=U.extend({messages:H(g_),modelPreferences:I_.optional(),systemPrompt:X().optional(),includeContext:l(["none","thisServer","allServers"]).optional(),temperature:S().optional(),maxTokens:S().int(),stopSequences:H(X()).optional(),metadata:v.optional(),tools:H(W6).optional(),toolChoice:__.optional()}),b_=J.extend({method:P("sampling/createMessage"),params:N_}),U_=B.extend({model:X(),stopReason:C(l(["endTurn","stopSequence","maxTokens"]).or(X())),role:Iv,content:D_}),J_=B.extend({model:X(),stopReason:C(l(["endTurn","stopSequence","maxTokens","toolUse"]).or(X())),role:Iv,content:E([kv,H(kv)])}),X_=G({type:P("boolean"),title:X().optional(),description:X().optional(),default:k().optional()}),W_=G({type:P("string"),title:X().optional(),description:X().optional(),minLength:S().optional(),maxLength:S().optional(),format:l(["email","uri","date","date-time"]).optional(),default:X().optional()}),Q_=G({type:l(["number","integer"]),title:X().optional(),description:X().optional(),minimum:S().optional(),maximum:S().optional(),default:S().optional()}),Y_=G({type:P("string"),title:X().optional(),description:X().optional(),enum:H(X()),default:X().optional()}),G_=G({type:P("string"),title:X().optional(),description:X().optional(),oneOf:H(G({const:X(),title:X()})),default:X().optional()}),B_=G({type:P("string"),title:X().optional(),description:X().optional(),enum:H(X()),enumNames:H(X()).optional(),default:X().optional()}),j_=E([Y_,G_]),Q6=G({type:P("array"),title:X().optional(),description:X().optional(),minItems:S().optional(),maxItems:S().optional(),items:G({type:P("string"),enum:H(X())}),default:H(X()).optional()}),Y6=G({type:P("array"),title:X().optional(),description:X().optional(),minItems:S().optional(),maxItems:S().optional(),items:G({anyOf:H(G({const:X(),title:X()}))}),default:H(X()).optional()}),zg=E([Q6,Y6]),Kg=E([B_,j_,zg]),x$=E([Kg,X_,W_,Q_]),f$=U.extend({mode:P("form").optional(),message:X(),requestedSchema:G({type:P("object"),properties:L(X(),x$),required:H(X()).optional()}).catchall(x())}),z_=U.extend({mode:P("url"),message:X(),elicitationId:X(),url:X().url()}),t$=E([f$,z_]),Og=J.extend({method:P("elicitation/create"),params:t$}),Hg=W.extend({elicitationId:X()}),Fg=Y.extend({method:P("notifications/elicitation/complete"),params:Hg}),Pg=B.extend({action:l(["accept","decline","cancel"]),content:Pv((F$)=>F$===null?void 0:F$,L(X(),E([X(),S(),k(),H(X())])).optional())}),wg=G({type:P("ref/resource"),uri:X()}),qg=G({type:P("ref/prompt"),name:X()}),Mg=b.extend({ref:E([qg,wg]),argument:G({name:X(),value:X()}),context:G({arguments:L(X(),X()).optional()}).optional()}),K_=J.extend({method:P("completion/complete"),params:Mg}),Tg=B.extend({completion:u({values:H(X()).max(100),total:C(S().int()),hasMore:C(k())})}),Sg=G({uri:X().startsWith("file://"),name:X().optional(),_meta:L(X(),x()).optional()}),J4=J.extend({method:P("roots/list"),params:b.optional()}),O_=B.extend({roots:H(Sg)}),Ag=Y.extend({method:P("notifications/roots/list_changed"),params:W.optional()}),Zg=u({ttl:S().optional(),pollInterval:S().optional()}),Lg=l(["working","input_required","completed","failed","cancelled"]),Rv=G({taskId:X(),status:Lg,ttl:E([S(),Jv()]),createdAt:X(),lastUpdatedAt:X(),pollInterval:C(S()),statusMessage:C(X())}),Z$=B.extend({task:Rv}),Eg=W.merge(Rv),G6=Y.extend({method:P("notifications/tasks/status"),params:Eg}),X4=J.extend({method:P("tasks/get"),params:b.extend({taskId:X()})}),W4=B.merge(Rv),Q4=J.extend({method:P("tasks/result"),params:b.extend({taskId:X()})}),BU=B.loose(),L$=Bv.extend({method:P("tasks/list")}),b$=jv.extend({tasks:H(Rv)}),B6=J.extend({method:P("tasks/cancel"),params:b.extend({taskId:X()})});return{JSONValueSchema:$,JSONObjectSchema:v,ProgressTokenSchema:D,CursorSchema:g,TaskMetadataSchema:I,RelatedTaskMetadataSchema:_,RequestMetaSchema:N,BaseRequestParamsSchema:b,TaskAugmentedRequestParamsSchema:U,RequestSchema:J,NotificationsParamsSchema:W,NotificationSchema:Y,ResultSchema:B,RequestIdSchema:j,EmptyResultSchema:K,CancelledNotificationParamsSchema:F,CancelledNotificationSchema:T,IconSchema:V,IconsSchema:Z,BaseMetadataSchema:f,ImplementationSchema:r,ClientTasksCapabilitySchema:o,ServerTasksCapabilitySchema:C$,ClientCapabilitiesSchema:W$,InitializeRequestParamsSchema:n$,InitializeRequestSchema:$v,ServerCapabilitiesSchema:v6,InitializeResultSchema:I6,InitializedNotificationSchema:o6,PingRequestSchema:Zv,ProgressSchema:_6,ProgressNotificationParamsSchema:vv,ProgressNotificationSchema:Lv,PaginatedRequestParamsSchema:a6,PaginatedRequestSchema:Bv,PaginatedResultSchema:jv,ResourceContentsSchema:e6,TextResourceContentsSchema:s6,BlobResourceContentsSchema:$4,RoleSchema:Iv,AnnotationsSchema:c$,ResourceSchema:g6,ResourceTemplateSchema:AI,ListResourcesRequestSchema:ZI,ListResourcesResultSchema:LI,ListResourceTemplatesRequestSchema:Ev,ListResourceTemplatesResultSchema:v4,ResourceRequestParamsSchema:N6,ReadResourceRequestParamsSchema:EI,ReadResourceRequestSchema:VI,ReadResourceResultSchema:kI,ResourceListChangedNotificationSchema:RI,SubscribeRequestParamsSchema:CI,SubscribeRequestSchema:xI,UnsubscribeRequestParamsSchema:fI,UnsubscribeRequestSchema:yI,ResourceUpdatedNotificationParamsSchema:uI,ResourceUpdatedNotificationSchema:iI,PromptArgumentSchema:lI,PromptSchema:nI,ListPromptsRequestSchema:mI,ListPromptsResultSchema:hI,GetPromptRequestParamsSchema:rI,GetPromptRequestSchema:dI,TextContentSchema:b6,ImageContentSchema:U6,AudioContentSchema:J6,ToolUseContentSchema:pI,EmbeddedResourceSchema:Vv,ResourceLinkSchema:cI,ContentBlockSchema:m$,PromptMessageSchema:I4,GetPromptResultSchema:_4,PromptListChangedNotificationSchema:X6,ToolAnnotationsSchema:tI,ToolExecutionSchema:D4,ToolSchema:W6,ListToolsRequestSchema:g4,ListToolsResultSchema:N4,CallToolResultSchema:b4,CallToolRequestParamsSchema:H$,CallToolRequestSchema:oI,ToolListChangedNotificationSchema:Bg,LoggingLevelSchema:U4,SetLevelRequestParamsSchema:aI,SetLevelRequestSchema:eI,LoggingMessageNotificationParamsSchema:sI,LoggingMessageNotificationSchema:$_,ModelHintSchema:v_,ModelPreferencesSchema:I_,ToolChoiceSchema:__,ToolResultContentSchema:jg,SamplingContentSchema:D_,SamplingMessageContentBlockSchema:kv,SamplingMessageSchema:g_,CreateMessageRequestParamsSchema:N_,CreateMessageRequestSchema:b_,CreateMessageResultSchema:U_,CreateMessageResultWithToolsSchema:J_,BooleanSchemaSchema:X_,StringSchemaSchema:W_,NumberSchemaSchema:Q_,UntitledSingleSelectEnumSchemaSchema:Y_,TitledSingleSelectEnumSchemaSchema:G_,LegacyTitledEnumSchemaSchema:B_,SingleSelectEnumSchemaSchema:j_,UntitledMultiSelectEnumSchemaSchema:Q6,TitledMultiSelectEnumSchemaSchema:Y6,MultiSelectEnumSchemaSchema:zg,EnumSchemaSchema:Kg,PrimitiveSchemaDefinitionSchema:x$,ElicitRequestFormParamsSchema:f$,ElicitRequestURLParamsSchema:z_,ElicitRequestParamsSchema:t$,ElicitRequestSchema:Og,ElicitationCompleteNotificationParamsSchema:Hg,ElicitationCompleteNotificationSchema:Fg,ElicitResultSchema:Pg,ResourceTemplateReferenceSchema:wg,PromptReferenceSchema:qg,CompleteRequestParamsSchema:Mg,CompleteRequestSchema:K_,CompleteResultSchema:Tg,RootSchema:Sg,ListRootsRequestSchema:J4,ListRootsResultSchema:O_,RootsListChangedNotificationSchema:Ag,TaskCreationParamsSchema:Zg,TaskStatusSchema:Lg,TaskSchema:Rv,CreateTaskResultSchema:Z$,TaskStatusNotificationParamsSchema:Eg,TaskStatusNotificationSchema:G6,GetTaskRequestSchema:X4,GetTaskResultSchema:W4,GetTaskPayloadRequestSchema:Q4,GetTaskPayloadResultSchema:BU,ListTasksRequestSchema:L$,ListTasksResultSchema:b$,CancelTaskRequestSchema:B6,CancelTaskResultSchema:B.merge(Rv),ClientRequestSchema:E([Zv,$v,K_,eI,dI,mI,ZI,Ev,VI,xI,yI,oI,g4,X4,Q4,L$,B6]),ClientNotificationSchema:E([T,Lv,o6,Ag,G6]),ClientResultSchema:E([K,U_,J_,Pg,O_,W4,b$,Z$]),ServerRequestSchema:E([Zv,b_,Og,J4,X4,Q4,L$,B6]),ServerNotificationSchema:E([T,Lv,$_,iI,RI,Bg,X6,G6,Fg]),ServerResultSchema:E([K,I6,Tg,_4,hI,LI,v4,kI,b4,N4,W4,b$,Z$]),CallToolResultWireSchema:x().superRefine((F$,MB)=>{if(typeof F$!=="object"||F$===null||Array.isArray(F$)||F$.content!==void 0)return;for(let Z9 of lG)if(Z9 in F$){MB.addIssue({code:"custom",message:`content is required when the body carries '${Z9}' — another result family cannot default into an empty tools/call success`});return}}).transform(Ez).pipe(b4)}}var kz;function nG(){return kz??=Vz()}function mG($){return $.type!=="object"}var Rz=new Set(["const","enum","default","examples"]),Cz=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function ZG($){return $!==void 0&&!(typeof $==="string"&&$.startsWith("#"))}function xz($){let v=typeof $.$schema==="string"?$.$schema:void 0;if(ZG($.$id))return{...v!==void 0&&{$schema:v},type:"object",properties:{result:$},required:["result"]};let D=k9($.$schema)&&$.$recursiveAnchor!==!0,g=(I,_)=>{if(Array.isArray(I))return I.map((U)=>g(U,!1));if(I===null||typeof I!=="object")return I;if(!_&&ZG(I.$id))return I;let N={},b=!1;for(let[U,J]of Object.entries(I))if(_)N[U]=g(J,!1);else if((U==="$ref"||U==="$dynamicRef")&&typeof J==="string")N[U]=J==="#"?"#/properties/result":J.startsWith("#/")?`#/properties/result${J.slice(1)}`:J;else if(U==="$recursiveRef"&&J==="#"&&D)b=!0;else if(Rz.has(U))N[U]=J;else if(Cz.has(U))N[U]=g(J,!0);else N[U]=g(J,!1);if(b)if("$ref"in N)N.allOf=[...Array.isArray(N.allOf)?N.allOf:[],{$ref:"#/properties/result"}];else N.$ref="#/properties/result";return N};return{...v!==void 0&&{$schema:v},type:"object",properties:{result:g($,!1)},required:["result"]}}var hG={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},rG={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},fz={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},bU;function $9(){if(bU)return bU;let $=nG();return bU={requestSchemas:{ping:$.PingRequestSchema,initialize:$.InitializeRequestSchema,"completion/complete":$.CompleteRequestSchema,"logging/setLevel":$.SetLevelRequestSchema,"prompts/get":$.GetPromptRequestSchema,"prompts/list":$.ListPromptsRequestSchema,"resources/list":$.ListResourcesRequestSchema,"resources/templates/list":$.ListResourceTemplatesRequestSchema,"resources/read":$.ReadResourceRequestSchema,"resources/subscribe":$.SubscribeRequestSchema,"resources/unsubscribe":$.UnsubscribeRequestSchema,"tools/call":$.CallToolRequestSchema,"tools/list":$.ListToolsRequestSchema,"tasks/get":$.GetTaskRequestSchema,"tasks/result":$.GetTaskPayloadRequestSchema,"tasks/list":$.ListTasksRequestSchema,"tasks/cancel":$.CancelTaskRequestSchema,"sampling/createMessage":$.CreateMessageRequestSchema,"elicitation/create":$.ElicitRequestSchema,"roots/list":$.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":$.CancelledNotificationSchema,"notifications/progress":$.ProgressNotificationSchema,"notifications/initialized":$.InitializedNotificationSchema,"notifications/roots/list_changed":$.RootsListChangedNotificationSchema,"notifications/tasks/status":$.TaskStatusNotificationSchema,"notifications/message":$.LoggingMessageNotificationSchema,"notifications/resources/updated":$.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":$.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":$.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":$.PromptListChangedNotificationSchema,"notifications/elicitation/complete":$.ElicitationCompleteNotificationSchema},resultSchemas:{ping:$.EmptyResultSchema,initialize:$.InitializeResultSchema,"completion/complete":$.CompleteResultSchema,"logging/setLevel":$.EmptyResultSchema,"prompts/get":$.GetPromptResultSchema,"prompts/list":$.ListPromptsResultSchema,"resources/list":$.ListResourcesResultSchema,"resources/templates/list":$.ListResourceTemplatesResultSchema,"resources/read":$.ReadResourceResultSchema,"resources/subscribe":$.EmptyResultSchema,"resources/unsubscribe":$.EmptyResultSchema,"tools/call":$.CallToolResultWireSchema,"tools/list":$.ListToolsResultSchema,"sampling/createMessage":$.CreateMessageResultWithToolsSchema,"elicitation/create":$.ElicitResultSchema,"roots/list":$.ListRootsResultSchema}},bU}function dG($){return Object.prototype.hasOwnProperty.call(hG,$)}function pG($){return Object.prototype.hasOwnProperty.call(rG,$)}function yz($){return Object.prototype.hasOwnProperty.call(fz,$)}function uz($){return yz($)?$9().resultSchemas[$]:void 0}function iz($){return dG($)?$9().requestSchemas[$]:void 0}function lz($){return pG($)?$9().notificationSchemas[$]:void 0}var cw=Object.keys(hG),tw=Object.keys(rG);function tQ($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function UU($,v){if($===void 0)return{ok:!1,reason:"not-in-era"};let D=$.safeParse(v);return D.success?{ok:!0,value:D.data}:{ok:!1,reason:"invalid",message:String(D.error)}}var LG={ok:!1,reason:"not-in-era"};function EG($){return tQ($)&&tQ($.outputSchema)&&mG($.outputSchema)}function VG($){return $}var v9={era:"2025-11-25",hasRequestMethod:dG,hasNotificationMethod:pG,validateRequest:($,v)=>UU(iz($),v),validateResult:($,v)=>UU(uz($),v),validateNotification:($,v)=>UU(lz($),v),hasInputRequestMethod:()=>!1,validateInputRequest:()=>LG,validateInputResponse:()=>LG,samplingResultVariant:($,v)=>{let D=nG();return UU($?D.CreateMessageResultWithToolsSchema:D.CreateMessageResultSchema,v)},outboundEnvelope:($)=>{return},validateEnvelopeMeta:($)=>[],projectCallToolResult($,v){let D=iG($),g=D.structuredContent;if(g===void 0)return D;let I=typeof g!=="object"||g===null||Array.isArray(g),_=v!==void 0&&mG(v);if(!I&&!_)return D;return{...D,structuredContent:{result:g}}},decodeResult($,v){if(tQ(v)&&"resultType"in v){let D={...v};return delete D.resultType,{kind:"complete",result:VG(D)}}return{kind:"complete",result:VG(v)}},encodeResult($,v){if($!=="tools/list")return v;let D=v.tools;if(!Array.isArray(D)||!D.some((g)=>EG(g)))return v;return{...v,tools:D.map((g)=>EG(g)?{...g,outputSchema:xz(g.outputSchema)}:g)}},encodeErrorCode:($)=>$===-32002?-32602:$,checkInboundEnvelope:($)=>{return}};function nz(){let $=cv(()=>E([X(),S(),k(),Jv(),L(X(),$),H($)])),v=L(X(),$),D=E([X(),S().int()]),g=X(),I=E([X(),S().int()]),_=l(["user","assistant"]),N=l(["debug","info","notice","warning","error","critical","alert","emergency"]),b=X().refine((b$)=>{try{return atob(b$),!0}catch{return!1}},{message:"Invalid Base64 string"}),U=G({ttl:S().optional()}),J=G({taskId:X()}),W=u({progressToken:D.optional(),"io.modelcontextprotocol/related-task":J.optional()}),Y=G({_meta:W.optional()}),B=Y.extend({task:U.optional()}),j=G({_meta:W.optional()}),K=G({method:X(),params:j.loose().optional()}),F=G({src:X(),mimeType:X().optional(),sizes:H(X()).optional(),theme:l(["light","dark"]).optional()}),T=G({icons:H(F).optional()}),V=G({name:X(),title:X().optional()}),Z=V.extend({...V.shape,...T.shape,version:X(),websiteUrl:X().optional(),description:X().optional()}),f=e$(G({applyDefaults:k().optional()}),v),r=Pv((b$)=>{if(b$&&typeof b$==="object"&&!Array.isArray(b$)&&Object.keys(b$).length===0)return{form:{}};return b$},e$(G({form:f.optional(),url:v.optional()}),v.optional())),t=u({list:v.optional(),cancel:v.optional(),requests:u({sampling:u({createMessage:v.optional()}).optional(),elicitation:u({create:v.optional()}).optional()}).optional()}),y=u({list:v.optional(),cancel:v.optional(),requests:u({tools:u({call:v.optional()}).optional()}).optional()}),o=G({experimental:L(X(),v).optional(),sampling:G({context:v.optional(),tools:v.optional()}).optional(),elicitation:r.optional(),roots:G({listChanged:k().optional()}).optional(),tasks:t.optional(),extensions:L(X(),v).optional()}),C$=G({experimental:L(X(),v).optional(),logging:v.optional(),completions:v.optional(),prompts:G({listChanged:k().optional()}).optional(),resources:G({subscribe:k().optional(),listChanged:k().optional()}).optional(),tools:G({listChanged:k().optional()}).optional(),tasks:y.optional(),extensions:L(X(),v).optional()}),W$=G({progress:S(),total:C(S()),message:C(X())}),n$=G({...j.shape,...W$.shape,progressToken:D}),$v=K.extend({method:P("notifications/progress"),params:n$}),v6=j.extend({level:N,logger:X().optional(),data:x()}),I6=K.extend({method:P("notifications/message"),params:v6}),o6=G({uri:X(),mimeType:C(X()),_meta:L(X(),x()).optional()}),Zv=o6.extend({text:X()}),_6=o6.extend({blob:b}),vv=G({audience:H(_).optional(),priority:S().min(0).max(1).optional(),lastModified:p$.datetime({offset:!0}).optional()}),Lv=G({...V.shape,...T.shape,uri:X(),description:C(X()),mimeType:C(X()),size:C(S()),annotations:vv.optional(),_meta:C(u({}))}),a6=G({...V.shape,...T.shape,uriTemplate:X(),description:C(X()),mimeType:C(X()),annotations:vv.optional(),_meta:C(u({}))}),Bv=K.extend({method:P("notifications/resources/list_changed"),params:j.optional()}),jv=j.extend({uri:X()}),e6=K.extend({method:P("notifications/resources/updated"),params:jv}),s6=G({name:X(),description:C(X()),required:C(k())}),D6=G({...V.shape,...T.shape,description:C(X()),arguments:C(H(s6)),_meta:C(u({}))}),$4=K.extend({method:P("notifications/prompts/list_changed"),params:j.optional()}),Iv=G({type:P("text"),text:X(),annotations:vv.optional(),_meta:L(X(),x()).optional()}),c$=G({type:P("image"),data:b,mimeType:X(),annotations:vv.optional(),_meta:L(X(),x()).optional()}),g6=G({type:P("audio"),data:b,mimeType:X(),annotations:vv.optional(),_meta:L(X(),x()).optional()}),AI=G({type:P("tool_use"),name:X(),id:X(),input:L(X(),x()),_meta:L(X(),x()).optional()}),ZI=G({type:P("resource"),resource:E([Zv,_6]),annotations:vv.optional(),_meta:L(X(),x()).optional()}),LI=Lv.extend({type:P("resource_link")}),Ev=E([Iv,c$,g6,LI,ZI]),v4=G({role:_,content:Ev}),N6=G({title:X().optional(),readOnlyHint:k().optional(),destructiveHint:k().optional(),idempotentHint:k().optional(),openWorldHint:k().optional()}),EI=K.extend({method:P("notifications/tools/list_changed"),params:j.optional()}),VI=G({name:X().optional()}),kI=G({hints:H(VI).optional(),costPriority:S().min(0).max(1).optional(),speedPriority:S().min(0).max(1).optional(),intelligencePriority:S().min(0).max(1).optional()}),RI=G({mode:l(["auto","required","none"]).optional()}),CI=G({type:P("boolean"),title:X().optional(),description:X().optional(),default:k().optional()}),xI=G({type:P("string"),title:X().optional(),description:X().optional(),minLength:S().optional(),maxLength:S().optional(),format:l(["email","uri","date","date-time"]).optional(),default:X().optional()}),fI=G({type:l(["number","integer"]),title:X().optional(),description:X().optional(),minimum:S().optional(),maximum:S().optional(),default:S().optional()}),yI=G({type:P("string"),title:X().optional(),description:X().optional(),enum:H(X()),default:X().optional()}),uI=G({type:P("string"),title:X().optional(),description:X().optional(),oneOf:H(G({const:X(),title:X()})),default:X().optional()}),iI=G({type:P("string"),title:X().optional(),description:X().optional(),enum:H(X()),enumNames:H(X()).optional(),default:X().optional()}),lI=E([yI,uI]),nI=G({type:P("array"),title:X().optional(),description:X().optional(),minItems:S().optional(),maxItems:S().optional(),items:G({type:P("string"),enum:H(X())}),default:H(X()).optional()}),mI=G({type:P("array"),title:X().optional(),description:X().optional(),minItems:S().optional(),maxItems:S().optional(),items:G({anyOf:H(G({const:X(),title:X()}))}),default:H(X()).optional()}),hI=E([nI,mI]),rI=E([iI,lI,hI]),dI=E([rI,CI,xI,fI]),b6=B.extend({mode:P("form").optional(),message:X(),requestedSchema:G({type:P("object"),properties:L(X(),dI),required:H(X()).optional()}).catchall(x())}),U6=G({type:P("ref/resource"),uri:X()}),J6=G({type:P("ref/prompt"),name:X()}),pI=G({uri:X().startsWith("file://"),name:X().optional(),_meta:L(X(),x()).optional()}),Vv=o.shape,cI=G({experimental:Vv.experimental,sampling:Vv.sampling,elicitation:Vv.elicitation,roots:Vv.roots,extensions:Vv.extensions}),m$=C$.shape,I4=G({experimental:m$.experimental,logging:m$.logging,completions:m$.completions,prompts:m$.prompts,resources:m$.resources,tools:m$.tools,extensions:m$.extensions}),_4=u({progressToken:D.optional(),[k6]:X(),[$I]:Z.optional(),[R6]:cI,[vI]:N.optional()}),X6=G({...V.shape,...T.shape,description:X().optional(),inputSchema:u({$schema:X().optional(),type:P("object")}),outputSchema:u({$schema:X().optional()}).optional(),annotations:N6.optional(),_meta:L(X(),x()).optional()}),tI=G({type:P("tool_result"),toolUseId:X(),content:H(Ev),structuredContent:x().optional(),isError:k().optional(),_meta:L(X(),x()).optional()}),D4=E([Iv,c$,g6,AI,tI]),W6=G({role:_,content:E([D4,H(D4)]),_meta:L(X(),x()).optional()}),g4=X(),N4=u({[ov]:Z.optional().catch(void 0)}),b4=N4.optional();function H$(b$){return u({_meta:b4,resultType:g4.default("complete"),...b$})}let oI=H$({}),Bg=H$({nextCursor:g.optional()}),U4=H$({content:H(Ev),structuredContent:x().optional(),isError:k().optional()}),aI=H$({ttlMs:S().int().min(0),cacheScope:l(["public","private"]),tools:H(X6),nextCursor:g.optional()}),eI=H$({ttlMs:S().int().min(0),cacheScope:l(["public","private"]),prompts:H(D6),nextCursor:g.optional()}),sI=H$({description:X().optional(),messages:H(v4)}),$_=H$({ttlMs:S().int().min(0),cacheScope:l(["public","private"]),resources:H(Lv),nextCursor:g.optional()}),v_=H$({ttlMs:S().int().min(0),cacheScope:l(["public","private"]),resourceTemplates:H(a6),nextCursor:g.optional()}),I_=H$({ttlMs:S().int().min(0),cacheScope:l(["public","private"]),contents:H(E([Zv,_6]))}),__=H$({completion:G({values:H(X()).max(100),total:S().int().optional(),hasMore:k().optional()}).loose()}),jg=H$({ttlMs:S().int().min(0),cacheScope:l(["public","private"])}),D_=H$({ttlMs:S().int().min(0).catch(0),cacheScope:l(["public","private"]).catch("private"),supportedVersions:H(X()),capabilities:I4,instructions:X().optional()}),kv=G({messages:H(W6),modelPreferences:kI.optional(),systemPrompt:X().optional(),includeContext:l(["none","thisServer","allServers"]).optional(),temperature:S().optional(),maxTokens:S().int(),stopSequences:H(X()).optional(),metadata:v.optional(),tools:H(X6).optional(),toolChoice:RI.optional()}),g_=G({method:P("sampling/createMessage"),params:kv}),N_=G({method:P("roots/list"),params:G({_meta:L(X(),x()).optional()}).optional()}),b_=G({...W6.shape,model:X(),stopReason:X().optional()}),U_=G({roots:H(pI)}),J_=G({action:l(["accept","decline","cancel"]),content:L(X(),E([X(),S(),k(),H(X())])).optional()}),X_=G({mode:P("url"),message:X(),url:X().url()}),W_=E([b6,X_]),Q_=G({method:P("elicitation/create"),params:W_}),Y_=E([g_,N_,Q_]),G_=E([b_,U_,J_]),B_=L(X(),Y_),j_=L(X(),G_),Q6=H$({inputRequests:B_.optional(),requestState:X().optional()}),Y6={inputResponses:j_.optional(),requestState:X().optional()},zg=G({_meta:_4,...Y6}),Kg=u({progressToken:D.optional()});function x$(b$,B6){return G({method:P(b$),params:G({_meta:_4,...B6})})}function f$(b$,B6){return G({method:P(b$),params:G({_meta:Kg.optional(),...B6}).optional()})}let z_={name:X(),arguments:L(X(),x()).optional(),...Y6},t$={cursor:g.optional()},Og=x$("tools/call",z_),Hg=x$("tools/list",t$),Fg=x$("prompts/list",t$),Pg=x$("prompts/get",{name:X(),arguments:L(X(),X()).optional(),...Y6}),wg=x$("resources/list",t$),qg=x$("resources/templates/list",t$),Mg=x$("resources/read",{uri:X(),...Y6}),K_={ref:E([J6,U6]),argument:G({name:X(),value:X()}),context:G({arguments:L(X(),X()).optional()}).optional()},Tg=x$("completion/complete",K_),Sg=x$("server/discover",{}),J4=G({toolsListChanged:k().optional(),promptsListChanged:k().optional(),resourcesListChanged:k().optional(),resourceSubscriptions:H(X()).optional()}),O_={notifications:J4},Ag=x$("subscriptions/listen",O_),Zg=N4.extend({"io.modelcontextprotocol/subscriptionId":I}),Lg=u({_meta:Zg,resultType:g4.default("complete")}),Rv={"tools/call":f$("tools/call",z_),"tools/list":f$("tools/list",t$),"prompts/get":f$("prompts/get",{name:X(),arguments:L(X(),X()).optional()}),"prompts/list":f$("prompts/list",t$),"resources/list":f$("resources/list",t$),"resources/templates/list":f$("resources/templates/list",t$),"resources/read":f$("resources/read",{uri:X()}),"completion/complete":f$("completion/complete",K_),"server/discover":f$("server/discover",{}),"subscriptions/listen":f$("subscriptions/listen",O_)};function Z$(b$){return u({_meta:b4,...b$})}let Eg={"tools/call":Z$({content:H(Ev),structuredContent:x().optional(),isError:k().optional()}),"tools/list":Z$({ttlMs:S().int().min(0),cacheScope:l(["public","private"]),tools:H(X6),nextCursor:g.optional()}),"prompts/get":Z$({description:X().optional(),messages:H(v4)}),"prompts/list":Z$({ttlMs:S().int().min(0),cacheScope:l(["public","private"]),prompts:H(D6),nextCursor:g.optional()}),"resources/list":Z$({ttlMs:S().int().min(0),cacheScope:l(["public","private"]),resources:H(Lv),nextCursor:g.optional()}),"resources/templates/list":Z$({ttlMs:S().int().min(0),cacheScope:l(["public","private"]),resourceTemplates:H(a6),nextCursor:g.optional()}),"resources/read":Z$({ttlMs:S().int().min(0),cacheScope:l(["public","private"]),contents:H(E([Zv,_6]))}),"completion/complete":Z$({completion:G({values:H(X()).max(100),total:S().int().optional(),hasMore:k().optional()}).loose()}),"server/discover":Z$({ttlMs:S().int().min(0).catch(0),cacheScope:l(["public","private"]).catch("private"),supportedVersions:H(X()),capabilities:I4,instructions:X().optional()}),"subscriptions/listen":Z$({})},G6=u({"io.modelcontextprotocol/subscriptionId":I.optional()}),X4=G({method:P("notifications/subscriptions/acknowledged"),params:G({_meta:G6.optional(),notifications:J4})}),W4=G({_meta:G6.optional(),requestId:I,reason:X().optional()}),Q4=G({method:P("notifications/cancelled"),params:W4}),BU={"notifications/cancelled":Q4,"notifications/progress":$v,"notifications/message":I6,"notifications/resources/updated":e6,"notifications/resources/list_changed":Bv,"notifications/tools/list_changed":EI,"notifications/prompts/list_changed":$4,"notifications/subscriptions/acknowledged":X4},L$=(b$)=>G({jsonrpc:P("2.0"),id:E([X(),S().int()]),result:b$}).strict();return{JSONValueSchema:$,JSONObjectSchema:v,ProgressTokenSchema:D,CursorSchema:g,RequestIdSchema:I,RoleSchema:_,LoggingLevelSchema:N,TaskMetadataSchema:U,RelatedTaskMetadataSchema:J,RequestMetaSchema:W,BaseRequestParamsSchema:Y,TaskAugmentedRequestParamsSchema:B,NotificationsParamsSchema:j,NotificationSchema:K,IconSchema:F,IconsSchema:T,BaseMetadataSchema:V,ImplementationSchema:Z,ClientTasksCapabilitySchema:t,ServerTasksCapabilitySchema:y,ClientCapabilitiesSchema:o,ServerCapabilitiesSchema:C$,ProgressSchema:W$,ProgressNotificationParamsSchema:n$,ProgressNotificationSchema:$v,LoggingMessageNotificationParamsSchema:v6,LoggingMessageNotificationSchema:I6,ResourceContentsSchema:o6,TextResourceContentsSchema:Zv,BlobResourceContentsSchema:_6,AnnotationsSchema:vv,ResourceSchema:Lv,ResourceTemplateSchema:a6,ResourceListChangedNotificationSchema:Bv,ResourceUpdatedNotificationParamsSchema:jv,ResourceUpdatedNotificationSchema:e6,PromptArgumentSchema:s6,PromptSchema:D6,PromptListChangedNotificationSchema:$4,TextContentSchema:Iv,ImageContentSchema:c$,AudioContentSchema:g6,ToolUseContentSchema:AI,EmbeddedResourceSchema:ZI,ResourceLinkSchema:LI,ContentBlockSchema:Ev,PromptMessageSchema:v4,ToolAnnotationsSchema:N6,ToolListChangedNotificationSchema:EI,ModelHintSchema:VI,ModelPreferencesSchema:kI,ToolChoiceSchema:RI,BooleanSchemaSchema:CI,StringSchemaSchema:xI,NumberSchemaSchema:fI,UntitledSingleSelectEnumSchemaSchema:yI,TitledSingleSelectEnumSchemaSchema:uI,LegacyTitledEnumSchemaSchema:iI,SingleSelectEnumSchemaSchema:lI,UntitledMultiSelectEnumSchemaSchema:nI,TitledMultiSelectEnumSchemaSchema:mI,MultiSelectEnumSchemaSchema:hI,EnumSchemaSchema:rI,PrimitiveSchemaDefinitionSchema:dI,ElicitRequestFormParamsSchema:b6,ResourceTemplateReferenceSchema:U6,PromptReferenceSchema:J6,RootSchema:pI,ClientCapabilities2026Schema:cI,ServerCapabilities2026Schema:I4,RequestMetaEnvelopeSchema:_4,ToolSchema:X6,ToolResultContentSchema:tI,SamplingMessageContentBlockSchema:D4,SamplingMessageSchema:W6,ResultTypeSchema:g4,ResultMetaSchema:N4,ResultSchema:oI,PaginatedResultSchema:Bg,CallToolResultSchema:U4,ListToolsResultSchema:aI,ListPromptsResultSchema:eI,GetPromptResultSchema:sI,ListResourcesResultSchema:$_,ListResourceTemplatesResultSchema:v_,ReadResourceResultSchema:I_,CompleteResultSchema:__,CacheableResultSchema:jg,DiscoverResultSchema:D_,CreateMessageRequestParamsSchema:kv,CreateMessageRequestSchema:g_,ListRootsRequestSchema:N_,CreateMessageResultSchema:b_,ListRootsResultSchema:U_,ElicitResultSchema:J_,ElicitRequestURLParamsSchema:X_,ElicitRequestParamsSchema:W_,ElicitRequestSchema:Q_,InputRequestSchema:Y_,InputResponseSchema:G_,InputRequestsSchema:B_,InputResponsesSchema:j_,InputRequiredResultSchema:Q6,InputResponseRequestParamsSchema:zg,CallToolRequestSchema:Og,ListToolsRequestSchema:Hg,ListPromptsRequestSchema:Fg,GetPromptRequestSchema:Pg,ListResourcesRequestSchema:wg,ListResourceTemplatesRequestSchema:qg,ReadResourceRequestSchema:Mg,CompleteRequestSchema:Tg,DiscoverRequestSchema:Sg,SubscriptionFilterSchema:J4,SubscriptionsListenRequestSchema:Ag,SubscriptionsListenResultMetaSchema:Zg,SubscriptionsListenResultSchema:Lg,dispatchRequestSchemas:Rv,dispatchResultSchemas:Eg,NotificationMetaSchema:G6,SubscriptionsAcknowledgedNotificationSchema:X4,CancelledNotificationParamsSchema:W4,CancelledNotificationSchema:Q4,notificationSchemas2026:BU,JSONRPCResultResponseSchema:L$(oI),CallToolResultResponseSchema:L$(E([U4,Q6])),ListToolsResultResponseSchema:L$(aI),ListPromptsResultResponseSchema:L$(eI),GetPromptResultResponseSchema:L$(E([sI,Q6])),ListResourcesResultResponseSchema:L$($_),ListResourceTemplatesResultResponseSchema:L$(v_),ReadResourceResultResponseSchema:L$(E([I_,Q6])),CompleteResultResponseSchema:L$(__),DiscoverResultResponseSchema:L$(D_)}}var mz;function c6(){return mz??=nz()}var hz=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function rz($){return hz.includes($)}var I9=Symbol("modelcontextprotocol.resultCacheHintFallback");function dz($){return $[I9]}function cG($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function tG($){return $==="public"||$==="private"}var p=function($){return $[$.ParseError=-32700]="ParseError",$[$.InvalidRequest=-32600]="InvalidRequest",$[$.MethodNotFound=-32601]="MethodNotFound",$[$.InvalidParams=-32602]="InvalidParams",$[$.InternalError=-32603]="InternalError",$[$.ResourceNotFound=-32002]="ResourceNotFound",$[$.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",$[$.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",$[$.UrlElicitationRequired=-32042]="UrlElicitationRequired",$}({}),O$=class $ extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](v){return l$(this,v)}static isInstance(v){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return l$(this,v)}constructor(v,D,g){super(D);this.code=v,this.data=g,this.name="ProtocolError",t6(this,new.target)}static fromError(v,D,g){if(v===p.UrlElicitationRequired&&g){let I=g;if(I.elicitations)return new aG(I.elicitations,D)}if(v===p.UnsupportedProtocolVersion&&g){let I=g;if(Array.isArray(I.supported)&&typeof I.requested==="string")return new eG({supported:I.supported,requested:I.requested},D)}if(v===p.InvalidParams||v===p.ResourceNotFound){let I=g;if(typeof I?.uri==="string"&&(v===p.ResourceNotFound||Object.keys(I).length===1))return new oG(I.uri,D)}if(v===p.MissingRequiredClientCapability&&g){let I=g;if(I.requiredCapabilities!==null&&typeof I.requiredCapabilities==="object"&&!Array.isArray(I.requiredCapabilities))return new sG({requiredCapabilities:I.requiredCapabilities},D)}return new $(v,D,g)}},oG=class extends O${static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor($,v=`Resource not found: ${$}`){super(p.InvalidParams,v,{uri:$})}get uri(){return this.data.uri}},aG=class extends O${static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor($,v=`URL elicitation${$.length>1?"s":""} required`){super(p.UrlElicitationRequired,v,{elicitations:$})}get elicitations(){return this.data?.elicitations??[]}},eG=class extends O${static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor($,v=`Unsupported protocol version: ${$.requested}`){super(p.UnsupportedProtocolVersion,v,$)}get supported(){return this.data.supported}get requested(){return this.data.requested}},sG=class extends O${static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor($,v=`Missing required client capabilities: ${Object.keys($.requiredCapabilities).join(", ")}`){super(p.MissingRequiredClientCapability,v,$)}get requiredCapabilities(){return this.data.requiredCapabilities}},pz=0,cz="private",tz=["tools/call","prompts/get","resources/read"];function oz($,v){let D=v.resultType;if(D===void 0)return{...v,resultType:"complete"};if(D==="complete")return v;if(tz.includes($))return v;throw new O$(p.InternalError,`Handler for ${$} returned resultType '${String(D)}', but results of ${$} only support 'complete' on protocol revision 2026-07-28`)}function az($,v){let D=dz(v);if(v.resultType!=="complete"||!rz($))return D===void 0?v:IK(v);let g=v,I=cG(g.ttlMs)?g.ttlMs:$K(D),_=tG(g.cacheScope)?g.cacheScope:vK(D),N={...g,ttlMs:I,cacheScope:_};return delete N[I9],N}function ez($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function sz($,v){if(v===void 0)return $;let D=$._meta;if(D===void 0)return{...$,_meta:{[ov]:v}};if(!ez(D))return $;if(D[ov]!==void 0)return $;return{...$,_meta:{...D,[ov]:v}}}function $K($){return $!==void 0&&cG($.ttlMs)?$.ttlMs:pz}function vK($){return $!==void 0&&tG($.cacheScope)?$.cacheScope:cz}function IK($){let v={...$};return delete v[I9],v}var _K=["elicitation/create","sampling/createMessage","roots/list"],JU;function $B(){if(JU)return JU;let $=c6();return JU={request:{"elicitation/create":G({method:P("elicitation/create"),params:$.ElicitRequestParamsSchema}),"sampling/createMessage":G({method:P("sampling/createMessage"),params:$.CreateMessageRequestParamsSchema}),"roots/list":G({method:P("roots/list"),params:u({}).optional()})},response:{"elicitation/create":$.ElicitResultSchema,"sampling/createMessage":$.CreateMessageResultSchema,"roots/list":$.ListRootsResultSchema}},JU}function vB($){return _K.includes($)}function mQ($){return vB($)?$B().request[$]:void 0}function DK($){return vB($)?$B().response[$]:void 0}var _9={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},IB={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};function _B($){return Object.prototype.hasOwnProperty.call(_9,$)}function DB($){return Object.prototype.hasOwnProperty.call(IB,$)}function gK($){return Object.prototype.hasOwnProperty.call(_9,$)}function NK($){return _B($)?c6().dispatchRequestSchemas[$]:void 0}function bK($){return gK($)?c6().dispatchResultSchemas[$]:void 0}function UK($){return DB($)?c6().notificationSchemas2026[$]:void 0}var ow=Object.keys(_9),aw=Object.keys(IB);function Xg($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function Ug($,v){if($===void 0)return{ok:!1,reason:"not-in-era"};let D=$.safeParse(v);return D.success?{ok:!0,value:D.data}:{ok:!1,reason:"invalid",message:String(D.error)}}var JK={ok:!1,reason:"not-in-era"},XK=[k6,R6];function WK($,v){let D=v,g=!1,I=()=>{if(!g)D={...D},g=!0;return D},_=v.tools;if($==="tools/list"&&Array.isArray(_)&&_.some((b)=>Xg(b)&&("execution"in b)))I().tools=_.map((b)=>{if(!Xg(b)||!("execution"in b))return b;let U={...b};return delete U.execution,U});let N=v.capabilities;if(Xg(N)&&"tasks"in N){let b={...N};delete b.tasks,I().capabilities=b}return D}var D9={era:"2026-07-28",hasRequestMethod:_B,hasNotificationMethod:DB,hasInputRequestMethod:($)=>mQ($)!==void 0,validateRequest:($,v)=>Ug(NK($),v),validateResult:($,v)=>Ug(bK($),v),validateNotification:($,v)=>Ug(UK($),v),validateInputRequest:($,v)=>Ug(mQ($),v),validateInputResponse:($,v)=>Ug(DK($),v),samplingResultVariant:()=>JK,outboundEnvelope($){return{[k6]:$.protocolVersion,[$I]:$.clientInfo,[R6]:$.clientCapabilities,...$.logLevel!==void 0&&{[vI]:$.logLevel}}},validateEnvelopeMeta($){let v=[];for(let g of XK)if(!(g in $))v.push({key:g,problem:"missing"});let D=c6().RequestMetaEnvelopeSchema.safeParse($);if(!D.success)for(let g of D.error.issues){let I=g.path.map(String),_=I.length>0?I.join("."):"_meta";if(I.length===1&&v.some((N)=>N.key===_&&N.problem==="missing"))continue;v.push({key:_,problem:g.message})}return v},projectCallToolResult:($)=>iG($),inputRequestSchema:mQ,decodeResult($,v){if(!Xg(v))return{kind:"invalid",error:new U$(K$.InvalidResult,`Invalid result for ${$}: not an object`,{method:$})};let D=v.resultType;if(D===void 0)return{kind:"invalid",error:new U$(K$.InvalidResult,`Invalid result for ${$}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:$,violation:"missing-resultType"})};if(typeof D!=="string")return{kind:"invalid",error:new U$(K$.InvalidResult,`Invalid result for ${$}: non-string resultType`,{method:$,resultType:D})};if(D==="input_required"){let N=v.inputRequests,b=Xg(N)?N:{},U=v.requestState;if(Object.keys(b).length===0&&typeof U!=="string")return{kind:"invalid",error:new U$(K$.InvalidResult,`Invalid result for ${$}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:$,violation:"input-required-missing-both"})};return{kind:"input_required",inputRequests:b,...typeof U==="string"&&{requestState:U}}}if(D!=="complete")return{kind:"invalid",error:new U$(K$.UnsupportedResultType,`Unsupported result type '${D}' for ${$}`,{resultType:D,method:$})};let g=QK(),I=Object.hasOwn(g,$)?g[$]:void 0;if(I!==void 0){let N=I.safeParse(v);if(!N.success)return{kind:"invalid",error:new U$(K$.InvalidResult,`Invalid result for ${$}: ${N.error}`,{method:$})}}let _={...v};return delete _.resultType,{kind:"complete",result:_}},encodeResult($,v,D){return sz(az($,oz($,WK($,v))),D)},encodeErrorCode:($)=>$===-32002?-32602:$,checkInboundEnvelope($){if($.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let v=c6().RequestMetaEnvelopeSchema.safeParse($.envelope);if(!v.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${v.error.issues.map((D)=>D.message).join("; ")}`}},XU;function QK(){if(XU)return XU;let $=c6();return XU={"tools/call":$.CallToolResultSchema,"tools/list":$.ListToolsResultSchema,"prompts/get":$.GetPromptResultSchema,"prompts/list":$.ListPromptsResultSchema,"resources/list":$.ListResourcesResultSchema,"resources/templates/list":$.ListResourceTemplatesResultSchema,"resources/read":$.ReadResourceResultSchema,"completion/complete":$.CompleteResultSchema,"server/discover":$.DiscoverResultSchema},XU}var g9="2026-07-28";function Qg($){return $!==void 0&&uG($)?D9:v9}function kG($){if($.revision!==void 0)return Qg($.revision).era;return $.era==="modern"?D9.era:v9.era}function hQ($){return gB.some((v)=>v.hasRequestMethod($))}function rQ($){return gB.some((v)=>v.hasNotificationMethod($))}var gB=[v9,D9],YK=E9({AnnotationsSchema:()=>Qv,AudioContentSchema:()=>n6,BaseMetadataSchema:()=>Xv,BaseRequestParamsSchema:()=>G$,BlobResourceContentsSchema:()=>BI,BooleanSchemaSchema:()=>OI,CallToolRequestParamsSchema:()=>j1,CallToolRequestSchema:()=>z1,CallToolResultSchema:()=>$6,CancelTaskRequestSchema:()=>ab,CancelTaskResultSchema:()=>eb,CancelledNotificationParamsSchema:()=>qD,CancelledNotificationSchema:()=>UI,ClientCapabilitiesSchema:()=>TD,ClientNotificationSchema:()=>$U,ClientRequestSchema:()=>sb,ClientResultSchema:()=>vU,ClientTasksCapabilitySchema:()=>yb,CompatibilityCallToolResultSchema:()=>ib,CompleteRequestParamsSchema:()=>h1,CompleteRequestSchema:()=>r1,CompleteResultSchema:()=>d1,ContentBlockSchema:()=>Yv,CreateMessageRequestParamsSchema:()=>Z1,CreateMessageRequestSchema:()=>L1,CreateMessageResultSchema:()=>E1,CreateMessageResultWithToolsSchema:()=>V1,CreateTaskResultSchema:()=>mb,CursorSchema:()=>_I,DiscoverRequestSchema:()=>ED,DiscoverResultSchema:()=>XI,ElicitRequestFormParamsSchema:()=>p6,ElicitRequestParamsSchema:()=>f1,ElicitRequestSchema:()=>y1,ElicitRequestURLParamsSchema:()=>x1,ElicitResultSchema:()=>l1,ElicitationCompleteNotificationParamsSchema:()=>u1,ElicitationCompleteNotificationSchema:()=>i1,EmbeddedResourceSchema:()=>m6,EmptyResultSchema:()=>ev,EnumSchemaSchema:()=>C1,GetPromptRequestParamsSchema:()=>N1,GetPromptRequestSchema:()=>b1,GetPromptResultSchema:()=>X1,GetTaskPayloadRequestSchema:()=>pb,GetTaskPayloadResultSchema:()=>cb,GetTaskRequestSchema:()=>rb,GetTaskResultSchema:()=>db,IconSchema:()=>MD,IconsSchema:()=>qv,ImageContentSchema:()=>l6,ImplementationSchema:()=>Wv,InitializeRequestParamsSchema:()=>SD,InitializeRequestSchema:()=>AD,InitializeResultSchema:()=>ZD,InitializedNotificationSchema:()=>LD,JSONArraySchema:()=>xb,JSONObjectSchema:()=>_$,JSONRPCErrorResponseSchema:()=>f6,JSONRPCMessageSchema:()=>y6,JSONRPCNotificationSchema:()=>bI,JSONRPCRequestSchema:()=>NI,JSONRPCResponseSchema:()=>fb,JSONRPCResultResponseSchema:()=>x6,JSONValueSchema:()=>wv,LegacyTitledEnumSchemaSchema:()=>PI,ListChangedOptionsBaseSchema:()=>lb,ListPromptsRequestSchema:()=>D1,ListPromptsResultSchema:()=>g1,ListResourceTemplatesRequestSchema:()=>yD,ListResourceTemplatesResultSchema:()=>uD,ListResourcesRequestSchema:()=>xD,ListResourcesResultSchema:()=>fD,ListRootsRequestSchema:()=>c1,ListRootsResultSchema:()=>t1,ListTasksRequestSchema:()=>tb,ListTasksResultSchema:()=>ob,ListToolsRequestSchema:()=>G1,ListToolsResultSchema:()=>B1,LoggingLevelSchema:()=>KI,LoggingMessageNotificationParamsSchema:()=>F1,LoggingMessageNotificationSchema:()=>P1,ModelHintSchema:()=>w1,ModelPreferencesSchema:()=>q1,MultiSelectEnumSchemaSchema:()=>R1,NotificationSchema:()=>z$,NotificationsParamsSchema:()=>w$,NumberSchemaSchema:()=>d6,PaginatedRequestParamsSchema:()=>RD,PaginatedRequestSchema:()=>Mv,PaginatedResultSchema:()=>Tv,PingRequestSchema:()=>WI,PrimitiveSchemaDefinitionSchema:()=>MI,ProgressNotificationParamsSchema:()=>kD,ProgressNotificationSchema:()=>QI,ProgressSchema:()=>VD,ProgressTokenSchema:()=>II,PromptArgumentSchema:()=>I1,PromptListChangedNotificationSchema:()=>W1,PromptMessageSchema:()=>J1,PromptReferenceSchema:()=>m1,PromptSchema:()=>_1,ReadResourceRequestParamsSchema:()=>iD,ReadResourceRequestSchema:()=>lD,ReadResourceResultSchema:()=>nD,RelatedTaskMetadataSchema:()=>wD,RequestIdSchema:()=>s$,RequestMetaSchema:()=>DI,RequestSchema:()=>D$,ResourceContentsSchema:()=>YI,ResourceLinkSchema:()=>h6,ResourceListChangedNotificationSchema:()=>mD,ResourceRequestParamsSchema:()=>u6,ResourceSchema:()=>jI,ResourceTemplateReferenceSchema:()=>n1,ResourceTemplateSchema:()=>CD,ResourceUpdatedNotificationParamsSchema:()=>$1,ResourceUpdatedNotificationSchema:()=>v1,ResultMetaObjectSchema:()=>gI,ResultSchema:()=>g$,RoleSchema:()=>Sv,RootSchema:()=>p1,RootsListChangedNotificationSchema:()=>o1,SamplingContentSchema:()=>S1,SamplingMessageContentBlockSchema:()=>tv,SamplingMessageSchema:()=>A1,ServerCapabilitiesSchema:()=>JI,ServerNotificationSchema:()=>_U,ServerRequestSchema:()=>IU,ServerResultSchema:()=>DU,ServerTasksCapabilitySchema:()=>ub,SetLevelRequestParamsSchema:()=>O1,SetLevelRequestSchema:()=>H1,SingleSelectEnumSchemaSchema:()=>k1,StringSchemaSchema:()=>r6,SubscribeRequestParamsSchema:()=>hD,SubscribeRequestSchema:()=>rD,SubscriptionFilterSchema:()=>zI,SubscriptionsAcknowledgedNotificationParamsSchema:()=>oD,SubscriptionsAcknowledgedNotificationSchema:()=>aD,SubscriptionsListenRequestParamsSchema:()=>cD,SubscriptionsListenRequestSchema:()=>tD,SubscriptionsListenResultMetaSchema:()=>eD,SubscriptionsListenResultSchema:()=>sD,TaskAugmentedRequestParamsSchema:()=>av,TaskCreationParamsSchema:()=>nb,TaskMetadataSchema:()=>PD,TaskSchema:()=>Av,TaskStatusNotificationParamsSchema:()=>e1,TaskStatusNotificationSchema:()=>hb,TaskStatusSchema:()=>a1,TextContentSchema:()=>i6,TextResourceContentsSchema:()=>GI,TitledMultiSelectEnumSchemaSchema:()=>qI,TitledSingleSelectEnumSchemaSchema:()=>FI,ToolAnnotationsSchema:()=>Q1,ToolChoiceSchema:()=>M1,ToolExecutionSchema:()=>Y1,ToolListChangedNotificationSchema:()=>K1,ToolResultContentSchema:()=>T1,ToolSchema:()=>sv,ToolUseContentSchema:()=>U1,UnsubscribeRequestParamsSchema:()=>dD,UnsubscribeRequestSchema:()=>pD,UntitledMultiSelectEnumSchemaSchema:()=>wI,UntitledSingleSelectEnumSchemaSchema:()=>HI});var NB=($)=>NI.safeParse($).success,bB=($)=>bI.safeParse($).success,oQ=($)=>x6.safeParse($).success,UB=($)=>f6.safeParse($).success;var Wg=-32020,ew=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32000],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[p.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[Wg,p.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[p.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope — and a missing envelope on a request whose protocol-version header names a modern revision — is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[p.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision’s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[p.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[Wg],conformance:["http-header-validation"],rationale:"SEP-2243 standard `Mcp-Method` / `Mcp-Name` headers — presence, sentinel decoding, and `Mcp-Name` ↔ body cross-check — are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The classifier’s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5–6) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[p.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced — pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[Wg],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool’s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],sw={[p.ParseError]:400,[p.InvalidRequest]:400,[p.MethodNotFound]:404,[p.UnsupportedProtocolVersion]:400,[p.MissingRequiredClientCapability]:400,[Wg]:400};function N9($,v){return JD($,v)}function Jg($){return new Set($.flatMap((v)=>Object.keys(v.shape)))}function aQ($){if($==null)return!1;let v=typeof $;if(v!=="object"&&v!=="function")return!1;if(!("~standard"in $))return!1;return typeof $["~standard"]?.validate==="function"}var RG=!1,eQ="draft-2020-12";function GK($,v="input"){let D=$["~standard"],g;if(D.jsonSchema)g=D.jsonSchema[v]({target:eQ});else if(D.vendor==="zod"){if(!("_zod"in $))throw Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");if(!RG)RG=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.");g=Z6($,{target:eQ,io:v})}else throw Error(`Schema library "${D.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(v==="output"){if(g.type!==void 0)return g;return JB(g)?{type:"object",...g}:g}if(g.type!==void 0&&g.type!=="object")throw Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(g.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...g}}function JB($){if("properties"in $||"patternProperties"in $||"additionalProperties"in $||"required"in $)return!0;for(let v of["oneOf","anyOf","allOf"]){let D=$[v];if(Array.isArray(D)&&D.length>0)return D.every((g)=>g!==null&&typeof g==="object"&&(g.type==="object"||JB(g)))}return!1}function BK($){if(!$.path?.length)return $.message;return`${$.path.map((v)=>String(typeof v==="object"?v.key:v)).join(".")}: ${$.message}`}async function dQ($,v){let D=await $["~standard"].validate(v);if(D.issues&&D.issues.length>0)return{success:!1,error:D.issues.map((g)=>BK(g)).join(", ")};return{success:!0,data:D.value}}function jK($){let v=Z6($,{target:eQ,io:"input"});return typeof v.pattern==="string"?v.pattern:void 0}var zK=/\\\.\\d\{(\d+)\}/;function KK($){let v=zK.exec($),D=[void 0,-1,0];if(v)D.push(Number(v[1]));return[!1,!0].flatMap((g)=>[!1,!0].flatMap((I)=>D.map((_)=>p$.datetime({local:g,offset:I,precision:_}))))}function OK($,v){let D;switch($){case"email":D=[Jb()];break;case"uri":D=[t4()];break;case"date":D=[p$.date()];break;case"date-time":D=KK(v);break}return new Set(D.map((g)=>jK(g)).filter((g)=>g!==void 0))}function HK($,v,D){if(D!=="zod")return!0;return OK($,v).has(v)}function Yg($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function FK($){try{return GK($,"input")}catch(v){let D=v instanceof Error?v.message:String(v);throw new O$(p.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${D}`)}}var PK=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function b9($){return PK.has($)||$.startsWith("x-")}var wK=new Set(["$schema",...Object.keys(p6.shape.requestedSchema.shape)]),CG={string:Jg([r6,HI,FI,PI]),number:Jg([d6]),integer:Jg([d6]),boolean:Jg([OI]),array:Jg([wI,qI])},qK=new Set(r6.shape.format.unwrap().options);function MK($,v,D,g){if(!Yg($))return $;let I=typeof $.type==="string"&&Object.hasOwn(CG,$.type)?CG[$.type]:void 0;if(I===void 0)return $;let _={};for(let[N,b]of Object.entries($))if(I.has(N)||b9(N))_[N]=b;else if(N==="pattern"&&$.type==="string"&&typeof $.format==="string"){if(!qK.has($.format))_[N]=b;else if(typeof b!=="string"||!HK($.format,b,D))g.push(`${v}.${N}`)}else g.push(`${v}.${N}`);return _}function TK($,v){let D={},g=[];for(let[I,_]of Object.entries($))if(I==="properties"&&Yg(_))D[I]=Object.fromEntries(Object.entries(_).map(([N,b])=>[N,MK(b,`properties.${N}`,v,g)]));else if(wK.has(I))D[I]=_;else if(!b9(I))g.push(I);if(g.length>0)throw new O$(p.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${g.join(", ")}`);return D}function SK($,v){if(!Yg($.properties))return v;let D=Object.entries($.properties).filter(([,g])=>!N9(MI,g).success).map(([g])=>`properties.${g}`);return D.length>0?D.join(", "):v}function sQ($,v,D=""){if(Array.isArray($)&&Array.isArray(v))return $.flatMap((g,I)=>sQ(g,v[I],`${D}[${I}]`));if(!Yg($)||!Yg(v))return[];return Object.entries($).flatMap(([g,I])=>{let _=D?`${D}.${g}`:g;if(!Object.prototype.hasOwnProperty.call(v,g))return b9(g)?[]:[_];return sQ(I,v[g],_)})}function AK($){if(!aQ($.requestedSchema))return{...$,mode:"form",requestedSchema:$.requestedSchema};let v=$.requestedSchema["~standard"].vendor,D=TK(FK($.requestedSchema),v),g=N9(p6.shape.requestedSchema,D);if(!g.success)throw new O$(p.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${SK(D,g.error.message)}`);let I=sQ(D,g.data);if(I.length>0)throw new O$(p.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${I.join(", ")}`);let _=(g.data.required??[]).filter((N)=>!Object.prototype.hasOwnProperty.call(g.data.properties,N));if(_.length>0)throw new O$(p.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${_.join(", ")}`);return{...$,mode:"form",requestedSchema:g.data}}function ZK($){let v=$.inputRequests!==void 0&&Object.keys($.inputRequests).length>0,D=typeof $.requestState==="string";if(!v&&!D)throw TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...$.inputRequests!==void 0&&{inputRequests:$.inputRequests},...$.requestState!==void 0&&{requestState:$.requestState}}}var $q=Object.assign(ZK,{elicit($){try{return{method:"elicitation/create",params:AK($)}}catch(v){throw v instanceof O$?TypeError(v.message,{cause:v}):v}},elicitUrl($){return{method:"elicitation/create",params:{...$,mode:"url"}}},createMessage($){return{method:"sampling/createMessage",params:$}},listRoots(){return{method:"roots/list"}}});var LK=["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"],EK={IdJagTokenExchangeResponseSchema:_g,OAuthClientInformationFullSchema:bg,OAuthClientInformationSchema:Ng,OAuthClientMetadataSchema:gg,OAuthClientRegistrationErrorSchema:gU,OAuthErrorResponseSchema:Dg,OAuthMetadataSchema:TI,OAuthProtectedResourceMetadataSchema:s1,OAuthTokenRevocationRequestSchema:NU,OAuthTokensSchema:Ig,OpenIdProviderDiscoveryMetadataSchema:vg,OpenIdProviderMetadataSchema:$g},XB={},WB={};function QB($,v){let D=$.slice(0,-6);XB[D]=v,WB[D]=(g)=>v.safeParse(g).success}for(let $ of LK)QB($,YK[$]);for(let[$,v]of Object.entries(EK))QB($,v);var VK=Object.freeze(XB),kK=Object.freeze(WB);function RK($){switch($){case"initialize":case"notifications/initialized":return Qg(void 0);case"server/discover":return Qg(g9);default:return}}var YB=60000,CK=[k6,$I,R6,vI],xK=["inputResponses","requestState"];function xG($,v){let D=$.params;if(!pQ(D))return{message:$,lifted:{}};let g=D._meta,I=pQ(g)?CK.filter((U)=>(U in g)):[],_=v==="request"?xK.filter((U)=>(U in D)):[];if(I.length===0&&_.length===0)return{message:$,lifted:{}};let N={},b={...D};if(I.length>0&&pQ(g)){let U={},J={...g};for(let W of I)U[W]=g[W],delete J[W];if(N.envelope=U,Object.keys(J).length>0)b._meta=J;else delete b._meta}for(let U of _){if(U==="inputResponses")N.inputResponses=b[U];if(U==="requestState")N.requestState=b[U];delete b[U]}return{message:{...$,params:b},lifted:N}}function fG($,v){let D=$.validateResult(v,void 0);if(!D.ok&&D.reason==="not-in-era")return;return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(g){let I=$.validateResult(v,g);if(I.ok)return{value:I.value};return{issues:[{message:I.reason==="invalid"?I.message:`not-in-era: ${v}`}]}}}}}function GB($){return()=>$}var fK=GB(void 0),yK,U9=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{yK=($,v)=>{$._negotiatedProtocolVersion=v}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor($){this._options=$,this._supportedProtocolVersions=$?.supportedProtocolVersions??kb,this.setNotificationHandler("notifications/cancelled",(v)=>{this._oncancel(v)}),this.setNotificationHandler("notifications/progress",(v)=>{this._onprogress(v)}),this.setRequestHandler("ping",(v)=>({}))}_shouldDropInbound($){}_outboundMetaEnvelope(){}_envelopeOutbound($){let v=this._outboundMetaEnvelope();if(v===void 0)return $;let D=$.params??{};return{...$,params:{...D,_meta:{...v,...D._meta}}}}_resolveNonCompleteResult($,v){return Promise.reject(new U$(K$.UnsupportedResultType,`Unsupported result type '${$.kind}' for ${v.request.method}`,{resultType:$.kind,method:v.request.method}))}_getRequestHandler($){return this._requestHandlers.get($)}async _oncancel($){if(!$.params.requestId)return;this._requestHandlerAbortControllers.get($.params.requestId)?.abort($.params.reason)}_setupTimeout($,v,D,g,I=!1){this._timeoutInfo.set($,{timeoutId:setTimeout(g,v),startTime:Date.now(),timeout:v,maxTotalTimeout:D,resetTimeoutOnProgress:I,onTimeout:g})}_resetTimeout($){let v=this._timeoutInfo.get($);if(!v)return!1;let D=Date.now()-v.startTime;if(v.maxTotalTimeout&&D>=v.maxTotalTimeout)throw this._timeoutInfo.delete($),new U$(K$.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:v.maxTotalTimeout,totalElapsed:D});return clearTimeout(v.timeoutId),v.timeoutId=setTimeout(v.onTimeout,v.timeout),!0}_cleanupTimeout($){let v=this._timeoutInfo.get($);if(v)clearTimeout(v.timeoutId),this._timeoutInfo.delete($)}async connect($){this._transport=$;let v=this.transport?.onclose;this._transport.onclose=()=>{try{v?.()}finally{this._onclose()}};let D=this.transport?.onerror;this._transport.onerror=(I)=>{D?.(I),this._onerror(I)};let g=this._transport?.onmessage;this._transport.onmessage=(I,_)=>{if(g?.(I,_),oQ(I)||UB(I))this._onresponse(I);else if(NB(I))this._onrequest(I,_);else if(bB(I))this._onnotification(I,_);else this._onerror(Error(`Unknown message type: ${JSON.stringify(I)}`))},$.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let $=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let g of this._timeoutInfo.values())clearTimeout(g.timeoutId);this._timeoutInfo.clear();let v=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let D=new U$(K$.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let g of $.values())g(D);for(let g of v.values())g.abort(D)}}_onerror($){this.onerror?.($)}_onnotification($,v){let{message:D}=xG($,"notification"),g=this._negotiatedWireCodec();if(v?.classification===void 0&&this._shouldDropInbound($)==="drop")return;if(v?.classification!==void 0){let N=kG(v.classification);if(N!==g.era){this._onerror(Error(`Era mismatch on inbound notification '${D.method}': classified as ${N} but this instance serves ${g.era}`));return}}if(rQ(D.method)&&!g.hasNotificationMethod(D.method))return;let I=this._notificationHandlers.get(D.method),_=this.fallbackNotificationHandler;if(I===void 0&&_===void 0)return;Promise.resolve().then(()=>I===void 0?_(D):I(D,g)).catch((N)=>this._onerror(Error(`Uncaught error in notification handler: ${N}`)))}_onrequest($,v){let{message:D,lifted:g}=xG($,"request"),I=this._negotiatedWireCodec();if(v?.classification===void 0&&this._shouldDropInbound($)==="drop"){this._onerror(Error(`Dropped inbound request '${$.method}': not servable on this connection's protocol era`));return}let _=this._transport,N=(F,T,V)=>{let Z={jsonrpc:"2.0",id:D.id,error:{code:F,message:T,...V!==void 0&&{data:V}}};_?.send(Z).catch((f)=>this._onerror(Error(`Failed to send an error response: ${f}`)))};if(v?.classification!==void 0){let F=kG(v.classification);if(F!==I.era){this._onerror(Error(`Era mismatch on inbound request '${D.method}': classified as ${F} but this instance serves ${I.era}`));let T=v.classification.revision??F;N(p.UnsupportedProtocolVersion,`Unsupported protocol version: ${T}`,{supported:this._supportedProtocolVersions,requested:T});return}}if(hQ(D.method)&&!I.hasRequestMethod(D.method)){N(p.MethodNotFound,"Method not found");return}let b=this._requestHandlers.get(D.method)??this.fallbackRequestHandler;if(b===void 0){N(p.MethodNotFound,"Method not found");return}let U=I.checkInboundEnvelope(g);if(U!==void 0){N(p.InvalidParams,U);return}let J=(F,T)=>this._notificationViaCodec(this._resolveOutboundCodec(F.method),F,{...T,relatedRequestId:D.id}),W=(F,T,V)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(F.method),F,T,{...V,relatedRequestId:D.id}),Y=new AbortController;this._requestHandlerAbortControllers.set(D.id,Y);let B=g.inputResponses===void 0?void 0:uK(g.inputResponses),j={sessionId:_?.sessionId,mcpReq:{id:D.id,method:D.method,_meta:D.params?._meta,...g.envelope!==void 0&&{envelope:g.envelope},...B!==void 0&&{inputResponses:B.accepted},...B!==void 0&&B.droppedKeys.length>0&&{droppedInputResponseKeys:B.droppedKeys},requestState:g.requestState===void 0?fK:GB(g.requestState),signal:Y.signal,send:(F,T,V)=>{let Z=this._resolveOutboundCodec(F.method);if(this._assertOutboundRequestInEra(Z,F.method),aQ(T))return W(F,T,V);let f=fG(Z,F.method);if(f===void 0)throw TypeError(`'${F.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return W(F,f,T)},notify:J},http:v?.authInfo?{authInfo:v.authInfo}:void 0},K=this.buildContext(j,v);Promise.resolve().then(()=>b(D,K)).then(async(F)=>{if(Y.signal.aborted)return;let T;try{T=I.encodeResult(D.method,F,this._outboundServerInfo())}catch(Z){this._onerror(Error(`Failed to encode result for ${D.method}: ${Z}`)),N(p.InternalError,"Internal error");return}let V={result:T,jsonrpc:"2.0",id:D.id};await _?.send(V)},async(F)=>{if(Y.signal.aborted)return;let T=Number.isSafeInteger(F.code)?F.code:p.InternalError,V={jsonrpc:"2.0",id:D.id,error:{code:I.encodeErrorCode(T),message:F.message??"Internal error",...F.data!==void 0&&{data:F.data}}};await _?.send(V)}).catch((F)=>this._onerror(Error(`Failed to send response: ${F}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(D.id)===Y)this._requestHandlerAbortControllers.delete(D.id)})}_onprogress($){let{progressToken:v,...D}=$.params,g=Number(v),I=this._progressHandlers.get(g);if(!I){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify($)}`));return}let _=this._responseHandlers.get(g),N=this._timeoutInfo.get(g);if(N&&_&&N.resetTimeoutOnProgress)try{this._resetTimeout(g)}catch(b){this._responseHandlers.delete(g),this._progressHandlers.delete(g),this._cleanupTimeout(g),_(b);return}I(D)}_onresponse($){let v=Number($.id),D=this._responseHandlers.get(v);if(D===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify($)}`));return}if(this._responseHandlers.delete(v),this._cleanupTimeout(v),this._progressHandlers.delete(v),oQ($))D($);else D(O$.fromError($.error.code,$.error.message,$.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request($,v,D){let g=this._resolveOutboundCodec($.method);if(this._assertOutboundRequestInEra(g,$.method),aQ(v))return this._requestWithSchemaViaCodec(g,$,v,D);let I=fG(g,$.method);if(I===void 0)throw TypeError(`'${$.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(g,$,I,v)}_negotiatedWireCodec(){return Qg(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec($){if(this._negotiatedProtocolVersion===void 0){let v=RK($);if(v)return v}return this._negotiatedWireCodec()}_assertOutboundRequestInEra($,v){if(hQ(v)&&!$.hasRequestMethod(v))throw new U$(K$.MethodNotSupportedByProtocolVersion,`Method '${v}' is not supported by the negotiated protocol version (wire era ${$.era})`,{method:v,era:$.era})}_requestWithSchema($,v,D){let g=this._resolveOutboundCodec($.method);return this._assertOutboundRequestInEra(g,$.method),this._requestWithSchemaViaCodec(g,$,v,D)}_requestWithSchemaViaCodec($,v,D,g){let{relatedRequestId:I,resumptionToken:_,onresumptiontoken:N,headers:b}=g??{},U=Date.now(),J,W;return new Promise((Y,B)=>{let j=(y)=>{B(y)};if(!this._transport){j(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(v.method)}catch(y){j(y);return}if(g?.signal?.aborted){let y=g.signal.reason;throw y instanceof U$?y:new U$(K$.RequestTimeout,String(y))}let K=$.era===g9&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,F=this._requestMessageId++;W=F;let T={...v,jsonrpc:"2.0",id:F};if(g?.onprogress)this._progressHandlers.set(F,g.onprogress),T.params={...v.params,_meta:{...v.params?._meta,progressToken:F}};let V=this._envelopeOutbound(T),Z=!1,f=(y)=>{if(Z)return;if(this._progressHandlers.delete(F),K===void 0)this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:F,reason:String(y)}}),{relatedRequestId:I,resumptionToken:_,onresumptiontoken:N}).catch((o)=>this._onerror(Error(`Failed to send cancellation: ${o}`)));else K.abort();B(y instanceof U$?y:new U$(K$.RequestTimeout,String(y)))};this._responseHandlers.set(F,(y)=>{if(g?.signal?.aborted)return;if(Z=!0,y instanceof Error)return B(y);let o;try{o=$.decodeResult(v.method,y.result)}catch(W$){return B(W$ instanceof Error?W$:Error(String(W$)))}if(o.kind==="invalid")return B(o.error);if(o.kind==="input_required"){if(g?.allowInputRequired===!0)return Y(iK(o));let W$={codec:$,request:v,resultSchema:D,options:g,flowStartedAt:U,retry:(n$,$v)=>this._requestWithSchemaViaCodec($,n$===void 0?{method:v.method}:{method:v.method,params:n$},D,$v)};return Y(this._resolveNonCompleteResult(o,W$))}let C$=o.result;dQ(D,C$).then((W$)=>{if(W$.success)Y(W$.data);else B(new U$(K$.InvalidResult,`Invalid result for ${v.method}: ${W$.error}`))},B)}),J=()=>f(g?.signal?.reason),g?.signal?.addEventListener("abort",J,{once:!0});let r=g?.timeout??YB,t=()=>f(new U$(K$.RequestTimeout,"Request timed out",{timeout:r}));this._setupTimeout(F,r,g?.maxTotalTimeout,t,g?.resetTimeoutOnProgress??!1),this._transport.send(V,{relatedRequestId:I,resumptionToken:_,onresumptiontoken:N,headers:b,requestSignal:K?.signal}).catch((y)=>{this._progressHandlers.delete(F),B(y)})}).finally(()=>{if(J)g?.signal?.removeEventListener("abort",J);if(W!==void 0)this._responseHandlers.delete(W),this._cleanupTimeout(W)})}async notification($,v){return this._notificationViaCodec(this._resolveOutboundCodec($.method),$,v)}async _notificationViaCodec($,v,D){if(!this._transport)throw new U$(K$.NotConnected,"Not connected");if(rQ(v.method)&&!$.hasNotificationMethod(v.method))throw new U$(K$.MethodNotSupportedByProtocolVersion,`Notification '${v.method}' is not supported by the negotiated protocol version (wire era ${$.era})`,{method:v.method,era:$.era});this.assertNotificationCapability(v.method);let g=this._envelopeOutbound({jsonrpc:"2.0",...v});if((this._options?.debouncedNotificationMethods??[]).includes(v.method)&&!v.params&&!D?.relatedRequestId){if(this._pendingDebouncedNotifications.has(v.method))return;this._pendingDebouncedNotifications.add(v.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(v.method),!this._transport)return;this._transport?.send(g,D).catch((I)=>this._onerror(I))});return}await this._transport.send(g,D)}setRequestHandler($,v,D){this.assertRequestHandlerCapability($);let g;if(typeof v==="function"){if(!hQ($))throw TypeError(`'${$}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);g=(I,_)=>{let N=this._negotiatedWireCodec(),b=N.validateRequest($,I);if(!b.ok&&b.reason==="not-in-era")b=N.validateInputRequest($,I);if(!b.ok){if(b.reason==="not-in-era")throw new O$(p.InternalError,`No wire schema for ${$} in the resolved era`);throw Error(b.message)}return Promise.resolve(v(b.value,_))}}else if(D)g=async(I,_)=>{let N=await dQ(v.params,{...I.params});if(!N.success)throw new O$(p.InvalidParams,`Invalid params for ${$}: ${N.error}`);return D(N.data,_)};else throw TypeError("setRequestHandler: handler is required");this._requestHandlers.set($,this._wrapHandler($,g))}_wrapHandler($,v){return v}_outboundServerInfo(){}removeRequestHandler($){this._requestHandlers.delete($)}assertCanSetRequestHandler($){if(this._requestHandlers.has($))throw Error(`A request handler for ${$} already exists, which would be overridden`)}setNotificationHandler($,v,D){if(typeof v==="function"){if(!rQ($))throw TypeError(`'${$}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set($,(g,I)=>{let _=I.validateNotification($,g);if(!_.ok){if(_.reason==="not-in-era")throw new O$(p.InternalError,`No wire schema for ${$} in the resolved era`);throw Error(_.message)}return Promise.resolve(v(_.value))});return}if(!D)throw TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set($,async(g)=>{let I=await dQ(v.params,{...g.params});if(!I.success)throw new O$(p.InvalidParams,`Invalid params for notification ${$}: ${I.error}`);await D(I.data,g)})}removeNotificationHandler($){this._notificationHandlers.delete($)}};function pQ($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function yG($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function uK($){let v={},D=[];if(!yG($))return{accepted:v,droppedKeys:D};for(let[g,I]of Object.entries($)){if(!yG(I)||"method"in I||"result"in I){D.push(g);continue}v[g]=I}return{accepted:v,droppedKeys:D}}function iK($){return{resultType:"input_required",inputRequests:$.inputRequests,...$.requestState!==void 0&&{requestState:$.requestState}}}/*! +* content-type +* Copyright(c) 2015 Douglas Christopher Wilson +* MIT Licensed +*/var lK=L9(($)=>{var v=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,D=/\\([\u000b\u0020-\u00ff])/g,g=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;$.parse=I;function I(b){if(!b)throw TypeError("argument string is required");var U=typeof b==="object"?_(b):b;if(typeof U!=="string")throw TypeError("argument string is required to be a string");var J=U.indexOf(";"),W=J!==-1?U.slice(0,J).trim():U.trim();if(!g.test(W))throw TypeError("invalid media type");var Y=new N(W.toLowerCase());if(J!==-1){var B,j,K;v.lastIndex=J;while(j=v.exec(U)){if(j.index!==J)throw TypeError("invalid parameter format");if(J+=j[0].length,B=j[1].toLowerCase(),K=j[2],K.charCodeAt(0)===34){if(K=K.slice(1,-1),K.indexOf("\\")!==-1)K=K.replace(D,"$1")}Y.parameters[B]=K}if(J!==U.length)throw TypeError("invalid parameter format")}return Y}function _(b){var U;if(typeof b.getHeader==="function")U=b.getHeader("content-type");else if(typeof b.headers==="object")U=b.headers&&b.headers["content-type"];if(typeof U!=="string")throw TypeError("content-type header is missing from object");return U}function N(b){this.parameters=Object.create(null),this.type=b}}),vq=V9(lK(),1);var Qq=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");var nK=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,mK=[0,31,28,31,30,31,30,31,31,30,31,30,31],hK=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,rK=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,dK=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,pK=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,cK=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,tK=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,oK=/^(?:\/(?:[^~/]|~0|~1)*)*$/,aK=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,eK=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,sK=($)=>{if($[0]==='"')return!1;let[v,D,...g]=$.split("@");if(!v||!D||g.length!==0||v.length>64||D.length>253)return!1;if(v[0]==="."||v.endsWith(".")||v.includes(".."))return!1;if(!/^[a-z0-9.-]+$/i.test(D)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(v))return!1;return D.split(".").every((I)=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(I))},$O=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,vO=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,IO=($)=>$.length>1&&$.length<80&&(/^P\d+([.,]\d+)?W$/.test($)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test($)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test($));function Gv($){return $.test.bind($)}var Yq={date:BB,time:jB.bind(void 0,!1),"date-time":gO,duration:IO,uri:UO,"uri-reference":Gv(dK),"uri-template":Gv(pK),url:Gv(cK),email:sK,hostname:Gv(rK),ipv4:Gv($O),ipv6:Gv(vO),regex:XO,uuid:Gv(tK),"json-pointer":Gv(oK),"json-pointer-uri-fragment":Gv(aK),"relative-json-pointer":Gv(eK)};function _O($){return $%4===0&&($%100!==0||$%400===0)}function BB($){let v=$.match(nK);if(!v)return!1;let D=+v[1],g=+v[2],I=+v[3];return g>=1&&g<=12&&I>=1&&I<=(g==2&&_O(D)?29:mK[g])}function jB($,v){let D=v.match(hK);if(!D)return!1;let g=+D[1],I=+D[2],_=+D[3],N=!!D[5];return(g<=23&&I<=59&&_<=59||g==23&&I==59&&_==60)&&(!$||N)}var DO=/t|\s/i;function gO($){let v=$.split(DO);return v.length==2&&BB(v[0])&&jB(!0,v[1])}var NO=/\/|:/,bO=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function UO($){return NO.test($)&&bO.test($)}var JO=/[^\\]\\Z/;function XO($){if(JO.test($))return!1;try{return new RegExp($,"u"),!0}catch(v){return!1}}var QO;QO=globalThis.crypto;var Gg=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance]($){return l$(this,$)}static isInstance($){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return l$(this,$)}constructor($){super($);this.name=new.target.name,t6(this,new.target)}},DM=class extends Gg{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.IssuerMismatchError"})}kind;expected;received;constructor($,v,D){super(`Issuer mismatch in ${$==="metadata"?"authorization server metadata (RFC 8414 §3.3)":"authorization response (RFC 9207)"}: expected ${JSON.stringify(v)}, received ${JSON.stringify(D)}`);this.kind=$,this.expected=v,this.received=D}},gM=class extends Gg{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.RegistrationRejectedError"})}status;body;submittedMetadata;constructor($){super(`Dynamic Client Registration rejected (HTTP ${$.status}): ${$.body}`);this.status=$.status,this.body=$.body,this.submittedMetadata=$.submittedMetadata}},NM=class extends Gg{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsecureTokenEndpointError"})}tokenEndpoint;constructor($){super(`Refusing to send credentials to non-https token endpoint '${$}'. OAuth token requests MUST use TLS (localhost / 127.0.0.1 / ::1 are exempt).`);this.tokenEndpoint=$}},bM=class extends Gg{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.AuthorizationServerMismatchError"})}constructor($,v){super(`Authorization server changed between redirect and callback (redirected to ${JSON.stringify($)}, callback resolved ${JSON.stringify(v)}); refusing to send authorization_code/code_verifier to a different token endpoint`);this.recordedIssuer=$,this.currentIssuer=v}},UM=class extends Gg{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsufficientScopeError"})}requiredScope;resourceMetadataUrl;errorDescription;constructor($){super(`Insufficient scope${$.requiredScope?`: required "${$.requiredScope}"`:""}`);this.requiredScope=$.requiredScope,this.resourceMetadataUrl=$.resourceMetadataUrl,this.errorDescription=$.errorDescription}};var JM=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance]($){return l$(this,$)}static isInstance($){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return l$(this,$)}constructor($){super($??"Unauthorized");this.name="UnauthorizedError",t6(this,new.target)}};var XM=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance]($){return l$(this,$)}static isInstance($){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return l$(this,$)}constructor($,v,D){super(`SSE error: ${v}`);this.code=$,this.event=D,t6(this,new.target)}};var YO="ui/resourceUri",GO="text/html;profile=mcp-app";class WU{_eventSlots=new Map;setHandler($,v){let D=this._ensureEventSlot($);if(D.onHandler&&v)console.warn(`[MCP Apps] on${String($)} handler replaced. Use addEventListener("${String($)}", …) to add multiple listeners without replacing.`);D.onHandler=v}getHandler($){return this._eventSlots.get($)?.onHandler}addEventListener($,v){this._ensureEventSlot($).listeners.push(v)}removeEventListener($,v){let D=this._eventSlots.get($);if(!D)return;let g=D.listeners.indexOf(v);if(g!==-1)D.listeners.splice(g,1)}dispatch($,v){let D=this._eventSlots.get($);if(!D)return;D.onHandler?.(v);for(let g of[...D.listeners])g(v)}_ensureEventSlot($){let v=this._eventSlots.get($);if(!v)v={listeners:[]},this._eventSlots.set($,v);return v}}class J9{_methods=new Set;claim($,v){if(this._methods.has($))throw Error(`Handler for "${$}" already registered (via ${v}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._methods.add($)}replace($){this._methods.add($)}release($){this._methods.delete($)}has($){return this._methods.has($)}}var zB=new Set;function X9($,v){let[D,g]=v,I=D?.shape;if(typeof I?.method?.value!=="string")return;let _=I.method.value,N=$==="request"?"setRequestHandler":"setNotificationHandler";if(!zB.has(N))zB.add(N),console.warn(`[ext-apps] ${N}(Schema, handler) is deprecated; use ${N}("${_}", { params: Schema.shape.params }, handler).`);let b=g;return[_,{params:I.params},$==="request"?(U,J)=>b({method:_,params:U},BO(J)):(U)=>b({method:_,params:U})]}function BO($){return{signal:$.mcpReq.signal,requestId:$.mcpReq.id,sessionId:$.sessionId,_meta:$.mcpReq._meta,sendRequest:$.mcpReq.send,sendNotification:$.mcpReq.notify,authInfo:$.http?.authInfo}}var W9="2026-01-26",jO="ui/open-link",zO="ui/download-file",KO="ui/message",OO="ui/notifications/sandbox-proxy-ready",HO="ui/notifications/sandbox-resource-ready",FO="ui/notifications/size-changed",PO="ui/notifications/tool-input",Q9="ui/notifications/tool-input-partial",wO="ui/notifications/tool-result",qO="ui/notifications/tool-cancelled",MO="ui/notifications/host-context-changed",TO="ui/notifications/request-teardown",SO="ui/resource-teardown",AO="ui/initialize",ZO="ui/notifications/initialized",LO="ui/request-display-mode";class QU{eventTarget;eventSource;messageListener;constructor($=window.parent,v){this.eventTarget=$;this.eventSource=v;this.messageListener=(D)=>{if(v&&D.source!==this.eventSource){console.debug("Ignoring message from unknown source",D);return}let g=y6.safeParse(D.data);if(g.success)console.debug("Parsed message",g.data),this.onmessage?.(g.data);else if(D.data?.jsonrpc!=="2.0")console.debug("Ignoring non-JSON-RPC message",g.error.message,D);else console.error("Failed to parse message",g.error.message,D),this.onerror?.(Error("Invalid JSON-RPC message received: "+g.error.message))}}async start(){window.addEventListener("message",this.messageListener)}async send($,v){if($.method!==Q9)console.debug("Sending message",$);this.eventTarget.postMessage($,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}var KB=Q.union([Q.literal("light"),Q.literal("dark")]).describe("Color theme preference for the host environment."),SI=Q.union([Q.literal("inline"),Q.literal("fullscreen"),Q.literal("pip")]).describe("Display mode for UI presentation."),EO=Q.union([Q.literal("--color-background-primary"),Q.literal("--color-background-secondary"),Q.literal("--color-background-tertiary"),Q.literal("--color-background-inverse"),Q.literal("--color-background-ghost"),Q.literal("--color-background-info"),Q.literal("--color-background-danger"),Q.literal("--color-background-success"),Q.literal("--color-background-warning"),Q.literal("--color-background-disabled"),Q.literal("--color-text-primary"),Q.literal("--color-text-secondary"),Q.literal("--color-text-tertiary"),Q.literal("--color-text-inverse"),Q.literal("--color-text-ghost"),Q.literal("--color-text-info"),Q.literal("--color-text-danger"),Q.literal("--color-text-success"),Q.literal("--color-text-warning"),Q.literal("--color-text-disabled"),Q.literal("--color-border-primary"),Q.literal("--color-border-secondary"),Q.literal("--color-border-tertiary"),Q.literal("--color-border-inverse"),Q.literal("--color-border-ghost"),Q.literal("--color-border-info"),Q.literal("--color-border-danger"),Q.literal("--color-border-success"),Q.literal("--color-border-warning"),Q.literal("--color-border-disabled"),Q.literal("--color-ring-primary"),Q.literal("--color-ring-secondary"),Q.literal("--color-ring-inverse"),Q.literal("--color-ring-info"),Q.literal("--color-ring-danger"),Q.literal("--color-ring-success"),Q.literal("--color-ring-warning"),Q.literal("--font-sans"),Q.literal("--font-mono"),Q.literal("--font-weight-normal"),Q.literal("--font-weight-medium"),Q.literal("--font-weight-semibold"),Q.literal("--font-weight-bold"),Q.literal("--font-text-xs-size"),Q.literal("--font-text-sm-size"),Q.literal("--font-text-md-size"),Q.literal("--font-text-lg-size"),Q.literal("--font-heading-xs-size"),Q.literal("--font-heading-sm-size"),Q.literal("--font-heading-md-size"),Q.literal("--font-heading-lg-size"),Q.literal("--font-heading-xl-size"),Q.literal("--font-heading-2xl-size"),Q.literal("--font-heading-3xl-size"),Q.literal("--font-text-xs-line-height"),Q.literal("--font-text-sm-line-height"),Q.literal("--font-text-md-line-height"),Q.literal("--font-text-lg-line-height"),Q.literal("--font-heading-xs-line-height"),Q.literal("--font-heading-sm-line-height"),Q.literal("--font-heading-md-line-height"),Q.literal("--font-heading-lg-line-height"),Q.literal("--font-heading-xl-line-height"),Q.literal("--font-heading-2xl-line-height"),Q.literal("--font-heading-3xl-line-height"),Q.literal("--border-radius-xs"),Q.literal("--border-radius-sm"),Q.literal("--border-radius-md"),Q.literal("--border-radius-lg"),Q.literal("--border-radius-xl"),Q.literal("--border-radius-full"),Q.literal("--border-width-regular"),Q.literal("--shadow-hairline"),Q.literal("--shadow-sm"),Q.literal("--shadow-md"),Q.literal("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),VO=Q.record(EO.describe(`Style variables for theming MCP apps. + +Individual style keys are optional - hosts may provide any subset of these values. +Values are strings containing CSS values (colors, sizes, font stacks, etc.). + +Note: This type uses \`Record\` rather than \`Partial>\` +for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),Q.union([Q.string(),Q.undefined()]).describe(`Style variables for theming MCP apps. + +Individual style keys are optional - hosts may provide any subset of these values. +Values are strings containing CSS values (colors, sizes, font stacks, etc.). + +Note: This type uses \`Record\` rather than \`Partial>\` +for compatibility with Zod schema generation. Both are functionally equivalent for validation.`)).describe(`Style variables for theming MCP apps. + +Individual style keys are optional - hosts may provide any subset of these values. +Values are strings containing CSS values (colors, sizes, font stacks, etc.). + +Note: This type uses \`Record\` rather than \`Partial>\` +for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),kO=Q.object({method:Q.literal("ui/open-link"),params:Q.object({url:Q.string().describe("URL to open in the host's browser")})}),G9=Q.object({isError:Q.boolean().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough(),B9=Q.object({isError:Q.boolean().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough(),j9=Q.object({isError:Q.boolean().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough(),RO=Q.object({method:Q.literal("ui/notifications/sandbox-proxy-ready"),params:Q.object({})}),YU=Q.object({connectDomains:Q.array(Q.string()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket). + +- Maps to CSP \`connect-src\` directive +- Empty or omitted → no network connections (secure default)`),resourceDomains:Q.array(Q.string()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted → no network resources (secure default)"),frameDomains:Q.array(Q.string()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:Q.array(Q.string()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)")}),GU=Q.object({camera:Q.object({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:Q.object({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:Q.object({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:Q.object({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")}),CO=Q.object({method:Q.literal("ui/notifications/size-changed"),params:Q.object({width:Q.number().optional().describe("New width in pixels."),height:Q.number().optional().describe("New height in pixels.")})}),z9=Q.object({method:Q.literal("ui/notifications/tool-input"),params:Q.object({arguments:Q.record(Q.string(),Q.unknown().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})}),K9=Q.object({method:Q.literal("ui/notifications/tool-input-partial"),params:Q.object({arguments:Q.record(Q.string(),Q.unknown().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})}),O9=Q.object({method:Q.literal("ui/notifications/tool-cancelled"),params:Q.object({reason:Q.string().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})}),OB=Q.object({fonts:Q.string().optional()}),HB=Q.object({variables:VO.optional().describe("CSS variables for theming the app."),css:OB.optional().describe("CSS blocks that apps can inject.")}),H9=Q.object({method:Q.literal("ui/resource-teardown"),params:Q.object({})}),F9=Q.record(Q.string(),Q.unknown()),Y9=Q.object({text:Q.object({}).optional().describe("Host supports text content blocks."),image:Q.object({}).optional().describe("Host supports image content blocks."),audio:Q.object({}).optional().describe("Host supports audio content blocks."),resource:Q.object({}).optional().describe("Host supports resource content blocks."),resourceLink:Q.object({}).optional().describe("Host supports resource link content blocks."),structuredContent:Q.object({}).optional().describe("Host supports structured content.")}),xO=Q.object({method:Q.literal("ui/notifications/request-teardown"),params:Q.object({}).optional()}),FB=Q.object({experimental:Q.record(Q.string(),Q.record(Q.string(),Q.any()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),openLinks:Q.object({}).optional().describe("Host supports opening external URLs."),downloadFile:Q.object({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:Q.object({listChanged:Q.boolean().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:Q.object({listChanged:Q.boolean().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:Q.object({}).optional().describe("Host accepts log messages."),sandbox:Q.object({permissions:GU.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:YU.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:Y9.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:Y9.optional().describe("Host supports receiving content messages (ui/message) from the view."),sampling:Q.object({tools:Q.object({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.")}).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.")}),PB=Q.object({experimental:Q.record(Q.string(),Q.record(Q.string(),Q.any()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),tools:Q.object({listChanged:Q.boolean().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:Q.array(SI).optional().describe("Display modes the app supports.")}),fO=Q.object({method:Q.literal("ui/notifications/initialized"),params:Q.object({}).optional()}),yO=Q.object({csp:YU.optional().describe("Content Security Policy configuration for UI resources."),permissions:GU.optional().describe("Sandbox permissions requested by the UI resource."),domain:Q.string().optional().describe(`Dedicated origin for view sandbox. + +Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists. + +**Host-dependent:** The format and validation rules for this field are determined by each host. Servers MUST consult host-specific documentation for the expected domain format. Common patterns include: +- Hash-based subdomains (e.g., \`{hash}.claudemcpcontent.com\`) +- URL-derived subdomains (e.g., \`www-example-com.oaiusercontent.com\`) + +If omitted, host uses default sandbox origin (typically per-conversation).`),prefersBorder:Q.boolean().optional().describe(`Visual boundary preference - true if view prefers a visible border. + +Boolean requesting whether a visible border and background is provided by the host. Specifying an explicit value for this is recommended because hosts' defaults may vary. + +- \`true\`: request visible border + background +- \`false\`: request no visible border + background +- omitted: host decides border`)}),uO=Q.object({method:Q.literal("ui/request-display-mode"),params:Q.object({mode:SI.describe("The display mode being requested.")})}),P9=Q.object({mode:SI.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),wB=Q.union([Q.literal("model"),Q.literal("app")]).describe("Tool visibility scope - who can access the tool."),iO=Q.object({resourceUri:Q.string().optional(),visibility:Q.array(wB).optional().describe(`Who can access this tool. Default: ["model", "app"] +- "model": Tool visible to and callable by the agent +- "app": Tool callable by the app from this server only`),csp:Q.never().optional(),permissions:Q.never().optional()}),EM=Q.object({mimeTypes:Q.array(Q.string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),lO=Q.object({method:Q.literal("ui/download-file"),params:Q.object({contents:Q.array(Q.union([m6,h6])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),nO=Q.object({method:Q.literal("ui/message"),params:Q.object({role:Q.literal("user").describe('Message role, currently only "user" is supported.'),content:Q.array(Yv).describe("Message content blocks (text, image, etc.).")})}),mO=Q.object({method:Q.literal("ui/notifications/sandbox-resource-ready"),params:Q.object({html:Q.string().describe("HTML content to load into the inner iframe."),sandbox:Q.string().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:YU.optional().describe("CSP configuration from resource metadata."),permissions:GU.optional().describe("Sandbox permissions from resource metadata.")})}),w9=Q.object({method:Q.literal("ui/notifications/tool-result"),params:$6.describe("Standard MCP tool execution result.")}),q9=Q.object({toolInfo:Q.object({id:s$.optional().describe("JSON-RPC id of the tools/call request."),tool:sv.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:KB.optional().describe("Current color theme preference."),styles:HB.optional().describe("Style configuration for theming the app."),displayMode:SI.optional().describe("How the UI is currently displayed."),availableDisplayModes:Q.array(SI).optional().describe("Display modes the host supports."),containerDimensions:Q.union([Q.object({height:Q.number().describe("Fixed container height in pixels.")}),Q.object({maxHeight:Q.union([Q.number(),Q.undefined()]).optional().describe("Maximum container height in pixels.")})]).and(Q.union([Q.object({width:Q.number().describe("Fixed container width in pixels.")}),Q.object({maxWidth:Q.union([Q.number(),Q.undefined()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other +container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:Q.string().optional().describe("User's language and region preference in BCP 47 format."),timeZone:Q.string().optional().describe("User's timezone in IANA format."),userAgent:Q.string().optional().describe("Host application identifier."),platform:Q.union([Q.literal("web"),Q.literal("desktop"),Q.literal("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:Q.object({touch:Q.boolean().optional().describe("Whether the device supports touch input."),hover:Q.boolean().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:Q.object({top:Q.number().describe("Top safe area inset in pixels."),right:Q.number().describe("Right safe area inset in pixels."),bottom:Q.number().describe("Bottom safe area inset in pixels."),left:Q.number().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),M9=Q.object({method:Q.literal("ui/notifications/host-context-changed"),params:q9.describe("Partial context update containing only changed fields.")}),hO=Q.object({method:Q.literal("ui/update-model-context"),params:Q.object({content:Q.array(Yv).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:Q.record(Q.string(),Q.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),rO=Q.object({method:Q.literal("ui/initialize"),params:Q.object({appInfo:Wv.describe("App identification (name and version)."),appCapabilities:PB.describe("Features and capabilities this app provides."),protocolVersion:Q.string().describe("Protocol version this app supports.")})}),T9=Q.object({protocolVersion:Q.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Wv.describe("Host application identification and version."),hostCapabilities:FB.describe("Features and capabilities provided by the host."),hostContext:q9.describe("Rich context about the host environment.")}).passthrough();var dO={target:"draft-2020-12"};async function S9($,v){let D=$["~standard"];if(D.jsonSchema)return D.jsonSchema[v](dO);throw Error(`Schema (vendor: ${D.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function A9($,v,D=""){let g=await $["~standard"].validate(v);if(g.issues){let I=g.issues.map((_)=>{let N=_.path?.map((b)=>typeof b==="object"?b.key:b).join(".");return N?`${N}: ${_.message}`:_.message}).join("; ");throw Error(D+I)}return g.value}function pO(){let $=document.documentElement.getAttribute("data-theme");if($==="dark"||$==="light")return $;return document.documentElement.classList.contains("dark")?"dark":"light"}function cO($){let v=document.documentElement;v.setAttribute("data-theme",$),v.style.colorScheme=$}function tO($,v=document.documentElement){for(let[D,g]of Object.entries($))if(g!==void 0)v.style.setProperty(D,g)}function oO($){if(document.getElementById("__mcp-host-fonts"))return;let D=document.createElement("style");D.id="__mcp-host-fonts",D.textContent=$,document.head.appendChild(D)}function aO($,v){let D={...$,...v};if(v.experimental!==void 0)D.experimental={...$.experimental,...v.experimental};if(v.tools!==void 0)D.tools={...$.tools,...v.tools};return D}class qB extends U9{_appInfo;_appCapabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_registeredEvents=new Set;_events=new WU;_methods=new J9;setRequestHandler=(...$)=>{let[v,...D]=X9("request",$)??$;this._methods.claim(v,"setRequestHandler"),super.setRequestHandler.call(this,v,...D)};setNotificationHandler=(...$)=>{let[v,...D]=X9("notification",$)??$;this._methods.claim(v,"setNotificationHandler"),super.setNotificationHandler.call(this,v,...D)};removeRequestHandler=($)=>{this._methods.release($),super.removeRequestHandler($)};removeNotificationHandler=($)=>{this._methods.release($),super.removeNotificationHandler($)};replaceRequestHandler=($,...v)=>{this._methods.replace($),super.setRequestHandler.call(this,$,...v)};_assertInitialized($){if(this._initializedSent)return;let v=`[ext-apps] App.${$}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(v);console.warn(`${v}. This will throw in a future release.`)}eventSchemas={toolinput:z9,toolinputpartial:K9,toolresult:w9,toolcancelled:O9,hostcontextchanged:M9};static ONE_SHOT_EVENTS=new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]);_everHadListener=new Set;_assertHandlerTiming($){if(!qB.ONE_SHOT_EVENTS.has($)||this._everHadListener.has($))return;if(this._everHadListener.add($),!this._initializedSent)return;let v=`[ext-apps] "${String($)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(v);console.warn(v)}setEventHandler($,v){if(v)this._assertHandlerTiming($);this._ensureEventSlot($),this._events.setHandler($,v)}addEventListener($,v){this._assertHandlerTiming($),this._ensureEventSlot($),this._events.addEventListener($,v)}removeEventListener($,v){this._events.removeEventListener($,v)}_ensureEventSlot($){if(this._registeredEvents.has($))return;let v=this.eventSchemas[$];if(!v)throw Error(`Unknown event: ${String($)}`);this.setNotificationHandler(v.shape.method.value,{params:v.shape.params},(D)=>{let g=D;if($==="hostcontextchanged")this._hostContext={...this._hostContext,...g};this._events.dispatch($,g)}),this._registeredEvents.add($)}getEventHandler($){return this._events.getHandler($)}warnIfRequestHandlerReplaced($,v,D){if(v&&D)console.warn(`[MCP Apps] ${$} handler replaced. Previous handler will no longer be called.`)}constructor($,v={},D={autoResize:!0}){super(D);this._appInfo=$;this._appCapabilities=v;this.options=D;if(this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),!D.allowUnsafeEval)Q.config({jitless:!0});this.replaceRequestHandler("ping",(g)=>{return console.log("Received ping:",g.params),{}}),this.setEventHandler("hostcontextchanged",void 0)}buildContext($){return $}registerAppCapabilities($){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._appCapabilities=aO(this._appCapabilities,$)}registerTool($,v,D){if(this._registeredTools[$])throw Error(`Tool ${$} is already registered`);let g=this,I=()=>{if(g._initializedSent&&g._appCapabilities.tools?.listChanged)g.sendToolListChanged()},_=v.inputSchema!==void 0,N={title:v.title,description:v.description,inputSchema:v.inputSchema,outputSchema:v.outputSchema,annotations:v.annotations,_meta:v._meta,enabled:!0,enable(){this.enabled=!0,I()},disable(){this.enabled=!1,I()},update(b){Object.assign(this,b),I()},remove(){if(g._registeredTools[$]!==N)return;delete g._registeredTools[$],I()},handler:async(b,U)=>{if(!N.enabled)throw Error(`Tool ${$} is disabled`);let J;if(_){let W=N.inputSchema,Y=W?await A9(W,b??{},`Invalid input for tool ${$}: `):b??{};J=await D(Y,U)}else J=await D(U);if(N.outputSchema&&!J.isError)J.structuredContent=await A9(N.outputSchema,J.structuredContent,`Invalid output for tool ${$}: `);return J}};if(this._registeredTools[$]=N,!this._appCapabilities.tools&&!this.transport)this.registerAppCapabilities({tools:{listChanged:!0}});return this.ensureToolHandlersInitialized(),I(),N}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){if(this._toolHandlersInitialized)return;this._toolHandlersInitialized=!0,this.oncalltool=async($,v)=>{let D=this._registeredTools[$.name];if(!D)throw Error(`Tool ${$.name} not found`);return D.handler($.arguments,v)},this.onlisttools=async($,v)=>{return{tools:await Promise.all(Object.entries(this._registeredTools).filter(([g,I])=>I.enabled).map(async([g,I])=>{let _={name:g,title:I.title,description:I.description,inputSchema:I.inputSchema?await S9(I.inputSchema,"input"):{type:"object",properties:{}}};if(I.outputSchema)_.outputSchema=await S9(I.outputSchema,"output");if(I.annotations)_.annotations=I.annotations;if(I._meta)_._meta=I._meta;return _}))}}}async sendToolListChanged($={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:$})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput($){this.setEventHandler("toolinput",$)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial($){this.setEventHandler("toolinputpartial",$)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult($){this.setEventHandler("toolresult",$)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled($){this.setEventHandler("toolcancelled",$)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged($){this.setEventHandler("hostcontextchanged",$)}_onteardown;get onteardown(){return this._onteardown}set onteardown($){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,$),this._onteardown=$,this.replaceRequestHandler("ui/resource-teardown",{params:H9.shape.params,result:F9},(v,D)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(v,D)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool($){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,$),this._oncalltool=$,this.replaceRequestHandler("tools/call",(v,D)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(v.params,D)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools($){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,$),this._onlisttools=$,this.replaceRequestHandler("tools/list",(v,D)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(v.params,D)})}assertCapabilityForMethod($){switch($){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${$})`);break}}assertRequestHandlerCapability($){switch($){case"tools/call":case"tools/list":if(!this._appCapabilities.tools)throw Error(`Client does not support tool capability (required for ${$})`);return;default:return}}assertNotificationCapability($){}async callServerTool($,v){if(this._assertInitialized("callServerTool"),typeof $==="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${$}"). Did you mean: callServerTool({ name: "${$}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:$},{onprogress:()=>{},resetTimeoutOnProgress:!0,...v})}async readServerResource($,v){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:$},v)}async listServerResources($,v){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:$},v)}async createSamplingMessage($,v){return this._assertInitialized("createSamplingMessage"),await this.request({method:"sampling/createMessage",params:$},v)}sendMessage($,v){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:$},j9,v)}sendLog($){return this.notification({method:"notifications/message",params:$})}updateModelContext($,v){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:$},ev,v)}openLink($,v){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:$},G9,v)}sendOpenLink=this.openLink;downloadFile($,v){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:$},B9,v)}requestTeardown($={}){return this.notification({method:"ui/notifications/request-teardown",params:$})}requestDisplayMode($,v){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:$},P9,v)}sendSizeChanged($){return this.notification({method:"ui/notifications/size-changed",params:$})}setupSizeChangedNotifications(){let $=!1,v=0,D=0,g=()=>{if($)return;$=!0,requestAnimationFrame(()=>{$=!1;let _=document.documentElement,N=_.style.height;_.style.height="max-content";let b=Math.ceil(_.getBoundingClientRect().height);_.style.height=N;let U=Math.ceil(window.innerWidth);if(U!==v||b!==D)v=U,D=b,this.sendSizeChanged({width:U,height:b})})};g();let I=new ResizeObserver(g);return I.observe(document.documentElement),I.observe(document.body),()=>I.disconnect()}async connect($=new QU(window.parent,window.parent),v){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1;try{await super.connect($);let D=await this.request({method:"ui/initialize",params:{appCapabilities:this._appCapabilities,appInfo:this._appInfo,protocolVersion:W9}},T9,v);if(D===void 0)throw Error(`Server sent invalid initialize result: ${D}`);if(this._hostCapabilities=D.hostCapabilities,this._hostInfo=D.hostInfo,this._hostContext=D.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize)this.setupSizeChangedNotifications()}catch(D){throw this.close(),D}}}export{pO as getDocumentTheme,tO as applyHostStyleVariables,oO as applyHostFonts,cO as applyDocumentTheme,wO as TOOL_RESULT_METHOD,Q9 as TOOL_INPUT_PARTIAL_METHOD,PO as TOOL_INPUT_METHOD,qO as TOOL_CANCELLED_METHOD,FO as SIZE_CHANGED_METHOD,HO as SANDBOX_RESOURCE_READY_METHOD,OO as SANDBOX_PROXY_READY_METHOD,YO as RESOURCE_URI_META_KEY,SO as RESOURCE_TEARDOWN_METHOD,GO as RESOURCE_MIME_TYPE,TO as REQUEST_TEARDOWN_METHOD,LO as REQUEST_DISPLAY_MODE_METHOD,QU as PostMessageTransport,jO as OPEN_LINK_METHOD,hO as McpUiUpdateModelContextRequestSchema,wB as McpUiToolVisibilitySchema,w9 as McpUiToolResultNotificationSchema,iO as McpUiToolMetaSchema,K9 as McpUiToolInputPartialNotificationSchema,z9 as McpUiToolInputNotificationSchema,O9 as McpUiToolCancelledNotificationSchema,KB as McpUiThemeSchema,Y9 as McpUiSupportedContentBlockModalitiesSchema,CO as McpUiSizeChangedNotificationSchema,mO as McpUiSandboxResourceReadyNotificationSchema,RO as McpUiSandboxProxyReadyNotificationSchema,F9 as McpUiResourceTeardownResultSchema,H9 as McpUiResourceTeardownRequestSchema,GU as McpUiResourcePermissionsSchema,yO as McpUiResourceMetaSchema,YU as McpUiResourceCspSchema,xO as McpUiRequestTeardownNotificationSchema,P9 as McpUiRequestDisplayModeResultSchema,uO as McpUiRequestDisplayModeRequestSchema,G9 as McpUiOpenLinkResultSchema,kO as McpUiOpenLinkRequestSchema,j9 as McpUiMessageResultSchema,nO as McpUiMessageRequestSchema,fO as McpUiInitializedNotificationSchema,T9 as McpUiInitializeResultSchema,rO as McpUiInitializeRequestSchema,HB as McpUiHostStylesSchema,OB as McpUiHostCssSchema,q9 as McpUiHostContextSchema,M9 as McpUiHostContextChangedNotificationSchema,FB as McpUiHostCapabilitiesSchema,B9 as McpUiDownloadFileResultSchema,lO as McpUiDownloadFileRequestSchema,SI as McpUiDisplayModeSchema,PB as McpUiAppCapabilitiesSchema,KO as MESSAGE_METHOD,W9 as LATEST_PROTOCOL_VERSION,AO as INITIALIZE_METHOD,ZO as INITIALIZED_METHOD,MO as HOST_CONTEXT_CHANGED_METHOD,WU as EventDispatcher,zO as DOWNLOAD_FILE_METHOD,qB as App}; diff --git a/src/App/AppBridge.php b/src/App/AppBridge.php new file mode 100644 index 0000000..f851642 --- /dev/null +++ b/src/App/AppBridge.php @@ -0,0 +1,50 @@ + $viewVars The view variables. + * @param \Mcp\Schema\Extension\Apps\UiResourceContentMeta|null $meta CSP domains, permissions, border: the + * host applies them to the frame it loads the app in. + * @param string $layout The layout. The default, `CakeDC/Mcp.app`, inlines the official MCP Apps client as + * `McpApps` for the page's own scripts. + * @return \Mcp\Schema\Content\TextResourceContents + */ + public static function render( + string $uri, + string $template, + array $viewVars = [], + ?UiResourceContentMeta $meta = null, + string $layout = 'CakeDC/Mcp.app', + ): TextResourceContents { + $html = (new ViewBuilder()) + ->setTemplate($template) + ->setLayout($layout) + ->setVars($viewVars) + ->build() + ->render(); + + return new TextResourceContents($uri, McpApps::MIME_TYPE, $html, $meta === null ? null : [ + 'ui' => $meta->jsonSerialize(), + ]); + } +} diff --git a/src/McpConfig.php b/src/McpConfig.php index 3fe5c92..77d4ba9 100644 --- a/src/McpConfig.php +++ b/src/McpConfig.php @@ -42,6 +42,7 @@ final class McpConfig 'discovery' => ['scanDirs' => ['src/Mcp'], 'excludeDirs' => [], 'cache' => '_cake_mcp_'], 'schema' => ['normalize' => false], 'catalog' => ['enabled' => false, 'tools' => [], 'maxCalls' => 5], + 'apps' => ['enabled' => false], 'session' => ['cache' => 'mcp_sessions', 'ttl' => 3600], 'http' => ['allowedHosts' => null, 'allowedOrigins' => [], 'maxBodyBytes' => 4 * 1024 * 1024], 'identity' => ['required' => true, 'attribute' => 'identity', 'scopes' => null], diff --git a/src/Server/ServerFactory.php b/src/Server/ServerFactory.php index 0aed873..17d0fec 100644 --- a/src/Server/ServerFactory.php +++ b/src/Server/ServerFactory.php @@ -30,6 +30,7 @@ use Mcp\Event\RequestEvent; use Mcp\Event\ResponseEvent; use Mcp\Schema\Enum\ProtocolVersion; +use Mcp\Schema\Extension\Apps\McpApps; use Mcp\Schema\ToolAnnotations; use Mcp\Server; use Mcp\Server\Builder; @@ -145,6 +146,9 @@ private function build(bool $trusted, LoggerInterface $logger): Server // the build, and the audit asks it whether a tool exists, to tell a denied tool from an unknown one. $registry = new Registry($events, $logger); $builder->setRegistry($registry); + if (McpConfig::get('apps.enabled', $this->server) === true) { + $builder->enableExtension(new McpApps()); + } if ($catalogOn) { $this->addCatalog($builder, new ToolCatalog( $registry, diff --git a/templates/layout/app.php b/templates/layout/app.php new file mode 100644 index 0000000..5926e2a --- /dev/null +++ b/templates/layout/app.php @@ -0,0 +1,22 @@ + + + + + +<?= h($this->fetch('title')) ?> +fetch('css') ?> + + + +fetch('content') ?> +fetch('script') ?> + + diff --git a/tests/TestCase/App/AppBridgeTest.php b/tests/TestCase/App/AppBridgeTest.php new file mode 100644 index 0000000..38a0e16 --- /dev/null +++ b/tests/TestCase/App/AppBridgeTest.php @@ -0,0 +1,29 @@ +assertMatchesRegularExpression('/globalThis\.McpApps=\{[^}]*App:[A-Za-z0-9_$]+[^}]*\};$/', $script); + $this->assertDoesNotMatchRegularExpression('/export\{[^}]*\};?\s*$/', $script); + $this->assertStringNotContainsString('assertStringContainsString($hash, $readme); + } +} diff --git a/tests/TestCase/App/McpAppsTest.php b/tests/TestCase/App/McpAppsTest.php new file mode 100644 index 0000000..6582bfe --- /dev/null +++ b/tests/TestCase/App/McpAppsTest.php @@ -0,0 +1,103 @@ + ArrayEngine::class]); + Configure::write('Mcp.discovery.scanDirs', ['src/McpApps']); + Configure::write('Mcp.apps.enabled', true); + // The layout lives in the plugin, loaded by the application; these tests build the server without it. + $this->loadPlugins(['CakeDC/Mcp']); + } + + protected function tearDown(): void + { + Cache::drop('mcp_sessions'); + parent::tearDown(); + } + + public function testAppsOffAdvertisesNothing(): void + { + Configure::write('Mcp.apps.enabled', false); + + $capabilities = $this->serve([])->responseFor(1)['result']['capabilities'] ?? []; + + $this->assertArrayNotHasKey(self::UI, $capabilities['extensions'] ?? []); + } + + public function testAppsOnAdvertisesTheExtension(): void + { + $capabilities = $this->serve([])->responseFor(1)['result']['capabilities'] ?? []; + + $this->assertSame(['text/html;profile=mcp-app'], $capabilities['extensions'][self::UI]['mimeTypes'] ?? null); + } + + public function testAnAppResourceIsSelfContainedHtml(): void + { + $transport = $this->serve([['jsonrpc' => '2.0', 'id' => 2, 'method' => 'resources/read', 'params' => [ + 'uri' => 'ui://test/inbox', + ]]]); + + $contents = $transport->responseFor(2)['result']['contents'][0] ?? []; + $this->assertSame('text/html;profile=mcp-app', $contents['mimeType'] ?? null); + $html = (string)($contents['text'] ?? ''); + $this->assertStringStartsWith('', $html); + $this->assertStringContainsString('globalThis.McpApps={', $html); + $this->assertStringContainsString('

Inbox: 3 orders to read

', $html); + $this->assertLessThan(strpos($html, 'new McpApps.App('), strpos($html, 'globalThis.McpApps={')); + $this->assertSame(['https://api.example.com'], $contents['_meta']['ui']['csp']['connectDomains'] ?? null); + } + + public function testATemplateErrorIsAReadError(): void + { + $transport = $this->serve([['jsonrpc' => '2.0', 'id' => 2, 'method' => 'resources/read', 'params' => [ + 'uri' => 'ui://test/broken', + ]]]); + + $this->assertArrayHasKey('error', $transport->responseFor(2) ?? []); + } + + /** + * @param list> $requests + * @param array $capabilities The client's capabilities. + */ + private function serve(array $requests, array $capabilities = []): RecordingTransport + { + $container = new Container(); + $identity = new CurrentIdentity(); + $container->addShared(CurrentIdentity::class, $identity); + $transport = new RecordingTransport(array_map(fn(array $message): string => (string)json_encode($message), [ + ['jsonrpc' => '2.0', 'id' => 1, 'method' => 'initialize', 'params' => [ + 'protocolVersion' => '2025-06-18', + 'capabilities' => $capabilities === [] ? new stdClass() : $capabilities, + 'clientInfo' => ['name' => 'test', 'version' => '1.0'], + ]], + ['jsonrpc' => '2.0', 'method' => 'notifications/initialized'], + ...$requests, + ])); + (new ServerFactory($container, $identity))->create(true)->run($transport); + + return $transport; + } +} diff --git a/tests/test_app/src/McpApps/InboxApp.php b/tests/test_app/src/McpApps/InboxApp.php new file mode 100644 index 0000000..c7ec3f5 --- /dev/null +++ b/tests/test_app/src/McpApps/InboxApp.php @@ -0,0 +1,40 @@ + 3], + new UiResourceContentMeta(csp: new UiResourceCsp(connectDomains: ['https://api.example.com'])), + ); + } + + /** + * A page whose template fails. + */ + #[McpResource(uri: 'ui://test/broken', name: 'broken', mimeType: McpApps::MIME_TYPE)] + public function broken(): TextResourceContents + { + return AppView::render('ui://test/broken', 'McpApps/broken'); + } +} diff --git a/tests/test_app/templates/McpApps/broken.php b/tests/test_app/templates/McpApps/broken.php new file mode 100644 index 0000000..91e8ffa --- /dev/null +++ b/tests/test_app/templates/McpApps/broken.php @@ -0,0 +1,7 @@ + +

Inbox: orders to read

+ From 03d814370740d771aa198fbb1c7f07314a616766 Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 21:07:44 +0100 Subject: [PATCH 035/181] MCP Apps: #[McpApp], app-only tools hidden from clients without Apps, audit --- src/App/AppSupport.php | 30 ++++++ src/App/AppTools.php | 58 ++++++++++++ src/Attribute/McpApp.php | 33 +++++++ src/Audit/AuditRecord.php | 4 +- src/Audit/AuditWriter.php | 3 + src/Event/AppToolFilter.php | 35 +++++++ src/Event/AuditListener.php | 3 + src/Server/Conditions.php | 36 +------- src/Server/HandlerAttributes.php | 49 ++++++++++ src/Server/ServerFactory.php | 7 ++ tests/TestCase/App/McpAppsTest.php | 91 ++++++++++++++++++- tests/TestCase/Controller/McpAppsHttpTest.php | 67 ++++++++++++++ tests/test_app/src/McpApps/InboxApp.php | 24 +++++ 13 files changed, 402 insertions(+), 38 deletions(-) create mode 100644 src/App/AppSupport.php create mode 100644 src/App/AppTools.php create mode 100644 src/Attribute/McpApp.php create mode 100644 src/Event/AppToolFilter.php create mode 100644 src/Server/HandlerAttributes.php create mode 100644 tests/TestCase/Controller/McpAppsHttpTest.php diff --git a/src/App/AppSupport.php b/src/App/AppSupport.php new file mode 100644 index 0000000..d7f8cb2 --- /dev/null +++ b/src/App/AppSupport.php @@ -0,0 +1,30 @@ +get(RequestMeta::class); + if ($meta instanceof RequestMeta) { + return isset($meta->clientCapabilities->extensions[McpApps::EXTENSION_ID]); + } + $capabilities = $session->get('client_capabilities', []); + + return is_array($capabilities) && isset($capabilities['extensions'][McpApps::EXTENSION_ID]); + } +} diff --git a/src/App/AppTools.php b/src/App/AppTools.php new file mode 100644 index 0000000..8a56336 --- /dev/null +++ b/src/App/AppTools.php @@ -0,0 +1,58 @@ +getTools()->references as $name => $tool) { + $reference = $registry->getTool((string)$name); + $app = HandlerAttributes::first($reference, McpApp::class); + if ($app === null) { + continue; + } + $meta = $tool->meta ?? []; + $meta['ui'] = ['resourceUri' => $app->resource, 'visibility' => $app->visibility] + + (is_array($meta['ui'] ?? null) ? $meta['ui'] : []); + $registry->unregisterTool($tool->name); + $registry->registerTool(new Tool( + $tool->name, + $tool->title, + $tool->inputSchema, + $tool->description, + $tool->annotations, + $tool->icons, + $meta, + $tool->outputSchema, + $tool->execution, + ), $reference->handler); + } + } + + /** + * Whether a tool is for apps only: its `_meta.ui.visibility` is exactly `["app"]`. + * + * @param \Mcp\Schema\Tool $tool The tool. + * @return bool + */ + public static function appOnly(Tool $tool): bool + { + return ($tool->meta['ui']['visibility'] ?? null) === ['app']; + } +} diff --git a/src/Attribute/McpApp.php b/src/Attribute/McpApp.php new file mode 100644 index 0000000..763b7dc --- /dev/null +++ b/src/Attribute/McpApp.php @@ -0,0 +1,33 @@ + $visibility Who may call the tool: `model`, `app` or both. + * @throws \InvalidArgumentException When the resource is not a `ui://` URI or the visibility is unknown. + */ + public function __construct( + public readonly string $resource, + public readonly array $visibility = ['model', 'app'], + ) { + if (!str_starts_with($resource, 'ui://')) { + throw new InvalidArgumentException(sprintf('#[McpApp] resource "%s" must be a ui:// URI.', $resource)); + } + if ($visibility === [] || array_diff($visibility, ['model', 'app']) !== []) { + throw new InvalidArgumentException('#[McpApp] visibility must list "model", "app" or both.'); + } + } +} diff --git a/src/Audit/AuditRecord.php b/src/Audit/AuditRecord.php index a18ecab..4d586ca 100644 --- a/src/Audit/AuditRecord.php +++ b/src/Audit/AuditRecord.php @@ -39,6 +39,7 @@ final class AuditRecord * @param string|null $error Error message, for the outcomes that are not `ok`. * @param int|null $durationMs Duration, null when it is not known. * @param string|null $via The plugin tool that made the call (`call_tools`), null for a direct call. + * @param bool $app Whether the tool is for MCP Apps only. */ public function __construct( public readonly string $method, @@ -52,6 +53,7 @@ public function __construct( public readonly ?string $error, public readonly ?int $durationMs, public readonly ?string $via = null, + public readonly bool $app = false, ) { } @@ -82,6 +84,6 @@ public function toArray(): array 'arguments' => $this->arguments, 'error' => $this->error, 'durationMs' => $this->durationMs, - ] + ($this->via === null ? [] : ['via' => $this->via]); + ] + ($this->via === null ? [] : ['via' => $this->via]) + ($this->app ? ['app' => true] : []); } } diff --git a/src/Audit/AuditWriter.php b/src/Audit/AuditWriter.php index 66d3531..60649c5 100644 --- a/src/Audit/AuditWriter.php +++ b/src/Audit/AuditWriter.php @@ -129,6 +129,9 @@ private function line(AuditRecord $record): string if ($record->via !== null) { $line .= ' via=' . $this->field($record->via); } + if ($record->app) { + $line .= ' app=1'; + } if ($this->settings->arguments) { $line .= ' args=' . json_encode((object)$record->arguments, self::JSON_FLAGS); } diff --git a/src/Event/AppToolFilter.php b/src/Event/AppToolFilter.php new file mode 100644 index 0000000..b20d1b1 --- /dev/null +++ b/src/Event/AppToolFilter.php @@ -0,0 +1,35 @@ +getResponse(); + $result = $response->result; + if (!$result instanceof ListToolsResult || AppSupport::client($event->getSession())) { + return; + } + $tools = array_values(array_filter($result->tools, fn(Tool $tool): bool => !AppTools::appOnly($tool))); + if (count($tools) !== count($result->tools)) { + $event->setResponse(new Response($response->getId(), new ListToolsResult($tools, $result->nextCursor))); + } + } +} diff --git a/src/Event/AuditListener.php b/src/Event/AuditListener.php index c1b11e0..6f36d55 100644 --- a/src/Event/AuditListener.php +++ b/src/Event/AuditListener.php @@ -58,6 +58,7 @@ final class AuditListener * @param \Closure|null $clock `fn(): float`, seconds; `microtime(true)` by default. * @param \Closure|null $toolExists `fn(string $name): ?bool`, whether the tool exists (null: unknown). Without * it, every tool the gate refuses is recorded as denied. + * @param \Closure|null $appOnly `fn(string $name): bool`, whether a tool is for MCP Apps only (`app=1` in records). */ public function __construct( private readonly AuditSettings $settings, @@ -66,6 +67,7 @@ public function __construct( private readonly CurrentIdentity $identity, ?Closure $clock = null, ?Closure $toolExists = null, + private readonly ?Closure $appOnly = null, ) { $this->clock = $clock ?? fn(): float => microtime(true); $this->toolExists = $toolExists; @@ -230,6 +232,7 @@ private function record(Request $request, SessionInterface $session, string $out $error === null ? null : mb_substr($error, 0, self::MAX_ERROR_LENGTH), $start === null ? null : (int)round((($this->clock)() - $start) * 1000), self::viaOf($request), + $request instanceof CallToolRequest && $this->appOnly !== null && ($this->appOnly)($request->name) === true, )); } diff --git a/src/Server/Conditions.php b/src/Server/Conditions.php index 0259b51..c4653fe 100644 --- a/src/Server/Conditions.php +++ b/src/Server/Conditions.php @@ -7,9 +7,6 @@ use InvalidArgumentException; use Mcp\Capability\Registry; use Mcp\Capability\Registry\ElementReference; -use ReflectionClass; -use ReflectionException; -use ReflectionMethod; /** * Removes from a loaded registry the elements whose `#[McpWhen]` does not hold on a server. @@ -45,7 +42,7 @@ public static function prune(Registry $registry, string $server): array ksort($references, SORT_STRING); foreach ($references as $key => $element) { $key = (string)$key; - $condition = self::condition($get($key)); + $condition = HandlerAttributes::first($get($key), McpWhen::class); if ($condition === null) { continue; } @@ -64,37 +61,6 @@ public static function prune(Registry $registry, string $server): array return $skipped; } - /** - * The `#[McpWhen]` of an element's handler: on the method first, then on its class. Closures have none. - * - * @param \Mcp\Capability\Registry\ElementReference $reference The element. - * @return \CakeDC\Mcp\Attribute\McpWhen|null - */ - private static function condition(ElementReference $reference): ?McpWhen - { - $handler = $reference->handler; - if (is_string($handler) && class_exists($handler)) { - $handler = [$handler, '__invoke']; - } - if (!is_array($handler)) { - return null; - } - $class = is_object($handler[0]) ? $handler[0]::class : $handler[0]; - if (!class_exists($class)) { - return null; - } - try { - $attributes = (new ReflectionMethod($class, $handler[1]))->getAttributes(McpWhen::class); - if ($attributes === []) { - $attributes = (new ReflectionClass($class))->getAttributes(McpWhen::class); - } - } catch (ReflectionException) { - return null; - } - - return $attributes === [] ? null : $attributes[0]->newInstance(); - } - /** * @param mixed $element The definition from the registry page. * @param string $key Its key (a name or a URI). diff --git a/src/Server/HandlerAttributes.php b/src/Server/HandlerAttributes.php new file mode 100644 index 0000000..bfe8ef9 --- /dev/null +++ b/src/Server/HandlerAttributes.php @@ -0,0 +1,49 @@ + $class The attribute class. + * @return T|null + */ + public static function first(ElementReference $reference, string $class): ?object + { + $handler = $reference->handler; + if (is_string($handler) && class_exists($handler)) { + $handler = [$handler, '__invoke']; + } + if (!is_array($handler)) { + return null; + } + $owner = is_object($handler[0]) ? $handler[0]::class : $handler[0]; + if (!class_exists($owner)) { + return null; + } + try { + $attributes = (new ReflectionMethod($owner, $handler[1]))->getAttributes($class); + if ($attributes === []) { + $attributes = (new ReflectionClass($owner))->getAttributes($class); + } + } catch (ReflectionException) { + return null; + } + + return $attributes === [] ? null : $attributes[0]->newInstance(); + } +} diff --git a/src/Server/ServerFactory.php b/src/Server/ServerFactory.php index 17d0fec..ad6ae32 100644 --- a/src/Server/ServerFactory.php +++ b/src/Server/ServerFactory.php @@ -4,6 +4,7 @@ namespace CakeDC\Mcp\Server; use Cake\Cache\Cache; +use CakeDC\Mcp\App\AppTools; use CakeDC\Mcp\Audit\AuditSettings; use CakeDC\Mcp\Audit\AuditWriter; use CakeDC\Mcp\Authorization\RbacToolAuthorizer; @@ -13,6 +14,7 @@ use CakeDC\Mcp\Catalog\CatalogPatterns; use CakeDC\Mcp\Catalog\ToolCatalog; use CakeDC\Mcp\Container\ContainerBridge; +use CakeDC\Mcp\Event\AppToolFilter; use CakeDC\Mcp\Event\AuditListener; use CakeDC\Mcp\Event\EventDispatcher; use CakeDC\Mcp\Event\ToolListFilter; @@ -140,6 +142,8 @@ private function build(bool $trusted, LoggerInterface $logger): Server // After the filter, on the tools the caller may see. $events->listen(ResponseEvent::class, new ToolSchemaNormalizer()); } + // Clients that do not render apps never get app-only tools listed. + $events->listen(ResponseEvent::class, new AppToolFilter()); // The guard goes first: the SDK asks request handlers in the order they were added. $builder = Server::builder()->addRequestHandler(new ToolCallGuard($gate)); // Our own registry, set before the host hook (which may still replace it): #[McpWhen] prunes it after @@ -170,6 +174,8 @@ private function build(bool $trusted, LoggerInterface $logger): Server $gate, $this->identity, toolExists: fn(string $name): ?bool => $registry->hasTools() ? $registry->hasTool($name) : null, + appOnly: fn(string $name): bool => $registry->hasTool($name) + && AppTools::appOnly($registry->getTool($name)->tool), ); $events->listen(RequestEvent::class, $listener->onRequest(...)); $events->listen(ResponseEvent::class, $listener->onResponse(...)); @@ -217,6 +223,7 @@ private function build(bool $trusted, LoggerInterface $logger): Server $server = $builder->build(); $this->skipped = Conditions::prune($registry, $this->server); + AppTools::link($registry); $this->lastRegistry = $registry; return $server; diff --git a/tests/TestCase/App/McpAppsTest.php b/tests/TestCase/App/McpAppsTest.php index 6582bfe..0cfe924 100644 --- a/tests/TestCase/App/McpAppsTest.php +++ b/tests/TestCase/App/McpAppsTest.php @@ -7,7 +7,10 @@ use Cake\Cache\Engine\ArrayEngine; use Cake\Core\Configure; use Cake\Core\Container; +use Cake\Log\Engine\ArrayLog; +use Cake\Log\Log; use Cake\TestSuite\TestCase; +use CakeDC\Mcp\Authorization\ToolAuthorizerInterface; use CakeDC\Mcp\Identity\CurrentIdentity; use CakeDC\Mcp\Server\ServerFactory; use CakeDC\Mcp\TestSuite\RecordingTransport; @@ -20,6 +23,11 @@ class McpAppsTest extends TestCase { private const UI = 'io.modelcontextprotocol/ui'; + /** + * The capabilities of a client that renders apps. + */ + private const APPS_CLIENT = ['extensions' => [self::UI => ['mimeTypes' => ['text/html;profile=mcp-app']]]]; + protected function setUp(): void { parent::setUp(); @@ -78,11 +86,90 @@ public function testATemplateErrorIsAReadError(): void $this->assertArrayHasKey('error', $transport->responseFor(2) ?? []); } + public function testMcpAppLinksTheToolToItsApp(): void + { + $tools = $this->toolsFor(self::APPS_CLIENT); + + $this->assertSame( + ['resourceUri' => 'ui://test/inbox', 'visibility' => ['model', 'app']], + $tools['show_inbox']['_meta']['ui'] ?? null, + ); + $this->assertSame(['app'], $tools['inbox_rows']['_meta']['ui']['visibility'] ?? null); + } + + public function testAppOnlyToolsAreHiddenFromClientsWithoutApps(): void + { + $tools = $this->toolsFor([]); + + $this->assertArrayHasKey('show_inbox', $tools); + $this->assertArrayNotHasKey('inbox_rows', $tools); + } + + public function testAppOnlyToolsAreListedForClientsWithApps(): void + { + $this->assertArrayHasKey('inbox_rows', $this->toolsFor(self::APPS_CLIENT)); + } + + public function testAppOnlyToolsAreStillGatedWhenCalledDirectly(): void + { + Configure::write('Mcp.authorization.authorizer', new class implements ToolAuthorizerInterface { + public function canCall(mixed $identity, string $tool): bool + { + return $tool !== 'inbox_rows'; + } + }); + + $transport = $this->serve([['jsonrpc' => '2.0', 'id' => 2, 'method' => 'tools/call', 'params' => [ + 'name' => 'inbox_rows', + 'arguments' => new stdClass(), + ]]], self::APPS_CLIENT, trusted: false); + + $this->assertSame('Tool not found: "inbox_rows".', $transport->responseFor(2)['error']['message'] ?? null); + } + + public function testAppToolCallsAreAuditedAsApp(): void + { + Log::setConfig('audit_apps', ['className' => ArrayLog::class, 'scopes' => ['mcp_audit']]); + Configure::write('Mcp.audit.enabled', true); + try { + $this->serve([ + ['jsonrpc' => '2.0', 'id' => 2, 'method' => 'tools/call', 'params' => [ + 'name' => 'inbox_rows', + 'arguments' => new stdClass(), + ]], + ['jsonrpc' => '2.0', 'id' => 3, 'method' => 'tools/call', 'params' => [ + 'name' => 'show_inbox', + 'arguments' => new stdClass(), + ]], + ], self::APPS_CLIENT); + + $engine = Log::engine('audit_apps'); + $lines = array_map('strval', $engine instanceof ArrayLog ? $engine->read() : []); + $this->assertCount(2, $lines); + $this->assertStringContainsString('MCP tools/call inbox_rows ok', $lines[0]); + $this->assertStringContainsString(' app=1', $lines[0]); + $this->assertStringNotContainsString('app=', $lines[1]); + } finally { + Log::drop('audit_apps'); + } + } + + /** + * @param array $capabilities The client's capabilities. + * @return array> The listed tools by name. + */ + private function toolsFor(array $capabilities): array + { + $transport = $this->serve([['jsonrpc' => '2.0', 'id' => 2, 'method' => 'tools/list']], $capabilities); + + return array_column($transport->responseFor(2)['result']['tools'] ?? [], null, 'name'); + } + /** * @param list> $requests * @param array $capabilities The client's capabilities. */ - private function serve(array $requests, array $capabilities = []): RecordingTransport + private function serve(array $requests, array $capabilities = [], bool $trusted = true): RecordingTransport { $container = new Container(); $identity = new CurrentIdentity(); @@ -96,7 +183,7 @@ private function serve(array $requests, array $capabilities = []): RecordingTran ['jsonrpc' => '2.0', 'method' => 'notifications/initialized'], ...$requests, ])); - (new ServerFactory($container, $identity))->create(true)->run($transport); + (new ServerFactory($container, $identity))->create($trusted)->run($transport); return $transport; } diff --git a/tests/TestCase/Controller/McpAppsHttpTest.php b/tests/TestCase/Controller/McpAppsHttpTest.php new file mode 100644 index 0000000..a2350f1 --- /dev/null +++ b/tests/TestCase/Controller/McpAppsHttpTest.php @@ -0,0 +1,67 @@ +listTools(['extensions' => ['io.modelcontextprotocol/ui' => ['mimeTypes' => ['text/html;profile=mcp-app']]]]); + + $this->assertContains('inbox_rows', $names); + $this->assertContains('show_inbox', $names); + } + + public function testAClientWithoutAppsDoesNot(): void + { + $names = $this->listTools([]); + + $this->assertNotContains('inbox_rows', $names); + $this->assertContains('show_inbox', $names); + } + + /** + * @param array $capabilities + * @return list + */ + private function listTools(array $capabilities): array + { + $this->configRequest(['headers' => [ + 'Host' => 'localhost', + 'Accept' => 'application/json, text/event-stream', + 'Content-Type' => 'application/json', + 'Authorization' => 'Bearer ' . TestTokens::EDITOR, + 'MCP-Protocol-Version' => '2026-07-28', + 'Mcp-Method' => 'tools/list', + ]]); + $this->post('/mcp', (string)json_encode(['jsonrpc' => '2.0', 'id' => 1, 'method' => 'tools/list', 'params' => [ + '_meta' => [ + 'io.modelcontextprotocol/protocolVersion' => '2026-07-28', + 'io.modelcontextprotocol/clientCapabilities' => $capabilities === [] ? new stdClass() : $capabilities, + ], + ]])); + $this->assertResponseOk(); + $body = json_decode((string)$this->_response->getBody(), true); + + return array_column($body['result']['tools'] ?? [], 'name'); + } +} diff --git a/tests/test_app/src/McpApps/InboxApp.php b/tests/test_app/src/McpApps/InboxApp.php index c7ec3f5..a6a9c8c 100644 --- a/tests/test_app/src/McpApps/InboxApp.php +++ b/tests/test_app/src/McpApps/InboxApp.php @@ -4,7 +4,9 @@ namespace TestApp\McpApps; use CakeDC\Mcp\App\AppView; +use CakeDC\Mcp\Attribute\McpApp; use Mcp\Capability\Attribute\McpResource; +use Mcp\Capability\Attribute\McpTool; use Mcp\Schema\Content\TextResourceContents; use Mcp\Schema\Extension\Apps\McpApps; use Mcp\Schema\Extension\Apps\UiResourceContentMeta; @@ -29,6 +31,28 @@ public function inbox(): TextResourceContents ); } + /** + * Shows the inbox: the model calls it, the host opens the app. + */ + #[McpApp(resource: 'ui://test/inbox')] + #[McpTool(name: 'show_inbox')] + public function show(): string + { + return '3 orders to read.'; + } + + /** + * The rows of the inbox, for the app only. + * + * @return array + */ + #[McpApp(resource: 'ui://test/inbox', visibility: ['app'])] + #[McpTool(name: 'inbox_rows')] + public function rows(): array + { + return ['rows' => [['patient' => 'J. Doe', 'study' => 'CT chest']]]; + } + /** * A page whose template fails. */ From 143bfb2e2cca0462b239f6dcf384e981bdab3f8b Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 21:09:54 +0100 Subject: [PATCH 036/181] MCP Apps: mcp check, bake mcp_app, docs --- CHANGELOG.md | 1 + README.md | 1 + docs/apps.md | 110 ++++++++++++++++++ docs/configuration.md | 1 + docs/tools.md | 4 +- src/Command/Bake/McpAppCommand.php | 63 ++++++++++ src/Command/McpCheckCommand.php | 53 +++++++++ src/Server/ServerFactory.php | 20 ++++ templates/bake/Mcp/app.twig | 41 +++++++ templates/bake/Mcp/app_template.twig | 24 ++++ templates/bake/tests/app.twig | 30 +++++ .../Command/Bake/McpBakeCommandsTest.php | 39 ++++++- .../TestCase/Command/McpCheckCommandTest.php | 38 ++++++ 13 files changed, 423 insertions(+), 2 deletions(-) create mode 100644 docs/apps.md create mode 100644 src/Command/Bake/McpAppCommand.php create mode 100644 templates/bake/Mcp/app.twig create mode 100644 templates/bake/Mcp/app_template.twig create mode 100644 templates/bake/tests/app.twig diff --git a/CHANGELOG.md b/CHANGELOG.md index 8fc58d4..88f4ce0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- MCP Apps (`Mcp.apps.enabled`): `AppView::render()` turns a Cake template into an app page, in a layout that inlines the official MCP Apps client (`@modelcontextprotocol/ext-apps` 2.0.4, vendored in `resources/ext-apps` with its license); `#[McpApp]` links a tool to its app; app-only tools are left out of `tools/list` for clients that do not render apps, and their audit records carry `app=1`; `mcp check` reports apps on a new `Apps` line; `bake mcp_app` creates an app. See `docs/apps.md`. - Tool catalog (`Mcp.catalog`): chosen tools leave `tools/list` and are reached with `find_tools` and `call_tools`; every inner call goes through the authorizer, the tool scopes (a `403 insufficient_scope` over HTTP), the input schema and the audit (`via=call_tools`). `mcp check` reports it on a new `Catalog` line, and its `Tool schemas` line covers catalogued tools. - `McpTestTrait` runs tools that report progress or log through the SDK's `ClientGateway` (they used to get no response in tests) and records their notifications: `mcpNotifications()`, `assertMcpProgressSent()`, `assertMcpNotificationSent()`. A tool that asks the client something fails with a clear message. - Docs: progress and logs from a tool, and what buffers server-sent events (PHP output buffering, compression, proxies). diff --git a/README.md b/README.md index 1204cde..f831b15 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,7 @@ $service->loadAuthenticator('Authentication.Token', [ - [Installation](docs/installation.md) - [Configuration](docs/configuration.md) - [Writing tools](docs/tools.md) +- [MCP Apps](docs/apps.md) - [Authentication](docs/authentication.md) - [OAuth](docs/oauth.md) - [Authorization](docs/authorization.md) diff --git a/docs/apps.md b/docs/apps.md new file mode 100644 index 0000000..38cc666 --- /dev/null +++ b/docs/apps.md @@ -0,0 +1,110 @@ +# MCP Apps + +An MCP App is a small web page a host (Claude, ChatGPT, an IDE) shows in a +frame next to the conversation. The model calls a tool; the host opens the +tool's app and passes it the result; the page can call tools of your server +itself. It is the MCP Apps extension of the protocol +(`io.modelcontextprotocol/ui`). The plugin renders the page from a Cake +template and ships the official MCP Apps client, so the page needs no build +step. + +## Turning it on + +```php +'Mcp' => ['apps' => ['enabled' => true]], +``` + +The server then tells clients it serves apps. Clients that do not render apps +ignore it and keep using your tools as before. + +## An app + +An app is a `ui://` resource with the MIME type `text/html;profile=mcp-app`, +plus a tool linked to it with `#[McpApp]`. `bin/cake bake mcp_app Inbox` +creates both, the page template and a test: + +```php +namespace App\Mcp; + +use CakeDC\Mcp\App\AppView; +use CakeDC\Mcp\Attribute\McpApp; +use Mcp\Capability\Attribute\McpResource; +use Mcp\Capability\Attribute\McpTool; +use Mcp\Schema\Content\TextResourceContents; +use Mcp\Schema\Extension\Apps\McpApps; +use Mcp\Schema\Extension\Apps\UiResourceContentMeta; +use Mcp\Schema\Extension\Apps\UiResourceCsp; + +class InboxApp +{ + #[McpResource(uri: 'ui://app/inbox', name: 'inbox', mimeType: McpApps::MIME_TYPE)] + public function page(): TextResourceContents + { + return AppView::render('ui://app/inbox', 'Mcp/inbox', [], new UiResourceContentMeta( + csp: new UiResourceCsp(connectDomains: ['https://api.example.com']), + )); + } + + /** + * The orders waiting to be read. + */ + #[McpApp(resource: 'ui://app/inbox')] + #[McpTool(name: 'show_inbox')] + public function show(): array + { + return ['count' => 3]; + } + + /** + * The rows of the inbox, for the app only. + */ + #[McpApp(resource: 'ui://app/inbox', visibility: ['app'])] + #[McpTool(name: 'inbox_rows')] + public function rows(): array + { + // ... + } +} +``` + +`AppView::render()` renders `templates/Mcp/inbox.php` in the plugin's +`CakeDC/Mcp.app` layout and returns the page with the right MIME type. The +layout is a complete HTML document whose first script defines `McpApps`, the +official client (`@modelcontextprotocol/ext-apps`, inlined, so the page needs +no network access to load it). The template uses it: + +```php +
    + +``` + +The third argument of `render()` holds the view variables. The fourth, +`UiResourceContentMeta`, tells the host what the frame may do: the domains it +may connect to or load from (`UiResourceCsp`), permissions such as the +clipboard (`UiResourcePermissions`), and whether it wants a border. Hosts apply +a strict policy by default, so declare every outside domain the page uses. + +## Visibility + +`#[McpApp]` writes `_meta.ui` into the tool's entry of `tools/list`: +`resourceUri`, and `visibility`, by default `['model', 'app']`. A tool with +`visibility: ['app']` is for the app only: hosts keep it from the model, and +clients that do not render apps do not get it in `tools/list` at all. + +Visibility is a hint for the host, not access control. An app-only tool can +still be called by anyone who knows its name and holds a valid token, so it is +gated by your authorizer, needs its scopes and is audited like any other tool +(its audit records carry `app=1`). Data an app shows also passes through the +host, so the host vendor's terms apply to it as much as to what the model reads. + +## Checking and testing + +`bin/cake mcp check` reports apps on its `Apps` line, and fails when a tool +links to a resource that is not a registered app page, or when tools link to +apps while `Mcp.apps.enabled` is off. In tests, call the resource method +directly to check the page, and the tools with `McpTestTrait` as usual. diff --git a/docs/configuration.md b/docs/configuration.md index a629b52..2bf7433 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -53,6 +53,7 @@ want to change; everything else keeps its default. These are the defaults - `catalog.enabled`: `true` turns on the tool catalog for this server (see [Tool catalog](tools.md#tool-catalog)). Default `false`. - `catalog.tools`: the tools behind the catalog, as names or `fnmatch()` patterns (`report_*`). They leave `tools/list` and are reached with `find_tools` and `call_tools`. - `catalog.maxCalls`: how many tools one `call_tools` may run, a positive integer. Default `5`. +- `apps.enabled`: `true` tells clients this server serves MCP Apps (the `io.modelcontextprotocol/ui` extension). Default `false`. See [MCP Apps](apps.md). - `server.configure`: optional callable that receives the SDK `Mcp\Server\Builder` before the server is built. See [Using the SDK builder](#using-the-sdk-builder). - `discovery.scanDirs`: directories (relative to `ROOT`) scanned for attributes. Missing directories are skipped. - `discovery.excludeDirs`: directories to skip while scanning. diff --git a/docs/tools.md b/docs/tools.md index 81398e9..bf360c6 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -272,10 +272,12 @@ With `cakephp/bake` installed, three bake commands create a class in bin/cake bake mcp_tool ListOrders # src/Mcp/ListOrdersTool.php, tool list_orders bin/cake bake mcp_resource OrderGuide # src/Mcp/OrderGuideResource.php, app://order-guide bin/cake bake mcp_prompt WeeklyReport # src/Mcp/WeeklyReportPrompt.php, prompt weekly_report +bin/cake bake mcp_app Inbox # src/Mcp/InboxApp.php and templates/Mcp/inbox.php, see MCP Apps ``` Each class is invokable, with the attribute on the class and the work in -`__invoke()`, one class per tool. The generated tool is read-only, has every +`__invoke()`, one class per tool. `mcp_app` creates an [MCP App](apps.md): a +class with the page resource and its tool, and the page template. The generated tool is read-only, has every parameter described and passes the `Tool schemas` line of `bin/cake mcp check`. Replace the placeholder description: the model reads it to decide when to call the tool. `--plugin Shop` bakes into a plugin, `--no-test` skips the test, and diff --git a/src/Command/Bake/McpAppCommand.php b/src/Command/Bake/McpAppCommand.php new file mode 100644 index 0000000..71f06d6 --- /dev/null +++ b/src/Command/Bake/McpAppCommand.php @@ -0,0 +1,63 @@ +`: an MCP App (a `ui://` resource rendered from a Cake template, and a tool linked + * to it) in `src/Mcp/`, its page in `templates/Mcp/`, and its test. + */ +class McpAppCommand extends McpBakeCommand +{ + /** + * @inheritDoc + */ + public static function getDescription(): string + { + return 'Bake an MCP App: its resource and tool, its page template and its test.'; + } + + /** + * @inheritDoc + */ + protected function kind(): string + { + return 'app'; + } + + /** + * @inheritDoc + */ + public function templateData(Arguments $arguments): array + { + $data = parent::templateData($arguments); + $data['pageTemplate'] = ($this->plugin ? $this->plugin . '.' : '') . 'Mcp/' . $data['mcpName']; + + return $data; + } + + /** + * Bakes the class, then the page template. + * + * @param string $name The name, as given. + * @param \Cake\Console\Arguments $args The arguments. + * @param \Cake\Console\ConsoleIo $io The console. + * @return void + */ + protected function bake(string $name, Arguments $args, ConsoleIo $io): void + { + parent::bake($name, $args, $io); + $data = $this->templateData($args); + $contents = $this->createTemplateRenderer()->set($data)->generate('CakeDC/Mcp.Mcp/app_template'); + $base = $this->plugin ? $this->_pluginPath($this->plugin) : ROOT . DS; + $io->createFile( + $base . 'templates' . DS . 'Mcp' . DS . $data['mcpName'] . '.php', + $contents, + $this->force, + ); + } +} diff --git a/src/Command/McpCheckCommand.php b/src/Command/McpCheckCommand.php index c954ac4..52e45b5 100644 --- a/src/Command/McpCheckCommand.php +++ b/src/Command/McpCheckCommand.php @@ -42,6 +42,7 @@ use CakeDC\OAuthServer\OAuthServer; use InvalidArgumentException; use Mcp\Schema\Enum\CacheScope; +use Mcp\Schema\Extension\Apps\McpApps; use ReflectionClass; use ReflectionProperty; use Symfony\Component\Finder\Finder; @@ -247,6 +248,7 @@ protected function checks(): array 'Tool schemas' => fn(): array => $this->toolSchemas(), 'Conditions' => fn(): array => $this->conditions(), 'Catalog' => fn(): array => $this->catalog(), + 'Apps' => fn(): array => $this->apps(), 'Authorizer' => fn(): array => $this->authorizerCheck(), 'Tool scopes' => fn(): array => $this->toolScopes(), 'Cache hints' => fn(): array => $this->cacheHints(), @@ -282,6 +284,57 @@ private function toolNames(): array return array_map(fn(array $tool): string => (string)$tool['name'], $this->toolDefinitions()); } + /** + * @return array{0: 'pass'|'warn'|'fail', 1: string} + */ + private function apps(): array + { + $links = []; + foreach ($this->factory()->registeredToolDefinitions() as $tool) { + $uri = $tool['_meta']['ui']['resourceUri'] ?? null; + if (is_string($uri)) { + $links[(string)$tool['name']] = $uri; + } + } + ksort($links); + $enabled = McpConfig::get('apps.enabled', $this->server) === true; + if (!$enabled) { + return $links === [] + ? ['pass', 'off'] + : ['fail', sprintf( + '%s link to apps but Mcp.apps.enabled is off, so clients are not told about apps, see %s', + implode(', ', array_keys($links)), + self::DOCS . 'apps.md', + )]; + } + $apps = []; + foreach ($this->factory()->registeredResourceDefinitions() as $resource) { + if (($resource['mimeType'] ?? null) === McpApps::MIME_TYPE) { + $apps[] = (string)$resource['uri']; + } + } + sort($apps); + $missing = []; + foreach ($links as $tool => $uri) { + if (!in_array($uri, $apps, true)) { + $missing[] = sprintf('%s links to %s, which is not an app resource', $tool, $uri); + } + } + if ($missing !== []) { + return ['fail', implode('; ', $missing) . sprintf( + ' (a ui:// resource with MIME type %s), see %s', + McpApps::MIME_TYPE, + self::DOCS . 'apps.md', + )]; + } + + return ['pass', $apps === [] ? 'on, no app resources' : sprintf( + '%d app resources: %s', + count($apps), + implode(', ', $apps), + )]; + } + /** * @return array{0: 'pass'|'warn'|'fail', 1: string} */ diff --git a/src/Server/ServerFactory.php b/src/Server/ServerFactory.php index ad6ae32..f60844d 100644 --- a/src/Server/ServerFactory.php +++ b/src/Server/ServerFactory.php @@ -420,6 +420,26 @@ public function registeredToolDefinitions(): array return $tools; } + /** + * Every resource registered on this server (not templates), decoded from JSON. + * + * @internal Used by `bin/cake mcp check`; not part of the public API. + * @return list> Each has a string `uri`. + */ + public function registeredResourceDefinitions(): array + { + $this->build(true, $this->quietLogger()); + $resources = []; + foreach ($this->lastRegistry?->getResources()->references ?? [] as $resource) { + $definition = json_decode((string)json_encode($resource), true); + if (is_array($definition) && is_string($definition['uri'] ?? null)) { + $resources[] = $definition; + } + } + + return $resources; + } + /** * What `#[McpWhen]` leaves out of this server, as a trusted client would see it. * diff --git a/templates/bake/Mcp/app.twig b/templates/bake/Mcp/app.twig new file mode 100644 index 0000000..1c22dd3 --- /dev/null +++ b/templates/bake/Mcp/app.twig @@ -0,0 +1,41 @@ +{{ element('Bake.file_header', { + namespace: "#{namespace}\\Mcp", + classImports: [ + 'CakeDC\\Mcp\\App\\AppView', + 'CakeDC\\Mcp\\Attribute\\McpApp', + 'Mcp\\Capability\\Attribute\\McpResource', + 'Mcp\\Capability\\Attribute\\McpTool', + 'Mcp\\Schema\\Content\\TextResourceContents', + 'Mcp\\Schema\\Extension\\Apps\\McpApps', + 'Mcp\\Schema\\ToolAnnotations', + ], +}) }} + +/** + * An MCP App: a page the host shows in a frame, and the tool that opens it. + */ +class {{ className }} +{ + /** + * The page, rendered from templates/Mcp/{{ mcpName }}.php. + * + * @return \Mcp\Schema\Content\TextResourceContents + */ + #[McpResource(uri: 'ui://app/{{ uriName }}', name: '{{ mcpName }}', mimeType: McpApps::MIME_TYPE)] + public function page(): TextResourceContents + { + return AppView::render('ui://app/{{ uriName }}', '{{ pageTemplate }}'); + } + + /** + * Describe what the app shows: the model calls this tool, and the host opens the app with its result. + * + * @return array + */ + #[McpApp(resource: 'ui://app/{{ uriName }}')] + #[McpTool(name: 'show_{{ mcpName }}', annotations: new ToolAnnotations(readOnlyHint: true, openWorldHint: false))] + public function show(): array + { + return ['items' => []]; + } +} diff --git a/templates/bake/Mcp/app_template.twig b/templates/bake/Mcp/app_template.twig new file mode 100644 index 0000000..3780a92 --- /dev/null +++ b/templates/bake/Mcp/app_template.twig @@ -0,0 +1,24 @@ + +
    +

    {{ className }}

    +
      +
      + diff --git a/templates/bake/tests/app.twig b/templates/bake/tests/app.twig new file mode 100644 index 0000000..afa3400 --- /dev/null +++ b/templates/bake/tests/app.twig @@ -0,0 +1,30 @@ +{{ element('Bake.file_header', { + namespace: testNamespace, + classImports: [ + 'Cake\\TestSuite\\TestCase', + 'CakeDC\\Mcp\\TestSuite\\McpTestTrait', + "#{namespace}\\Mcp\\#{className}", + ], +}) }} + +class {{ className }}Test extends TestCase +{ + use McpTestTrait; + + public function testThePageRenders(): void + { + $page = (new {{ className }}())->page(); + + $this->assertSame('text/html;profile=mcp-app', $page->mimeType); + $this->assertStringContainsString('McpApps', $page->text); + } + + public function testTheToolAnswers(): void + { + $this->mcpActingAs(['id' => 1]); + + $this->mcpCallTool('show_{{ mcpName }}'); + + $this->assertMcpToolSucceeded(); + } +} diff --git a/tests/TestCase/Command/Bake/McpBakeCommandsTest.php b/tests/TestCase/Command/Bake/McpBakeCommandsTest.php index 8d8948e..19fe303 100644 --- a/tests/TestCase/Command/Bake/McpBakeCommandsTest.php +++ b/tests/TestCase/Command/Bake/McpBakeCommandsTest.php @@ -29,6 +29,9 @@ class McpBakeCommandsTest extends TestCase 'tests/TestCase/Mcp/ListOrdersToolTest.php', 'tests/TestCase/Mcp/OrderGuideResourceTest.php', 'tests/TestCase/Mcp/WeeklyReportPromptTest.php', + 'src/Mcp/InboxApp.php', + 'templates/Mcp/inbox.php', + 'tests/TestCase/Mcp/InboxAppTest.php', ]; protected function setUp(): void @@ -46,7 +49,7 @@ protected function tearDown(): void unlink(self::PLUGIN . $file); } } - foreach (['src/Mcp', 'tests/TestCase/Mcp', 'tests/TestCase'] as $dir) { + foreach (['src/Mcp', 'tests/TestCase/Mcp', 'tests/TestCase', 'templates/Mcp', 'templates'] as $dir) { if (is_dir(self::PLUGIN . $dir)) { rmdir(self::PLUGIN . $dir); } @@ -102,6 +105,40 @@ public function testBakesAResourceAndAPrompt(): void $this->assertFileExists(self::PLUGIN . 'tests/TestCase/Mcp/WeeklyReportPromptTest.php'); } + public function testBakesAnApp(): void + { + $this->exec('bake mcp_app Inbox --plugin BakeTarget --force'); + + $this->assertExitSuccess(); + $class = $this->baked('src/Mcp/InboxApp.php'); + $this->assertStringContainsString("uri: 'ui://app/inbox'", $class); + $this->assertStringContainsString("#[McpApp(resource: 'ui://app/inbox')]", $class); + $this->assertStringContainsString("name: 'show_inbox'", $class); + $this->assertStringContainsString("'BakeTarget.Mcp/inbox'", $class); + $this->assertStringContainsString('new McpApps.App(', $this->baked('templates/Mcp/inbox.php')); + $this->assertFileExists(self::PLUGIN . 'tests/TestCase/Mcp/InboxAppTest.php'); + + require_once self::PLUGIN . 'src/Mcp/InboxApp.php'; + $transport = new RecordingTransport(array_map('json_encode', [ + ['jsonrpc' => '2.0', 'id' => 1, 'method' => 'initialize', 'params' => [ + 'protocolVersion' => '2025-06-18', + 'capabilities' => new stdClass(), + 'clientInfo' => ['name' => 'test', 'version' => '1'], + ]], + ['jsonrpc' => '2.0', 'method' => 'notifications/initialized'], + ['jsonrpc' => '2.0', 'id' => 2, 'method' => 'resources/read', 'params' => ['uri' => 'ui://app/inbox']], + ])); + Server::builder() + ->setServerInfo('bake', '1') + ->setDiscovery(rtrim(self::PLUGIN, DS), ['src/Mcp']) + ->build() + ->run($transport); + + $contents = $transport->responseFor(2)['result']['contents'][0] ?? []; + $this->assertSame('text/html;profile=mcp-app', $contents['mimeType'] ?? null, (string)json_encode($transport->responseFor(2))); + $this->assertStringContainsString('globalThis.McpApps={', (string)($contents['text'] ?? '')); + } + public function testNoTestOption(): void { $this->exec('bake mcp_tool ListOrders --plugin BakeTarget --force --no-test'); diff --git a/tests/TestCase/Command/McpCheckCommandTest.php b/tests/TestCase/Command/McpCheckCommandTest.php index bdf029e..6255888 100644 --- a/tests/TestCase/Command/McpCheckCommandTest.php +++ b/tests/TestCase/Command/McpCheckCommandTest.php @@ -20,6 +20,7 @@ use CakeDC\Mcp\Command\McpCheckCommand; use CakeDC\Mcp\Test\Support\OAuthFixtures; use CakeDC\OAuthServer\OAuthServer; +use Mcp\Server\Builder; use PHPUnit\Framework\Attributes\DataProvider; use Psr\Log\NullLogger; use TestApp\Authenticator\ApiTokenAuthenticator; @@ -649,6 +650,43 @@ public function testToolSchemasCoverCataloguedTools(): void $this->assertOutputContains('[WARN] Tool schemas: report.date_from: type union null|string'); } + public function testAppsLine(): void + { + $this->exec('mcp check'); + $this->assertOutputContains('[PASS] Apps: off'); + + Configure::write('Mcp.discovery.scanDirs', ['src/McpApps']); + $this->exec('mcp check'); + $this->assertOutputContains('[FAIL] Apps: inbox_rows, show_inbox link to apps but Mcp.apps.enabled is off'); + + Configure::write('Mcp.apps.enabled', true); + $this->exec('mcp check'); + $this->assertOutputContains('[PASS] Apps: 2 app resources: ui://test/broken, ui://test/inbox'); + + Configure::write('Mcp.servers.apps', [ + 'route' => '/mcp/apps', + 'discovery' => ['scanDirs' => ['src/McpApps'], 'excludeDirs' => []], + 'apps' => ['enabled' => true], + ]); + Configure::write('Mcp.discovery.scanDirs', ['src/Mcp']); + $this->exec('mcp check --server default'); + $this->assertOutputContains('[PASS] Apps: on, no app resources'); + } + + public function testAppsLineFailsOnAMissingResource(): void + { + Configure::write('Mcp.discovery.scanDirs', ['src/McpApps']); + Configure::write('Mcp.discovery.excludeDirs', []); + Configure::write('Mcp.apps.enabled', true); + Configure::write('Mcp.server.configure', function (Builder $builder): void { + $builder->addTool(fn(): string => 'x', 'orphan', meta: ['ui' => ['resourceUri' => 'ui://test/missing']]); + }); + + $this->exec('mcp check'); + + $this->assertOutputContains('[FAIL] Apps: orphan links to ui://test/missing, which is not an app resource'); + } + public function testCatalogLine(): void { $this->exec('mcp check'); From 6bb0910d5695f0428b76dd4aa9293df747040066 Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 21:22:42 +0100 Subject: [PATCH 037/181] MCP client: named clients over HTTP and stdio, tool filters --- src/Client/CakeHttpClientFactory.php | 22 + src/Client/CallsServerTrait.php | 140 +++++++ src/Client/ClientConfig.php | 396 ++++++++++++++++++ src/Client/ClientRegistry.php | 55 +++ src/Client/ClientSession.php | 127 ++++++ src/Client/Exception/ClientException.php | 14 + src/Client/HttpClientFactoryInterface.php | 20 + src/Client/McpClient.php | 70 ++++ src/Client/McpClients.php | 57 +++ src/Client/ServerUrlPolicy.php | 66 +++ src/Client/ToolFilter.php | 48 +++ src/Client/WatchedHttpClient.php | 46 ++ tests/Support/FixedHttpClientFactory.php | 36 ++ tests/Support/SdkServerHttpClient.php | 115 +++++ tests/TestCase/Client/ClientConfigTest.php | 183 ++++++++ tests/TestCase/Client/McpClientHttpTest.php | 194 +++++++++ tests/TestCase/Client/McpClientStdioTest.php | 48 +++ tests/TestCase/Client/ServerUrlPolicyTest.php | 71 ++++ tests/TestCase/Client/ToolFilterTest.php | 52 +++ tests/test_app/bin/stdio_mcp_server.php | 25 ++ 20 files changed, 1785 insertions(+) create mode 100644 src/Client/CakeHttpClientFactory.php create mode 100644 src/Client/CallsServerTrait.php create mode 100644 src/Client/ClientConfig.php create mode 100644 src/Client/ClientRegistry.php create mode 100644 src/Client/ClientSession.php create mode 100644 src/Client/Exception/ClientException.php create mode 100644 src/Client/HttpClientFactoryInterface.php create mode 100644 src/Client/McpClient.php create mode 100644 src/Client/McpClients.php create mode 100644 src/Client/ServerUrlPolicy.php create mode 100644 src/Client/ToolFilter.php create mode 100644 src/Client/WatchedHttpClient.php create mode 100644 tests/Support/FixedHttpClientFactory.php create mode 100644 tests/Support/SdkServerHttpClient.php create mode 100644 tests/TestCase/Client/ClientConfigTest.php create mode 100644 tests/TestCase/Client/McpClientHttpTest.php create mode 100644 tests/TestCase/Client/McpClientStdioTest.php create mode 100644 tests/TestCase/Client/ServerUrlPolicyTest.php create mode 100644 tests/TestCase/Client/ToolFilterTest.php create mode 100644 tests/test_app/bin/stdio_mcp_server.php diff --git a/src/Client/CakeHttpClientFactory.php b/src/Client/CakeHttpClientFactory.php new file mode 100644 index 0000000..13b1b9e --- /dev/null +++ b/src/Client/CakeHttpClientFactory.php @@ -0,0 +1,22 @@ + $config->timeout, 'redirect' => 0]); + } +} diff --git a/src/Client/CallsServerTrait.php b/src/Client/CallsServerTrait.php new file mode 100644 index 0000000..792b740 --- /dev/null +++ b/src/Client/CallsServerTrait.php @@ -0,0 +1,140 @@ + The tools the server offers that the client's filters allow. + */ + public function listTools(): array + { + $filter = $this->config()->toolFilter(); + $tools = []; + foreach ($this->pages(fn(Client $client, ?string $cursor) => $client->listTools($cursor)) as $page) { + foreach ($page->tools as $tool) { + if ($filter->allows($tool->name)) { + $tools[] = $tool; + } + } + } + + return $tools; + } + + /** + * @param string $name The tool. + * @param array $arguments Its arguments. + * @return \Mcp\Schema\Result\CallToolResult What the server answered; `isError` for a tool error. + * @throws \CakeDC\Mcp\Client\Exception\ClientException When the client's filters refuse the tool. + */ + public function callTool(string $name, array $arguments = []): CallToolResult + { + if (!$this->config()->toolFilter()->allows($name)) { + throw new ClientException(sprintf( + 'The tool "%s" is not allowed by "Mcp.clients.%s.tools".', + $name, + $this->config()->name, + )); + } + + return $this->run(fn(Client $client): CallToolResult => $client->callTool($name, $arguments)); + } + + /** + * @return list<\Mcp\Schema\ResourceDefinition> The server's resources. + */ + public function listResources(): array + { + $resources = []; + foreach ($this->pages(fn(Client $client, ?string $cursor) => $client->listResources($cursor)) as $page) { + array_push($resources, ...array_values($page->resources)); + } + + return $resources; + } + + /** + * @param string $uri The resource. + * @return \Mcp\Schema\Result\ReadResourceResult + */ + public function readResource(string $uri): ReadResourceResult + { + return $this->run(fn(Client $client): ReadResourceResult => $client->readResource($uri)); + } + + /** + * @return list<\Mcp\Schema\Prompt> The server's prompts. + */ + public function listPrompts(): array + { + $prompts = []; + foreach ($this->pages(fn(Client $client, ?string $cursor) => $client->listPrompts($cursor)) as $page) { + array_push($prompts, ...array_values($page->prompts)); + } + + return $prompts; + } + + /** + * @param string $name The prompt. + * @param array $arguments Its arguments. + * @return \Mcp\Schema\Result\GetPromptResult + */ + public function getPrompt(string $name, array $arguments = []): GetPromptResult + { + return $this->run(fn(Client $client): GetPromptResult => $client->getPrompt($name, $arguments)); + } + + /** + * @template P of \Mcp\Schema\Result\ListToolsResult|\Mcp\Schema\Result\ListResourcesResult|\Mcp\Schema\Result\ListPromptsResult + * @param callable(\Mcp\Client, ?string): P $list Lists one page. + * @return list

      + */ + private function pages(callable $list): array + { + $pages = []; + $cursor = null; + $left = self::$maxPages; + do { + $page = $this->run(fn(Client $client) => $list($client, $cursor)); + $pages[] = $page; + $cursor = $page->nextCursor; + $left--; + } while ($cursor !== null && $cursor !== '' && $left > 0); + + return $pages; + } +} diff --git a/src/Client/ClientConfig.php b/src/Client/ClientConfig.php new file mode 100644 index 0000000..c5c813e --- /dev/null +++ b/src/Client/ClientConfig.php @@ -0,0 +1,396 @@ + + */ + public const SETTINGS = [ + 'route' => '/mcp-client', + 'name' => 'CakePHP MCP Client', + 'version' => '1.0.0', + 'refreshLeeway' => 60, + 'maxResponseBytes' => 1024 * 1024, + 'identityAttribute' => 'identity', + ]; + + /** + * Keys a client config may have. + * + * @var list + */ + private const KEYS = [ + 'url', 'token', 'headers', 'command', 'args', 'env', 'cwd', 'auth', 'timeout', 'tools', 'protocolVersion', + 'allowInsecure', 'clientId', 'clientSecret', 'scopes', 'authorizationUrl', 'tokenUrl', 'revocationUrl', + ]; + + /** + * @param string $name The client's name in `Mcp.clients`. + * @param string|null $url The MCP server's URL, or null for a stdio client. + * @param string|null $command The stdio server's command, or null for an HTTP client. + * @param list $args The command's arguments. + * @param array $env Environment variables of the stdio server, over a minimal base. + * @param string|null $cwd The stdio server's working directory. + * @param array $headers Headers sent with every HTTP request, `Authorization` from `token` included. + * @param string $auth `app` or `user`. + * @param int $timeout Seconds for one request. + * @param list $toolsOnly Patterns of the tools allowed; empty for all. + * @param list $toolsExcept Patterns of the tools refused. + * @param \Mcp\Schema\Enum\ProtocolVersion|null $protocolVersion The protocol version to ask for, or null for the SDK's. + * @param bool $allowInsecure Whether configured URLs may use plain http to a host other than this machine. + * @param string|null $clientId The OAuth client id, or null to register one. + * @param string|null $clientSecret Its secret, if it has one. + * @param list $scopes Scopes to ask for; empty for the ones the server names. + * @param string|null $authorizationUrl A configured authorization endpoint. + * @param string|null $tokenUrl A configured token endpoint. + * @param string|null $revocationUrl A configured revocation endpoint. + */ + public function __construct( + public readonly string $name, + public readonly ?string $url, + public readonly ?string $command = null, + public readonly array $args = [], + public readonly array $env = [], + public readonly ?string $cwd = null, + public readonly array $headers = [], + public readonly string $auth = self::APP, + public readonly int $timeout = 30, + public readonly array $toolsOnly = [], + public readonly array $toolsExcept = [], + public readonly ?ProtocolVersion $protocolVersion = null, + public readonly bool $allowInsecure = false, + public readonly ?string $clientId = null, + public readonly ?string $clientSecret = null, + public readonly array $scopes = [], + public readonly ?string $authorizationUrl = null, + public readonly ?string $tokenUrl = null, + public readonly ?string $revocationUrl = null, + ) { + } + + /** + * @return bool Whether each user signs in (`auth` `user`). + */ + public function isUser(): bool + { + return $this->auth === self::USER; + } + + /** + * @return bool Whether the server is a local process on stdio. + */ + public function isStdio(): bool + { + return $this->command !== null; + } + + /** + * @return bool Whether the OAuth endpoints come from the config rather than from discovery. + */ + public function hasConfiguredEndpoints(): bool + { + return $this->authorizationUrl !== null; + } + + /** + * @return \CakeDC\Mcp\Client\ToolFilter The client's `tools.only` and `tools.except`. + */ + public function toolFilter(): ToolFilter + { + return new ToolFilter($this->toolsOnly, $this->toolsExcept); + } + + /** + * A setting shared by every client (`Mcp.client`), with its default. + * + * @param string $key A key of SETTINGS. + * @return mixed + */ + public static function setting(string $key): mixed + { + $value = Configure::read('Mcp.client.' . $key); + + return $value ?? self::SETTINGS[$key] ?? null; + } + + /** + * @return list The configured client names, in order. + * @throws \InvalidArgumentException When `Mcp.clients` is not an array of name => config. + */ + public static function names(): array + { + return array_keys(self::all()); + } + + /** + * @return bool Whether a configured client uses user mode, so the connect and callback routes are needed. + * @throws \InvalidArgumentException When `Mcp.clients` is not an array of name => config. + */ + public static function anyUserMode(): bool + { + foreach (self::all() as $config) { + if (($config['auth'] ?? null) === self::USER) { + return true; + } + } + + return false; + } + + /** + * @param string $name A key of `Mcp.clients`. + * @return self + * @throws \InvalidArgumentException When it is not configured or its config is invalid. + */ + public static function fromConfig(string $name): self + { + $config = self::all()[$name] ?? null; + if ($config === null) { + throw new InvalidArgumentException(sprintf('"Mcp.clients.%s" is not configured.', $name)); + } + $key = fn(string $child): string => sprintf('Mcp.clients.%s.%s', $name, $child); + $unknown = array_diff(array_keys($config), self::KEYS); + if ($unknown !== []) { + throw new InvalidArgumentException(sprintf( + '"%s" is not a client setting; the settings are %s.', + $key((string)reset($unknown)), + implode(', ', self::KEYS), + )); + } + + $auth = $config['auth'] ?? self::APP; + if ($auth !== self::APP && $auth !== self::USER) { + throw new InvalidArgumentException(sprintf('"%s" must be "app" or "user".', $key('auth'))); + } + $allowInsecure = self::bool($config, 'allowInsecure', $key); + $url = self::optionalString($config, 'url', $key); + $command = self::optionalString($config, 'command', $key); + if (($url === null) === ($command === null)) { + throw new InvalidArgumentException(sprintf( + $url === null + ? '"Mcp.clients.%s" needs a "url" (an HTTP server) or a "command" (a local stdio server).' + : '"Mcp.clients.%s" has a "url" and a "command"; set one, not both.', + $name, + )); + } + if ($url !== null) { + ServerUrlPolicy::check($url, $allowInsecure, $key('url')); + } + + $headers = $config['headers'] ?? []; + if (!is_array($headers)) { + throw new InvalidArgumentException(sprintf('"%s" must be an array of name => value.', $key('headers'))); + } + foreach ($headers as $header => $value) { + if (!is_string($header) || !is_string($value)) { + throw new InvalidArgumentException(sprintf('"%s" must be an array of name => value.', $key('headers'))); + } + } + if (array_key_exists('token', $config)) { + $token = $config['token']; + if (!is_string($token) || trim($token) === '') { + // Often an env() that is not set: sending no credentials would fail later and less clearly. + throw new InvalidArgumentException(sprintf( + '"%s" is empty; set it, or remove it if the server needs no token.', + $key('token'), + )); + } + $headers['Authorization'] = 'Bearer ' . $token; + } + $hasAuthorization = false; + foreach (array_keys($headers) as $header) { + $hasAuthorization = $hasAuthorization || strcasecmp($header, 'Authorization') === 0; + } + + if ($auth === self::USER) { + if ($url === null) { + throw new InvalidArgumentException(sprintf('"Mcp.clients.%s": user mode needs a "url".', $name)); + } + if ($hasAuthorization) { + throw new InvalidArgumentException(sprintf( + '"Mcp.clients.%s": user mode signs each user in, so it takes no "token" or Authorization header.', + $name, + )); + } + } + + $endpoints = []; + foreach (['authorizationUrl', 'tokenUrl', 'revocationUrl'] as $endpoint) { + $endpoints[$endpoint] = self::optionalString($config, $endpoint, $key); + if ($endpoints[$endpoint] !== null) { + ServerUrlPolicy::check($endpoints[$endpoint], $allowInsecure, $key($endpoint)); + } + } + $clientId = self::optionalString($config, 'clientId', $key); + $configured = array_filter($endpoints, fn(?string $value): bool => $value !== null) !== []; + if ( + $configured + && ($endpoints['authorizationUrl'] === null || $endpoints['tokenUrl'] === null || $clientId === null) + ) { + throw new InvalidArgumentException(sprintf( + '"Mcp.clients.%s" needs "authorizationUrl", "tokenUrl" and "clientId" together to skip discovery.', + $name, + )); + } + + $timeout = $config['timeout'] ?? 30; + if (!is_int($timeout) || $timeout < 1) { + throw new InvalidArgumentException(sprintf('"%s" must be a positive number of seconds.', $key('timeout'))); + } + $version = $config['protocolVersion'] ?? null; + $protocolVersion = null; + if ($version !== null) { + $protocolVersion = is_string($version) ? ProtocolVersion::tryFrom($version) : null; + if ($protocolVersion === null) { + throw new InvalidArgumentException(sprintf( + '"%s" must be one of %s.', + $key('protocolVersion'), + implode(', ', array_map(fn(ProtocolVersion $v): string => $v->value, ProtocolVersion::cases())), + )); + } + } + $tools = $config['tools'] ?? []; + if (!is_array($tools)) { + throw new InvalidArgumentException( + sprintf('"%s" must be an array with "only" and "except".', $key('tools')), + ); + } + + $env = $config['env'] ?? []; + if (!is_array($env)) { + throw new InvalidArgumentException(sprintf('"%s" must be an array of name => value.', $key('env'))); + } + foreach ($env as $variable => $value) { + if (!is_string($variable) || !is_string($value)) { + throw new InvalidArgumentException(sprintf('"%s" must be an array of name => value.', $key('env'))); + } + } + + /** @var array $headers */ + /** @var array $env */ + return new self( + $name, + $url, + $command, + self::strings($config['args'] ?? [], $key('args')), + $env, + self::optionalString($config, 'cwd', $key), + $headers, + $auth, + $timeout, + self::strings($tools['only'] ?? [], $key('tools.only')), + self::strings($tools['except'] ?? [], $key('tools.except')), + $protocolVersion, + $allowInsecure, + $clientId, + self::optionalString($config, 'clientSecret', $key), + self::strings($config['scopes'] ?? [], $key('scopes')), + $endpoints['authorizationUrl'], + $endpoints['tokenUrl'], + $endpoints['revocationUrl'], + ); + } + + /** + * @return array> `Mcp.clients`, checked for its shape. + * @throws \InvalidArgumentException + */ + private static function all(): array + { + $clients = Configure::read('Mcp.clients') ?? []; + if (!is_array($clients)) { + throw new InvalidArgumentException('"Mcp.clients" must be an array of client name => config.'); + } + foreach ($clients as $name => $config) { + if (!is_string($name) || !is_array($config)) { + throw new InvalidArgumentException('"Mcp.clients" must be an array of client name => config.'); + } + if (preg_match('/^[A-Za-z0-9_-]+$/', $name) !== 1) { + throw new InvalidArgumentException(sprintf( + 'The client name "%s" in "Mcp.clients" may only have letters, digits, "-" and "_".', + $name, + )); + } + } + + /** @var array> $clients */ + return $clients; + } + + /** + * @param array $config The client config. + * @param string $child The key. + * @param callable(string): string $key Builds the full key for a message. + * @return string|null The value, or null when it is not set. + */ + private static function optionalString(array $config, string $child, callable $key): ?string + { + $value = $config[$child] ?? null; + if ($value === null) { + return null; + } + if (!is_string($value) || trim($value) === '') { + throw new InvalidArgumentException(sprintf('"%s" must be a non-empty string.', $key($child))); + } + + return $value; + } + + /** + * @param array $config The client config. + * @param string $child The key. + * @param callable(string): string $key Builds the full key for a message. + * @return bool + */ + private static function bool(array $config, string $child, callable $key): bool + { + $value = $config[$child] ?? false; + if (!is_bool($value)) { + throw new InvalidArgumentException(sprintf('"%s" must be true or false.', $key($child))); + } + + return $value; + } + + /** + * @param mixed $value A configured list. + * @param string $key The full key, for the message. + * @return list + */ + private static function strings(mixed $value, string $key): array + { + if (!is_array($value) || !array_is_list($value)) { + throw new InvalidArgumentException(sprintf('"%s" must be a list of strings.', $key)); + } + foreach ($value as $item) { + if (!is_string($item) || $item === '') { + throw new InvalidArgumentException(sprintf('"%s" must be a list of strings.', $key)); + } + } + + return $value; + } +} diff --git a/src/Client/ClientRegistry.php b/src/Client/ClientRegistry.php new file mode 100644 index 0000000..d37c873 --- /dev/null +++ b/src/Client/ClientRegistry.php @@ -0,0 +1,55 @@ + + */ + private array $clients = []; + + /** + * @param \CakeDC\Mcp\Client\HttpClientFactoryInterface|null $http The PSR-18 client for configured URLs; Cake's + * HTTP client by default. + */ + public function __construct(private ?HttpClientFactoryInterface $http = null) + { + } + + /** + * @param string $name A key of `Mcp.clients`. + * @return \CakeDC\Mcp\Client\McpClient The same instance for the same name. + * @throws \InvalidArgumentException When it is not configured or its config is invalid. + */ + public function get(string $name): McpClient + { + return $this->clients[$name] ??= new McpClient(ClientConfig::fromConfig($name), $this); + } + + /** + * @return \CakeDC\Mcp\Client\HttpClientFactoryInterface + */ + public function http(): HttpClientFactoryInterface + { + return $this->http ??= new CakeHttpClientFactory(); + } + + /** + * Closes every client's connection. + * + * @return void + */ + public function close(): void + { + foreach ($this->clients as $client) { + $client->close(); + } + $this->clients = []; + } +} diff --git a/src/Client/ClientSession.php b/src/Client/ClientSession.php new file mode 100644 index 0000000..bb2043c --- /dev/null +++ b/src/Client/ClientSession.php @@ -0,0 +1,127 @@ + + */ + private const INHERITED_ENV = [ + 'PATH', 'HOME', 'USER', 'LANG', 'LC_ALL', 'TMPDIR', 'TEMP', 'TMP', 'SYSTEMROOT', 'USERPROFILE', 'APPDATA', + ]; + + private ?Client $client = null; + + private ?WatchedHttpClient $http = null; + + /** + * @param \CakeDC\Mcp\Client\ClientConfig $config The client. + * @param \CakeDC\Mcp\Client\HttpClientFactoryInterface $factory Makes the PSR-18 client for an HTTP server. + * @param array $headers Headers on top of the configured ones (a user's token). + */ + public function __construct( + private ClientConfig $config, + private HttpClientFactoryInterface $factory, + private array $headers = [], + ) { + } + + /** + * @return \Mcp\Client The SDK client, connected. + * @throws \Mcp\Exception\ConnectionException When the server cannot be reached or the handshake fails. + */ + public function client(): Client + { + if ($this->client !== null && $this->client->isConnected()) { + return $this->client; + } + $builder = Client::builder() + ->setClientInfo((string)ClientConfig::setting('name'), (string)ClientConfig::setting('version')) + ->setInitTimeout($this->config->timeout) + ->setRequestTimeout($this->config->timeout) + // The caller decides whether to try again; retries here would multiply the timeout. + ->setMaxRetries(0) + ->setLogger(new McpLogger()); + if ($this->config->protocolVersion !== null) { + $builder->setProtocolVersion($this->config->protocolVersion); + } + $client = $builder->build(); + $client->connect($this->transport()); + $this->client = $client; + + return $client; + } + + /** + * @return int|null The HTTP status of the last answer from the server, null for stdio or when none came. + */ + public function lastStatus(): ?int + { + return $this->http?->lastStatus(); + } + + /** + * Ends the connection: the HTTP session is deleted, the stdio server stopped. + * + * @return void + */ + public function close(): void + { + $this->client?->disconnect(); + $this->client = null; + } + + /** + * @return \Mcp\Client\Transport\TransportInterface + */ + private function transport(): TransportInterface + { + if ($this->config->command !== null) { + $env = []; + foreach (self::INHERITED_ENV as $name) { + $value = getenv($name); + if (is_string($value)) { + $env[$name] = $value; + } + } + + return new StdioTransport( + $this->config->command, + $this->config->args, + $this->config->cwd, + $this->config->env + $env, + new McpLogger(), + ); + } + + $this->http = new WatchedHttpClient($this->factory->create($this->config)); + + return new HttpTransport( + (string)$this->config->url, + $this->headers + $this->config->headers, + $this->http, + new RequestFactory(), + new StreamFactory(), + new McpLogger(), + ); + } +} diff --git a/src/Client/Exception/ClientException.php b/src/Client/Exception/ClientException.php new file mode 100644 index 0000000..35397e4 --- /dev/null +++ b/src/Client/Exception/ClientException.php @@ -0,0 +1,14 @@ +timeout`. + */ + public function create(ClientConfig $config): ClientInterface; +} diff --git a/src/Client/McpClient.php b/src/Client/McpClient.php new file mode 100644 index 0000000..6443a5d --- /dev/null +++ b/src/Client/McpClient.php @@ -0,0 +1,70 @@ +config->name; + } + + /** + * @inheritDoc + */ + public function config(): ClientConfig + { + return $this->config; + } + + /** + * Ends the connection to the server; the next call opens a new one. + * + * @return void + */ + public function close(): void + { + $this->session?->close(); + $this->session = null; + } + + /** + * @inheritDoc + */ + protected function run(callable $call): mixed + { + if ($this->config->isUser()) { + throw new LogicException(sprintf( + '"Mcp.clients.%s" is a user mode client: call it on behalf of a user with ' + . 'McpClients::get(\'%s\')->for($user).', + $this->config->name, + $this->config->name, + )); + } + $this->session ??= new ClientSession($this->config, $this->registry->http()); + + return $call($this->session->client()); + } +} diff --git a/src/Client/McpClients.php b/src/Client/McpClients.php new file mode 100644 index 0000000..6f3a76c --- /dev/null +++ b/src/Client/McpClients.php @@ -0,0 +1,57 @@ +callTool('search_issues', ['query' => 'bug']); + * McpClients::get('linear')->for($user)->listTools(); + * ``` + */ +final class McpClients +{ + private static ?ClientRegistry $registry = null; + + /** + * @param string $name A key of `Mcp.clients`. + * @return \CakeDC\Mcp\Client\McpClient + * @throws \InvalidArgumentException When it is not configured or its config is invalid. + */ + public static function get(string $name): McpClient + { + return self::registry()->get($name); + } + + /** + * @return \CakeDC\Mcp\Client\ClientRegistry The registry in use. + */ + public static function registry(): ClientRegistry + { + return self::$registry ??= new ClientRegistry(); + } + + /** + * Replaces the registry, for example with one built on test doubles. The previous one is closed. + * + * @param \CakeDC\Mcp\Client\ClientRegistry|null $registry The registry, or null for the default. + * @return void + */ + public static function setRegistry(?ClientRegistry $registry): void + { + self::$registry?->close(); + self::$registry = $registry; + } + + /** + * Closes every connection and goes back to the default registry. + * + * @return void + */ + public static function reset(): void + { + self::setRegistry(null); + } +} diff --git a/src/Client/ServerUrlPolicy.php b/src/Client/ServerUrlPolicy.php new file mode 100644 index 0000000..b5c3604 --- /dev/null +++ b/src/Client/ServerUrlPolicy.php @@ -0,0 +1,66 @@ + true on the client if this network is trusted.', + $key, + $host, + )); + } + } + + /** + * @param string $host Lowercase host, without IPv6 brackets. + * @return bool Whether it names this machine. + */ + private static function isLocal(string $host): bool + { + if ($host === 'localhost' || str_ends_with($host, '.localhost') || $host === '::1') { + return true; + } + + return filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false && str_starts_with($host, '127.'); + } +} diff --git a/src/Client/ToolFilter.php b/src/Client/ToolFilter.php new file mode 100644 index 0000000..b174bec --- /dev/null +++ b/src/Client/ToolFilter.php @@ -0,0 +1,48 @@ + $only Patterns of the tools allowed; empty for all. + * @param list $except Patterns of the tools refused. + */ + public function __construct(private array $only, private array $except) + { + } + + /** + * @param string $name A tool name. + * @return bool Whether the client may list and call it. + */ + public function allows(string $name): bool + { + if (self::matches($this->except, $name)) { + return false; + } + + return $this->only === [] || self::matches($this->only, $name); + } + + /** + * @param list $patterns The patterns. + * @param string $name The tool name. + * @return bool + */ + private static function matches(array $patterns, string $name): bool + { + foreach ($patterns as $pattern) { + if (fnmatch($pattern, $name)) { + return true; + } + } + + return false; + } +} diff --git a/src/Client/WatchedHttpClient.php b/src/Client/WatchedHttpClient.php new file mode 100644 index 0000000..cbdf97e --- /dev/null +++ b/src/Client/WatchedHttpClient.php @@ -0,0 +1,46 @@ +lastStatus = null; + $response = $this->client->sendRequest($request); + $this->lastStatus = $response->getStatusCode(); + + return $response; + } + + /** + * @return int|null The status of the last answer, null when none came. + */ + public function lastStatus(): ?int + { + return $this->lastStatus; + } +} diff --git a/tests/Support/FixedHttpClientFactory.php b/tests/Support/FixedHttpClientFactory.php new file mode 100644 index 0000000..745c4b1 --- /dev/null +++ b/tests/Support/FixedHttpClientFactory.php @@ -0,0 +1,36 @@ + + */ + public array $created = []; + + /** + * @param \Psr\Http\Client\ClientInterface $client The double. + */ + public function __construct(private ClientInterface $client) + { + } + + /** + * @inheritDoc + */ + public function create(ClientConfig $config): ClientInterface + { + $this->created[] = $config->name; + + return $this->client; + } +} diff --git a/tests/Support/SdkServerHttpClient.php b/tests/Support/SdkServerHttpClient.php new file mode 100644 index 0000000..ac472c0 --- /dev/null +++ b/tests/Support/SdkServerHttpClient.php @@ -0,0 +1,115 @@ +`), `whoami` (the bearer token it was called with), `delete_all`, `get_issue`, + * `get_secret`; resource `docs://readme`; prompt `greet`. + */ +final class SdkServerHttpClient implements ClientInterface +{ + /** + * @var list, rpc: string|null, body: string}> + */ + public array $requests = []; + + /** + * Bearer tokens the server accepts; null accepts any request. + * + * @var list|null + */ + public ?array $tokens = null; + + private InMemorySessionStore $sessions; + + private string $currentToken = ''; + + /** + * @param int $pageSize Items per page of a list. + */ + public function __construct(private int $pageSize = 50) + { + $this->sessions = new InMemorySessionStore(); + } + + /** + * @return list The JSON-RPC methods received, in order (notifications included). + */ + public function methods(): array + { + return array_values(array_filter(array_map(fn(array $r): ?string => $r['rpc'], $this->requests))); + } + + /** + * @inheritDoc + */ + public function sendRequest(RequestInterface $request): ResponseInterface + { + $body = (string)$request->getBody(); + $request->getBody()->rewind(); + $decoded = json_decode($body, true); + $headers = []; + foreach ($request->getHeaders() as $name => $values) { + $headers[strtolower((string)$name)] = implode(', ', $values); + } + $this->requests[] = [ + 'method' => $request->getMethod(), + 'url' => (string)$request->getUri(), + 'headers' => $headers, + 'rpc' => is_array($decoded) && is_string($decoded['method'] ?? null) ? $decoded['method'] : null, + 'body' => $body, + ]; + + $authorization = $headers['authorization'] ?? ''; + $this->currentToken = str_starts_with($authorization, 'Bearer ') ? substr($authorization, 7) : ''; + if ($this->tokens !== null && !in_array($this->currentToken, $this->tokens, true)) { + return new ClientResponse( + ['HTTP/1.1 401 Unauthorized', 'WWW-Authenticate: Bearer error="invalid_token"'], + '', + ); + } + + $token = $this->currentToken; + $server = Server::builder() + ->setServerInfo('fake', '1.0.0') + ->setSession($this->sessions) + ->setPaginationLimit($this->pageSize) + ->addTool(static fn(string $text): string => 'echo: ' . $text, 'echo', null, 'Echoes the text.') + ->addTool(static fn(): string => $token, 'whoami', null, 'The token of the call.') + ->addTool(static fn(): string => 'deleted', 'delete_all', null, 'Deletes everything.') + ->addTool(static fn(): string => 'issue', 'get_issue', null, 'Reads an issue.') + ->addTool(static fn(): string => 'secret', 'get_secret', null, 'Reads a secret.') + ->addResource(static fn(): string => 'Read me.', 'docs://readme', 'readme', null, null, 'text/plain') + ->addPrompt( + static fn(string $name): array => [['role' => 'user', 'content' => 'Hello ' . $name]], + 'greet', + null, + 'Greets someone.', + ) + ->build(); + + $serverRequest = (new ServerRequestFactory())->createServerRequest($request->getMethod(), $request->getUri()); + foreach ($request->getHeaders() as $name => $values) { + $serverRequest = $serverRequest->withHeader((string)$name, $values); + } + $serverRequest = $serverRequest->withHeader('Host', $request->getUri()->getHost()) + ->withBody((new StreamFactory())->createStream($body)); + + return $server->run(new StreamableHttpTransport($serverRequest, new ResponseFactory(), new StreamFactory(), null, [])); + } +} diff --git a/tests/TestCase/Client/ClientConfigTest.php b/tests/TestCase/Client/ClientConfigTest.php new file mode 100644 index 0000000..386f953 --- /dev/null +++ b/tests/TestCase/Client/ClientConfigTest.php @@ -0,0 +1,183 @@ + $config + * @return void + */ + private function expectError(array $config, string $message): void + { + Configure::write('Mcp.clients.broken', $config); + try { + ClientConfig::fromConfig('broken'); + $this->fail('No exception for ' . json_encode($config)); + } catch (InvalidArgumentException $e) { + $this->assertStringContainsString($message, $e->getMessage()); + } + } + + public function testAppModeWithTokenSetsTheBearerHeader(): void + { + Configure::write('Mcp.clients.github', [ + 'url' => 'https://api.example.com/mcp', + 'token' => 'secret-token', + 'headers' => ['X-Team' => 'core'], + 'timeout' => 12, + 'tools' => ['only' => ['get_*'], 'except' => ['get_secret']], + ]); + + $config = ClientConfig::fromConfig('github'); + + $this->assertSame('github', $config->name); + $this->assertSame('https://api.example.com/mcp', $config->url); + $this->assertSame(['X-Team' => 'core', 'Authorization' => 'Bearer secret-token'], $config->headers); + $this->assertSame(12, $config->timeout); + $this->assertSame(['get_*'], $config->toolsOnly); + $this->assertSame(['get_secret'], $config->toolsExcept); + $this->assertFalse($config->isUser()); + $this->assertFalse($config->isStdio()); + $this->assertNull($config->protocolVersion); + } + + public function testStdioClient(): void + { + Configure::write('Mcp.clients.local', [ + 'command' => 'php', + 'args' => ['server.php', '--quiet'], + 'env' => ['API_KEY' => 'k'], + 'cwd' => '/tmp', + ]); + + $config = ClientConfig::fromConfig('local'); + + $this->assertTrue($config->isStdio()); + $this->assertSame('php', $config->command); + $this->assertSame(['server.php', '--quiet'], $config->args); + $this->assertSame(['API_KEY' => 'k'], $config->env); + $this->assertSame('/tmp', $config->cwd); + $this->assertSame(30, $config->timeout); + } + + public function testUrlOrCommandIsRequiredButNotBoth(): void + { + $this->expectError([], 'needs a "url" (an HTTP server) or a "command"'); + $this->expectError(['url' => 'https://a.example.com', 'command' => 'php'], 'not both'); + } + + public function testUnknownClientFails(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('"Mcp.clients.nope" is not configured.'); + + ClientConfig::fromConfig('nope'); + } + + public function testUnsetTokenFails(): void + { + $this->expectError(['url' => 'https://a.example.com', 'token' => null], '"Mcp.clients.broken.token" is empty'); + $this->expectError(['url' => 'https://a.example.com', 'token' => ''], '"Mcp.clients.broken.token" is empty'); + } + + public function testUserModeNeedsAUrlAndNoToken(): void + { + $this->expectError(['command' => 'php', 'auth' => 'user'], 'user mode needs a "url"'); + $this->expectError( + ['url' => 'https://a.example.com', 'auth' => 'user', 'token' => 't'], + 'user mode signs each user in', + ); + $this->expectError( + ['url' => 'https://a.example.com', 'auth' => 'user', 'headers' => ['authorization' => 'Bearer x']], + 'user mode signs each user in', + ); + $this->expectError(['url' => 'https://a.example.com', 'auth' => 'admin'], '"app" or "user"'); + + Configure::write('Mcp.clients.linear', ['url' => 'https://mcp.example.com/mcp', 'auth' => 'user']); + $this->assertTrue(ClientConfig::fromConfig('linear')->isUser()); + } + + public function testConfiguredEndpointsNeedAClientId(): void + { + $this->expectError( + ['url' => 'https://a.example.com', 'auth' => 'user', 'tokenUrl' => 'https://a.example.com/token'], + 'needs "authorizationUrl", "tokenUrl" and "clientId" together', + ); + $this->expectError( + [ + 'url' => 'https://a.example.com', 'auth' => 'user', + 'authorizationUrl' => 'https://a.example.com/authorize', 'tokenUrl' => 'http://a.example.com/token', + 'clientId' => 'abc', + ], + '"Mcp.clients.broken.tokenUrl"', + ); + + Configure::write('Mcp.clients.internal', [ + 'url' => 'https://mcp.internal/mcp', + 'auth' => 'user', + 'authorizationUrl' => 'https://sso.internal/authorize', + 'tokenUrl' => 'https://sso.internal/token', + 'revocationUrl' => 'https://sso.internal/revoke', + 'clientId' => 'cake-app', + 'clientSecret' => 's3cret', + 'scopes' => ['read', 'write'], + ]); + $config = ClientConfig::fromConfig('internal'); + $this->assertSame('https://sso.internal/token', $config->tokenUrl); + $this->assertSame('cake-app', $config->clientId); + $this->assertSame(['read', 'write'], $config->scopes); + } + + public function testProtocolVersionMustBeKnown(): void + { + $this->expectError(['url' => 'https://a.example.com', 'protocolVersion' => '2020-01-01'], 'protocolVersion'); + + Configure::write('Mcp.clients.old', ['url' => 'https://a.example.com', 'protocolVersion' => '2025-06-18']); + $this->assertSame(ProtocolVersion::V2025_06_18, ClientConfig::fromConfig('old')->protocolVersion); + } + + public function testToolPatternsMustBeStrings(): void + { + $this->expectError(['url' => 'https://a.example.com', 'tools' => ['only' => 'get_*']], 'tools.only'); + $this->expectError(['url' => 'https://a.example.com', 'tools' => ['except' => [1]]], 'tools.except'); + $this->expectError(['url' => 'https://a.example.com', 'timeout' => 0], 'timeout'); + $this->expectError(['url' => 'https://a.example.com', 'headers' => ['X' => 1]], 'headers'); + } + + public function testNamesAndUserMode(): void + { + Configure::write('Mcp.clients', [ + 'a' => ['url' => 'https://a.example.com'], + 'b' => ['url' => 'https://b.example.com'], + ]); + $this->assertSame(['a', 'b'], ClientConfig::names()); + $this->assertFalse(ClientConfig::anyUserMode()); + + Configure::write('Mcp.clients.c', ['url' => 'https://c.example.com', 'auth' => 'user']); + $this->assertTrue(ClientConfig::anyUserMode()); + + Configure::write('Mcp.clients', ['bad name' => ['url' => 'https://a.example.com']]); + $this->expectException(InvalidArgumentException::class); + ClientConfig::names(); + } + + public function testSettingsHaveDefaults(): void + { + Configure::delete('Mcp.client'); + $this->assertSame('/mcp-client', ClientConfig::setting('route')); + $this->assertSame(60, ClientConfig::setting('refreshLeeway')); + $this->assertSame(1024 * 1024, ClientConfig::setting('maxResponseBytes')); + + Configure::write('Mcp.client.route', '/connections'); + $this->assertSame('/connections', ClientConfig::setting('route')); + $this->assertSame('identity', ClientConfig::setting('identityAttribute')); + } +} diff --git a/tests/TestCase/Client/McpClientHttpTest.php b/tests/TestCase/Client/McpClientHttpTest.php new file mode 100644 index 0000000..359995b --- /dev/null +++ b/tests/TestCase/Client/McpClientHttpTest.php @@ -0,0 +1,194 @@ +server = new SdkServerHttpClient(); + $this->factory = new FixedHttpClientFactory($this->server); + McpClients::setRegistry(new ClientRegistry($this->factory)); + Configure::write('Mcp.clients.remote', [ + 'url' => 'https://mcp.example.com/mcp', + 'token' => 'app-token', + ]); + } + + protected function tearDown(): void + { + McpClients::reset(); + parent::tearDown(); + } + + /** + * @param list<\Mcp\Schema\Tool> $tools + * @return list + */ + private static function names(array $tools): array + { + return array_map(fn(Tool $tool): string => $tool->name, $tools); + } + + public function testListsAndCallsToolsWithTheToken(): void + { + $client = McpClients::get('remote'); + + $this->assertSame( + ['echo', 'whoami', 'delete_all', 'get_issue', 'get_secret'], + self::names($client->listTools()), + ); + $result = $client->callTool('echo', ['text' => 'hi']); + $this->assertFalse($result->isError); + $this->assertInstanceOf(TextContent::class, $result->content[0]); + $this->assertSame('echo: hi', $result->content[0]->text); + $this->assertSame('app-token', $client->callTool('whoami')->content[0]->text ?? null); + + foreach ($this->server->requests as $request) { + $this->assertSame('https://mcp.example.com/mcp', $request['url']); + $this->assertSame('Bearer app-token', $request['headers']['authorization'] ?? null); + } + $this->assertSame(['remote'], $this->factory->created); + } + + public function testHeadersAreSent(): void + { + Configure::write('Mcp.clients.keyed', [ + 'url' => 'https://mcp.example.com/mcp', + 'headers' => ['X-Api-Key' => 'k-123'], + ]); + + McpClients::get('keyed')->listTools(); + + $this->assertSame('k-123', $this->server->requests[0]['headers']['x-api-key'] ?? null); + $this->assertArrayNotHasKey('authorization', $this->server->requests[0]['headers']); + } + + public function testToolFiltersHideAndRefuseTools(): void + { + Configure::write('Mcp.clients.filtered', [ + 'url' => 'https://mcp.example.com/mcp', + 'tools' => ['only' => ['get_*', 'echo'], 'except' => ['get_secret']], + ]); + $client = McpClients::get('filtered'); + + $this->assertSame(['echo', 'get_issue'], self::names($client->listTools())); + + foreach (['delete_all', 'get_secret'] as $tool) { + try { + $client->callTool($tool); + $this->fail($tool . ' was called'); + } catch (ClientException $e) { + $this->assertStringContainsString( + sprintf('"%s" is not allowed by "Mcp.clients.filtered.tools"', $tool), + $e->getMessage(), + ); + } + } + $this->assertNotContains('tools/call', $this->server->methods()); + $this->assertSame('echo: x', $client->callTool('echo', ['text' => 'x'])->content[0]->text ?? null); + } + + public function testListsEveryPage(): void + { + $this->server = new SdkServerHttpClient(2); + McpClients::setRegistry(new ClientRegistry(new FixedHttpClientFactory($this->server))); + + $this->assertCount(5, McpClients::get('remote')->listTools()); + $this->assertSame(3, count(array_keys($this->server->methods(), 'tools/list', true))); + } + + public function testResourcesAndPrompts(): void + { + $client = McpClients::get('remote'); + + $resources = $client->listResources(); + $this->assertSame('docs://readme', $resources[0]->uri); + $contents = $client->readResource('docs://readme')->contents[0]; + $this->assertInstanceOf(TextResourceContents::class, $contents); + $this->assertSame('Read me.', $contents->text); + + $this->assertSame('greet', $client->listPrompts()[0]->name); + $message = $client->getPrompt('greet', ['name' => 'Ana'])->messages[0]; + $this->assertInstanceOf(TextContent::class, $message->content); + $this->assertSame('Hello Ana', $message->content->text); + } + + public function testProtocolVersionIsSent(): void + { + Configure::write('Mcp.clients.pinned', [ + 'url' => 'https://mcp.example.com/mcp', + 'protocolVersion' => '2025-06-18', + ]); + + McpClients::get('pinned')->listTools(); + + $initialize = json_decode($this->server->requests[0]['body'], true); + $this->assertSame('initialize', $initialize['method']); + $this->assertSame('2025-06-18', $initialize['params']['protocolVersion']); + $last = $this->server->requests[array_key_last($this->server->requests)]; + $this->assertSame('2025-06-18', $last['headers']['mcp-protocol-version'] ?? null); + } + + public function testOneSessionForSeveralCalls(): void + { + $client = McpClients::get('remote'); + $client->listTools(); + $client->callTool('echo', ['text' => 'a']); + $client->callTool('echo', ['text' => 'b']); + + $handshakes = array_intersect($this->server->methods(), ['initialize', 'server/discover']); + $this->assertCount(1, $handshakes); + $this->assertSame($client, McpClients::get('remote')); + } + + public function testUserModeClientRefusesAppModeCalls(): void + { + Configure::write('Mcp.clients.personal', ['url' => 'https://mcp.example.com/mcp', 'auth' => 'user']); + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('McpClients::get(\'personal\')->for($user)'); + + McpClients::get('personal')->listTools(); + } + + public function testPlainHttpToARemoteHostFailsAtConfigTime(): void + { + Configure::write('Mcp.clients.plain', ['url' => 'http://mcp.example.com/mcp']); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('allowInsecure'); + + McpClients::get('plain'); + } + + public function testCloseEndsTheSession(): void + { + $client = McpClients::get('remote'); + $client->listTools(); + $client->close(); + $client->listTools(); + + $handshakes = array_intersect($this->server->methods(), ['initialize', 'server/discover']); + $this->assertCount(2, $handshakes); + } +} diff --git a/tests/TestCase/Client/McpClientStdioTest.php b/tests/TestCase/Client/McpClientStdioTest.php new file mode 100644 index 0000000..34b2bec --- /dev/null +++ b/tests/TestCase/Client/McpClientStdioTest.php @@ -0,0 +1,48 @@ + PHP_BINARY, + 'args' => [ROOT . 'bin' . DS . 'stdio_mcp_server.php'], + 'env' => ['MCP_CLIENT_TEST_KEY' => 'from-config'], + 'timeout' => 20, + ]); + } + + protected function tearDown(): void + { + putenv('MCP_CLIENT_TEST_PARENT_SECRET'); + McpClients::reset(); + parent::tearDown(); + } + + public function testCallsAToolOverStdio(): void + { + $client = McpClients::get('local'); + + $names = array_map(fn($tool): string => $tool->name, $client->listTools()); + $this->assertSame(['echo', 'env'], $names); + $this->assertSame('echo: over stdio', $client->callTool('echo', ['text' => 'over stdio'])->content[0]->text ?? null); + } + + public function testEnvIsPassedAndTheParentEnvIsNot(): void + { + $client = McpClients::get('local'); + + $this->assertSame('from-config', $client->callTool('env', ['name' => 'MCP_CLIENT_TEST_KEY'])->content[0]->text ?? null); + $this->assertSame('unset', $client->callTool('env', ['name' => 'MCP_CLIENT_TEST_PARENT_SECRET'])->content[0]->text ?? null); + $this->assertNotSame('unset', $client->callTool('env', ['name' => 'PATH'])->content[0]->text ?? null); + } +} diff --git a/tests/TestCase/Client/ServerUrlPolicyTest.php b/tests/TestCase/Client/ServerUrlPolicyTest.php new file mode 100644 index 0000000..ae89458 --- /dev/null +++ b/tests/TestCase/Client/ServerUrlPolicyTest.php @@ -0,0 +1,71 @@ + + */ + public static function allowed(): array + { + return [ + 'public https' => ['https://mcp.example.com/mcp', false], + 'internal https' => ['https://mcp.internal:8443/mcp', false], + 'private address https' => ['https://10.0.0.5/mcp', false], + 'localhost http' => ['http://localhost:8765/mcp', false], + 'loopback http' => ['http://127.0.0.1/mcp', false], + 'ipv6 loopback http' => ['http://[::1]:8080/mcp', false], + 'dot localhost http' => ['http://tools.localhost/mcp', false], + 'insecure allowed' => ['http://mcp.internal/mcp', true], + 'query kept' => ['https://mcp.example.com/mcp?team=1', false], + ]; + } + + #[DataProvider('allowed')] + public function testAllowed(string $url, bool $allowInsecure): void + { + ServerUrlPolicy::check($url, $allowInsecure, 'Mcp.clients.x.url'); + $this->addToAssertionCount(1); + } + + /** + * @return array + */ + public static function refused(): array + { + return [ + 'remote http' => ['http://mcp.example.com/mcp', false], + 'private http' => ['http://10.0.0.5/mcp', false], + 'localhost lookalike' => ['http://localhost.example.com/mcp', false], + 'userinfo' => ['https://user:pass@mcp.example.com/mcp', false], + 'fragment' => ['https://mcp.example.com/mcp#x', false], + 'other scheme' => ['ftp://mcp.example.com/mcp', true], + 'no host' => ['https:///mcp', false], + 'relative' => ['/mcp', false], + 'empty' => ['', false], + ]; + } + + #[DataProvider('refused')] + public function testRefused(string $url, bool $allowInsecure): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('"Mcp.clients.x.url"'); + + ServerUrlPolicy::check($url, $allowInsecure, 'Mcp.clients.x.url'); + } + + public function testPlainHttpMessageNamesTheWayOut(): void + { + $this->expectExceptionMessage('allowInsecure'); + + ServerUrlPolicy::check('http://mcp.example.com/mcp', false, 'Mcp.clients.x.url'); + } +} diff --git a/tests/TestCase/Client/ToolFilterTest.php b/tests/TestCase/Client/ToolFilterTest.php new file mode 100644 index 0000000..7a97d09 --- /dev/null +++ b/tests/TestCase/Client/ToolFilterTest.php @@ -0,0 +1,52 @@ +assertTrue($filter->allows('anything')); + } + + public function testOnly(): void + { + $filter = new ToolFilter(['get_*', 'search'], []); + + $this->assertTrue($filter->allows('get_issue')); + $this->assertTrue($filter->allows('search')); + $this->assertFalse($filter->allows('delete_issue')); + $this->assertFalse($filter->allows('search_all')); + } + + public function testExcept(): void + { + $filter = new ToolFilter([], ['delete_*']); + + $this->assertTrue($filter->allows('get_issue')); + $this->assertFalse($filter->allows('delete_issue')); + } + + public function testExceptWinsOverOnly(): void + { + $filter = new ToolFilter(['*_issue'], ['delete_*']); + + $this->assertTrue($filter->allows('get_issue')); + $this->assertFalse($filter->allows('delete_issue')); + $this->assertFalse($filter->allows('get_repo')); + } + + public function testPatternsAreCaseSensitiveAndWholeName(): void + { + $filter = new ToolFilter(['get'], []); + + $this->assertFalse($filter->allows('GET')); + $this->assertFalse($filter->allows('get_issue')); + } +} diff --git a/tests/test_app/bin/stdio_mcp_server.php b/tests/test_app/bin/stdio_mcp_server.php new file mode 100644 index 0000000..f445f78 --- /dev/null +++ b/tests/test_app/bin/stdio_mcp_server.php @@ -0,0 +1,25 @@ +setServerInfo('stdio-fake', '1.0.0') + ->addTool(static fn(string $text): string => 'echo: ' . $text, 'echo', null, 'Echoes the text.') + ->addTool( + static fn(string $name): string => getenv($name) === false ? 'unset' : (string)getenv($name), + 'env', + null, + 'Reads an environment variable.', + ) + ->build(); + +$server->run(new StdioTransport()); From e301459d6a64a6b7a5e24ed45754d4e77e101c5a Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 21:26:35 +0100 Subject: [PATCH 038/181] MCP client: SSRF guard for URLs learned from remote metadata --- src/Client/Http/BlockedUrlException.php | 14 ++ src/Client/Http/CakeGuardedTransport.php | 112 ++++++++++++++ src/Client/Http/CheckedEndpoint.php | 24 +++ src/Client/Http/DnsHostResolver.php | 30 ++++ src/Client/Http/EndpointGuard.php | 141 ++++++++++++++++++ src/Client/Http/GuardedHttp.php | 119 +++++++++++++++ src/Client/Http/GuardedTransportInterface.php | 21 +++ src/Client/Http/HostResolverInterface.php | 16 ++ src/Client/Http/HttpRequest.php | 26 ++++ src/Client/Http/HttpResponse.php | 66 ++++++++ src/Client/Http/OutboundHttp.php | 90 +++++++++++ tests/Support/ScriptedGuardedTransport.php | 71 +++++++++ tests/Support/StaticHostResolver.php | 44 ++++++ .../Client/Http/CakeGuardedTransportTest.php | 132 ++++++++++++++++ .../Client/Http/EndpointGuardTest.php | 129 ++++++++++++++++ .../TestCase/Client/Http/GuardedHttpTest.php | 115 ++++++++++++++ .../TestCase/Client/Http/OutboundHttpTest.php | 141 ++++++++++++++++++ 17 files changed, 1291 insertions(+) create mode 100644 src/Client/Http/BlockedUrlException.php create mode 100644 src/Client/Http/CakeGuardedTransport.php create mode 100644 src/Client/Http/CheckedEndpoint.php create mode 100644 src/Client/Http/DnsHostResolver.php create mode 100644 src/Client/Http/EndpointGuard.php create mode 100644 src/Client/Http/GuardedHttp.php create mode 100644 src/Client/Http/GuardedTransportInterface.php create mode 100644 src/Client/Http/HostResolverInterface.php create mode 100644 src/Client/Http/HttpRequest.php create mode 100644 src/Client/Http/HttpResponse.php create mode 100644 src/Client/Http/OutboundHttp.php create mode 100644 tests/Support/ScriptedGuardedTransport.php create mode 100644 tests/Support/StaticHostResolver.php create mode 100644 tests/TestCase/Client/Http/CakeGuardedTransportTest.php create mode 100644 tests/TestCase/Client/Http/EndpointGuardTest.php create mode 100644 tests/TestCase/Client/Http/GuardedHttpTest.php create mode 100644 tests/TestCase/Client/Http/OutboundHttpTest.php diff --git a/src/Client/Http/BlockedUrlException.php b/src/Client/Http/BlockedUrlException.php new file mode 100644 index 0000000..69f58bf --- /dev/null +++ b/src/Client/Http/BlockedUrlException.php @@ -0,0 +1,14 @@ +url); + $host = is_array($parts) ? strtolower(trim((string)($parts['host'] ?? ''), '[]')) : ''; + $host = str_ends_with($host, '.') ? substr($host, 0, -1) : $host; + $port = is_array($parts) ? (int)($parts['port'] ?? 443) : 0; + $scheme = is_array($parts) ? strtolower((string)($parts['scheme'] ?? '')) : ''; + if ($scheme !== 'https' || $host !== $pin->host || $port !== $pin->port) { + throw new BlockedUrlException('The request left the address that was checked.'); + } + + $tooLarge = false; + $ip = str_contains($pin->ip, ':') ? '[' . $pin->ip . ']' : $pin->ip; + $curl = [ + CURLOPT_RESOLVE => [sprintf('%s:%d:%s', $pin->host, $pin->port, $ip)], + CURLOPT_PROXY => '', + CURLOPT_NOPROXY => '*', + CURLOPT_FOLLOWLOCATION => false, + CURLOPT_MAXFILESIZE => $maxBytes, + CURLOPT_NOPROGRESS => false, + CURLOPT_XFERINFOFUNCTION => function ($handle, $total, $downloaded) use ($maxBytes, &$tooLarge): int { + if ($downloaded > $maxBytes) { + $tooLarge = true; + + return 1; + } + + return 0; + }, + ]; + if (defined('CURLOPT_PROTOCOLS_STR')) { + $curl[CURLOPT_PROTOCOLS_STR] = 'https'; + } else { + $curl[CURLOPT_PROTOCOLS] = CURLPROTO_HTTPS; + } + $headers = array_filter( + $request->headers, + fn(string $name): bool => strcasecmp($name, 'host') !== 0, + ARRAY_FILTER_USE_KEY, + ); + + try { + $client = new Client(['adapter' => $this->adapter ?? Curl::class]); + $response = $client->send( + new Request($request->url, $request->method, $headers, $request->body), + [ + 'timeout' => $request->timeout, + 'ssl_verify_peer' => true, + 'ssl_verify_host' => true, + 'curl' => $curl, + ], + ); + } catch (ClientExceptionInterface | InvalidArgumentException $e) { + // The message is left out: it quotes the URL, whose query may carry a secret. + if ($tooLarge || str_contains($e->getMessage(), '(' . CURLE_FILESIZE_EXCEEDED . ')')) { + throw self::tooLarge(); + } + + throw new ClientException(sprintf('The server at %s could not be reached.', $pin->host)); + } + $body = (string)$response->getBody(); + if (strlen($body) > $maxBytes) { + throw self::tooLarge(); + } + + return new HttpResponse($response->getStatusCode(), $response->getHeaders(), $body); + } + + /** + * @return \CakeDC\Mcp\Client\Exception\ClientException + */ + private static function tooLarge(): ClientException + { + return new ClientException('The server sent a larger answer than the MCP client accepts.'); + } +} diff --git a/src/Client/Http/CheckedEndpoint.php b/src/Client/Http/CheckedEndpoint.php new file mode 100644 index 0000000..e1349a1 --- /dev/null +++ b/src/Client/Http/CheckedEndpoint.php @@ -0,0 +1,24 @@ +resolver->resolve($host); + if ($addresses === []) { + throw new BlockedUrlException($notPublic); + } + foreach ($addresses as $address) { + if (!self::isPublic($address)) { + throw new BlockedUrlException($notPublic); + } + } + $port = (int)($parts['port'] ?? 443); + + return new CheckedEndpoint( + 'https://' . $host . ($port === 443 ? '' : ':' . $port), + $host, + $port, + $addresses[0], + ); + } + + /** + * @param string $host A host that is not an IP address, lowercase, without a trailing dot. + * @return bool Whether it is letters, digits, hyphens and dots only, in labels of 1 to 63 characters that do not + * start or end with a hyphen. + */ + private static function isHostName(string $host): bool + { + return strlen($host) <= 253 + && preg_match('/^(?!-)[a-z0-9-]{1,63}(?transport->send( + new HttpRequest('GET', $url, ['Accept' => 'application/json'], null, $timeout), + $this->guard->check($url), + $this->maxBytes, + ); + $location = $response->header('Location'); + if (!$response->isRedirect() || $location === null || trim($location) === '') { + return $response; + } + if ($hop >= self::MAX_REDIRECTS) { + throw new BlockedUrlException('The server redirected too many times.'); + } + $url = self::resolve($url, $location); + } + } + + /** + * A request that may carry credentials. Never follows a redirect. + * + * @param \CakeDC\Mcp\Client\Http\HttpRequest $request The request, sent to its exact URL. + * @return \CakeDC\Mcp\Client\Http\HttpResponse Any status but a 3xx. + * @throws \CakeDC\Mcp\Client\Http\BlockedUrlException For an address that is not allowed or a 3xx answer. + * @throws \CakeDC\Mcp\Client\Exception\ClientException + */ + public function send(HttpRequest $request): HttpResponse + { + $response = $this->transport->send($request, $this->guard->check($request->url), $this->maxBytes); + if ($response->isRedirect()) { + throw self::redirectRefused(); + } + + return $response; + } + + /** + * @return \CakeDC\Mcp\Client\Http\BlockedUrlException + */ + public static function redirectRefused(): BlockedUrlException + { + return new BlockedUrlException( + 'The server answered with a redirect, which the MCP client does not follow for a request with credentials.', + ); + } + + /** + * @param string $from The URL that answered. + * @param string $location Its Location header, absolute or relative. + * @return string The next URL, without a fragment; the guard judges it next. + */ + public static function resolve(string $from, string $location): string + { + $location = (string)preg_replace('/#.*$/s', '', trim($location)); + if (preg_match('/^[a-z][a-z0-9+.-]*:/i', $location) === 1) { + return $location; + } + $parts = (array)parse_url($from); + $scheme = (string)($parts['scheme'] ?? 'https'); + if (str_starts_with($location, '//')) { + return $scheme . ':' . $location; + } + $origin = $scheme . '://' . ($parts['host'] ?? '') . (isset($parts['port']) ? ':' . $parts['port'] : ''); + if (str_starts_with($location, '/')) { + return $origin . $location; + } + $path = (string)($parts['path'] ?? '/'); + $base = substr($path, 0, (int)strrpos($path, '/') + 1); + if (str_starts_with($location, '?')) { + return $origin . $path . $location; + } + + return $origin . ($base === '' ? '/' : $base) . $location; + } +} diff --git a/src/Client/Http/GuardedTransportInterface.php b/src/Client/Http/GuardedTransportInterface.php new file mode 100644 index 0000000..6dbe5d7 --- /dev/null +++ b/src/Client/Http/GuardedTransportInterface.php @@ -0,0 +1,21 @@ + Its IPv4 and IPv6 addresses; empty when it does not resolve. + */ + public function resolve(string $host): array; +} diff --git a/src/Client/Http/HttpRequest.php b/src/Client/Http/HttpRequest.php new file mode 100644 index 0000000..bd7c76a --- /dev/null +++ b/src/Client/Http/HttpRequest.php @@ -0,0 +1,26 @@ + $headers Header name => value. + * @param string|null $body The body, or null for none. + * @param float $timeout Seconds for the whole request. + */ + public function __construct( + public readonly string $method, + public readonly string $url, + public readonly array $headers = [], + public readonly ?string $body = null, + public readonly float $timeout = 15.0, + ) { + } +} diff --git a/src/Client/Http/HttpResponse.php b/src/Client/Http/HttpResponse.php new file mode 100644 index 0000000..25233f0 --- /dev/null +++ b/src/Client/Http/HttpResponse.php @@ -0,0 +1,66 @@ +> $headers Header name => values, as the server sent them. + * @param string $body The body. + */ + public function __construct( + public readonly int $status, + public readonly array $headers, + public readonly string $body, + ) { + } + + /** + * @param string $name Header name, in any case. + * @return string|null Its values joined with ", ", or null when the server did not send it. + */ + public function header(string $name): ?string + { + $values = null; + foreach ($this->headers as $key => $value) { + if (strcasecmp((string)$key, $name) === 0) { + $values = array_merge($values ?? [], $value); + } + } + + return $values === null ? null : implode(', ', $values); + } + + /** + * @return array|null The body as a JSON object, or null when it is not one. + */ + public function json(): ?array + { + try { + $decoded = json_decode($this->body, true, 32, JSON_THROW_ON_ERROR); + } catch (JsonException) { + return null; + } + if (!is_array($decoded) || ($decoded !== [] && array_is_list($decoded))) { + return null; + } + + /** @var array $decoded */ + return $decoded; + } + + /** + * @return bool Whether it is a redirect that may carry a Location. + */ + public function isRedirect(): bool + { + return $this->status >= 300 && $this->status < 400; + } +} diff --git a/src/Client/Http/OutboundHttp.php b/src/Client/Http/OutboundHttp.php new file mode 100644 index 0000000..2f31f6c --- /dev/null +++ b/src/Client/Http/OutboundHttp.php @@ -0,0 +1,90 @@ +guarded->get($url, $timeout); + } + $response = $this->trusted(new HttpRequest('GET', $url, ['Accept' => 'application/json'], null, $timeout)); + $location = $response->header('Location'); + if ($response->isRedirect() && $location !== null && trim($location) !== '') { + return $this->guarded->get(GuardedHttp::resolve($url, $location), $timeout); + } + + return $response; + } + + /** + * A request that may carry credentials; a redirect is refused. + * + * @param \CakeDC\Mcp\Client\Http\HttpRequest $request The request. + * @param bool $trusted Whether its URL comes from the config. + * @return \CakeDC\Mcp\Client\Http\HttpResponse + * @throws \CakeDC\Mcp\Client\Exception\ClientException + */ + public function send(HttpRequest $request, bool $trusted): HttpResponse + { + if (!$trusted) { + return $this->guarded->send($request); + } + $response = $this->trusted($request); + if ($response->isRedirect()) { + throw GuardedHttp::redirectRefused(); + } + + return $response; + } + + /** + * @param \CakeDC\Mcp\Client\Http\HttpRequest $request The request. + * @return \CakeDC\Mcp\Client\Http\HttpResponse + */ + private function trusted(HttpRequest $request): HttpResponse + { + try { + $response = $this->trusted->sendRequest( + new Request($request->url, $request->method, $request->headers, $request->body), + ); + } catch (ClientExceptionInterface) { + // The message is left out: it may quote the URL or the request. + throw new ClientException(sprintf( + 'The server at %s could not be reached.', + (string)parse_url($request->url, PHP_URL_HOST), + )); + } + + return new HttpResponse($response->getStatusCode(), $response->getHeaders(), (string)$response->getBody()); + } +} diff --git a/tests/Support/ScriptedGuardedTransport.php b/tests/Support/ScriptedGuardedTransport.php new file mode 100644 index 0000000..9cdfc21 --- /dev/null +++ b/tests/Support/ScriptedGuardedTransport.php @@ -0,0 +1,71 @@ + + */ + public array $sent = []; + + /** + * @var array + */ + private array $answers = []; + + /** + * @param string $method HTTP method. + * @param string $url The exact URL. + * @param \CakeDC\Mcp\Client\Http\HttpResponse|Closure(\CakeDC\Mcp\Client\Http\HttpRequest): \CakeDC\Mcp\Client\Http\HttpResponse $answer The answer. + * @return void + */ + public function on(string $method, string $url, HttpResponse|Closure $answer): void + { + $this->answers[$method . ' ' . $url] = $answer; + } + + /** + * @param string $url The exact URL. + * @param array $document The JSON document a GET answers. + * @return void + */ + public function json(string $url, array $document): void + { + $this->on('GET', $url, new HttpResponse( + 200, + ['Content-Type' => ['application/json']], + (string)json_encode($document, JSON_UNESCAPED_SLASHES), + )); + } + + /** + * @return list "METHOD url" of every request sent. + */ + public function urls(): array + { + return array_map(fn(array $sent): string => $sent['request']->method . ' ' . $sent['request']->url, $this->sent); + } + + /** + * @inheritDoc + */ + public function send(HttpRequest $request, CheckedEndpoint $pin, int $maxBytes): HttpResponse + { + $this->sent[] = ['request' => $request, 'ip' => $pin->ip]; + $answer = $this->answers[$request->method . ' ' . $request->url] ?? new HttpResponse(404, [], '{}'); + + return $answer instanceof Closure ? $answer($request) : $answer; + } +} diff --git a/tests/Support/StaticHostResolver.php b/tests/Support/StaticHostResolver.php new file mode 100644 index 0000000..37b96d1 --- /dev/null +++ b/tests/Support/StaticHostResolver.php @@ -0,0 +1,44 @@ + addresses. Hosts it does not know resolve to nothing. + */ +final class StaticHostResolver implements HostResolverInterface +{ + /** + * @var list + */ + public array $asked = []; + + /** + * @param array> $hosts Host => addresses. + */ + public function __construct(private array $hosts = []) + { + } + + /** + * @param string $host The host. + * @param list $addresses Its addresses. + * @return void + */ + public function add(string $host, array $addresses): void + { + $this->hosts[$host] = $addresses; + } + + /** + * @inheritDoc + */ + public function resolve(string $host): array + { + $this->asked[] = $host; + + return $this->hosts[$host] ?? []; + } +} diff --git a/tests/TestCase/Client/Http/CakeGuardedTransportTest.php b/tests/TestCase/Client/Http/CakeGuardedTransportTest.php new file mode 100644 index 0000000..bd8e057 --- /dev/null +++ b/tests/TestCase/Client/Http/CakeGuardedTransportTest.php @@ -0,0 +1,132 @@ +|null, request: \Psr\Http\Message\RequestInterface|null} + */ + private function adapter(string $body = '{"ok":true}', int $status = 200): AdapterInterface + { + return new class ($body, $status) implements AdapterInterface { + /** + * @var array|null + */ + public ?array $options = null; + + public ?RequestInterface $request = null; + + public function __construct(private string $body, private int $status) + { + } + + public function send(RequestInterface $request, array $options): array + { + $this->request = $request; + $this->options = $options; + + return [new Response( + [sprintf('HTTP/1.1 %d X', $this->status), 'Content-Type: application/json', 'Location: /next'], + $this->body, + )]; + } + }; + } + + public function testTheRequestIsPinnedWithoutProxyOrRedirects(): void + { + $adapter = $this->adapter(); + $transport = new CakeGuardedTransport($adapter); + $pin = new CheckedEndpoint('https://auth.example.com', 'auth.example.com', 443, '93.184.216.34'); + + $response = $transport->send( + new HttpRequest('POST', 'https://auth.example.com/token?x=1', ['Accept' => 'application/json'], 'a=b', 7.0), + $pin, + 2048, + ); + + $this->assertSame(200, $response->status); + $this->assertSame('{"ok":true}', $response->body); + $this->assertSame('application/json', $response->header('content-type')); + $this->assertNotNull($adapter->request); + $this->assertSame('https://auth.example.com/token?x=1', (string)$adapter->request->getUri()); + $this->assertSame('POST', $adapter->request->getMethod()); + $this->assertSame('a=b', (string)$adapter->request->getBody()); + $options = $adapter->options ?? []; + $this->assertSame(7.0, $options['timeout']); + $this->assertFalse(isset($options['proxy'])); + $curl = $options['curl']; + $this->assertSame(['auth.example.com:443:93.184.216.34'], $curl[CURLOPT_RESOLVE]); + $this->assertSame('', $curl[CURLOPT_PROXY]); + $this->assertSame('*', $curl[CURLOPT_NOPROXY]); + $this->assertFalse($curl[CURLOPT_FOLLOWLOCATION]); + $this->assertSame(2048, $curl[CURLOPT_MAXFILESIZE]); + $this->assertFalse($curl[CURLOPT_NOPROGRESS]); + $this->assertIsCallable($curl[CURLOPT_XFERINFOFUNCTION]); + $this->assertSame(1, $curl[CURLOPT_XFERINFOFUNCTION](null, 4096, 2049, 0, 0), 'past the cap aborts'); + $this->assertSame(0, $curl[CURLOPT_XFERINFOFUNCTION](null, 0, 100, 0, 0)); + if (defined('CURLOPT_PROTOCOLS_STR')) { + $this->assertSame('https', $curl[CURLOPT_PROTOCOLS_STR]); + } else { + $this->assertSame(CURLPROTO_HTTPS, $curl[CURLOPT_PROTOCOLS]); + } + } + + public function testAnIpv6PinIsBracketed(): void + { + $adapter = $this->adapter(); + $pin = new CheckedEndpoint('https://auth.example.com:8443', 'auth.example.com', 8443, '2606:2800:220:1::1'); + + (new CakeGuardedTransport($adapter))->send(new HttpRequest('GET', 'https://auth.example.com:8443/x'), $pin, 100); + + $this->assertSame(['auth.example.com:8443:[2606:2800:220:1::1]'], $adapter->options['curl'][CURLOPT_RESOLVE] ?? null); + } + + public function testAUrlOffThePinnedOriginIsRefused(): void + { + $adapter = $this->adapter(); + $pin = new CheckedEndpoint('https://auth.example.com', 'auth.example.com', 443, '93.184.216.34'); + + try { + (new CakeGuardedTransport($adapter))->send(new HttpRequest('GET', 'https://evil.example.com/x'), $pin, 100); + $this->fail('Not refused'); + } catch (BlockedUrlException) { + $this->assertNull($adapter->request); + } + } + + public function testABodyOverTheCapIsRefused(): void + { + $adapter = $this->adapter(str_repeat('x', 101)); + $pin = new CheckedEndpoint('https://auth.example.com', 'auth.example.com', 443, '93.184.216.34'); + + $this->expectException(ClientException::class); + $this->expectExceptionMessage('larger answer'); + + (new CakeGuardedTransport($adapter))->send(new HttpRequest('GET', 'https://auth.example.com/x'), $pin, 100); + } + + public function testRedirectsAreReturnedNotFollowed(): void + { + $adapter = $this->adapter('', 302); + $pin = new CheckedEndpoint('https://auth.example.com', 'auth.example.com', 443, '93.184.216.34'); + + $response = (new CakeGuardedTransport($adapter))->send(new HttpRequest('GET', 'https://auth.example.com/x'), $pin, 100); + + $this->assertSame(302, $response->status); + $this->assertSame('/next', $response->header('Location')); + } +} diff --git a/tests/TestCase/Client/Http/EndpointGuardTest.php b/tests/TestCase/Client/Http/EndpointGuardTest.php new file mode 100644 index 0000000..76fda71 --- /dev/null +++ b/tests/TestCase/Client/Http/EndpointGuardTest.php @@ -0,0 +1,129 @@ +resolver = new StaticHostResolver(['auth.example.com' => ['93.184.216.34', '2606:2800:220:1::1']]); + $this->guard = new EndpointGuard($this->resolver); + } + + public function testAPublicHostIsPinnedToItsFirstAddress(): void + { + $checked = $this->guard->check('https://Auth.Example.com./oauth/token?x=1'); + + $this->assertSame('https://auth.example.com', $checked->origin); + $this->assertSame('auth.example.com', $checked->host); + $this->assertSame(443, $checked->port); + $this->assertSame('93.184.216.34', $checked->ip); + } + + public function testThePortIsKept(): void + { + $checked = $this->guard->check('https://auth.example.com:8443/token'); + + $this->assertSame('https://auth.example.com:8443', $checked->origin); + $this->assertSame(8443, $checked->port); + } + + /** + * @return array + */ + public static function privateAddresses(): array + { + return [ + 'rfc1918 10' => ['10.0.0.1'], + 'rfc1918 192' => ['192.168.1.1'], + 'rfc1918 172' => ['172.16.0.1'], + 'loopback' => ['127.0.0.1'], + 'link local metadata' => ['169.254.169.254'], + 'shared cgnat' => ['100.64.0.1'], + 'unspecified' => ['0.0.0.0'], + 'multicast' => ['224.0.0.1'], + 'ipv6 loopback' => ['::1'], + 'ipv6 unique local' => ['fc00::1'], + 'ipv6 link local' => ['fe80::1'], + 'ipv4 mapped private' => ['::ffff:10.0.0.1'], + 'nat64 private' => ['64:ff9b::a00:1'], + '6to4 private' => ['2002:a00:1::1'], + 'documentation' => ['2001:db8::1'], + ]; + } + + #[DataProvider('privateAddresses')] + public function testAHostResolvingToAPrivateAddressIsRefused(string $address): void + { + $this->resolver->add('internal.example.com', [$address]); + + $this->expectException(BlockedUrlException::class); + $this->expectExceptionMessage('internal.example.com is not a public address'); + + $this->guard->check('https://internal.example.com/token'); + } + + public function testOnePrivateAddressAmongPublicOnesIsRefused(): void + { + $this->resolver->add('mixed.example.com', ['93.184.216.34', '10.0.0.1']); + + $this->expectException(BlockedUrlException::class); + + $this->guard->check('https://mixed.example.com/'); + } + + /** + * @return array + */ + public static function refusedUrls(): array + { + return [ + 'http' => ['http://auth.example.com/token'], + 'ip literal' => ['https://93.184.216.34/token'], + 'ipv6 literal' => ['https://[2606:2800:220:1::1]/token'], + 'decimal ip' => ['https://2130706433/token'], + 'short ip' => ['https://127.1/token'], + 'hex ip' => ['https://0x7f000001/token'], + 'single label' => ['https://intranet/token'], + 'userinfo' => ['https://user:pass@auth.example.com/token'], + 'fragment' => ['https://auth.example.com/token#x'], + 'not resolving' => ['https://nowhere.example.com/token'], + 'no host' => ['https:///token'], + 'port zero' => ['https://auth.example.com:0/token'], + 'other scheme' => ['file:///etc/passwd'], + 'spaces' => ['https://auth.example.com/to ken'], + ]; + } + + #[DataProvider('refusedUrls')] + public function testRefusedUrls(string $url): void + { + $this->expectException(BlockedUrlException::class); + + $this->guard->check($url); + } + + public function testTheMessageNamesOnlyTheHost(): void + { + $this->resolver->add('internal.example.com', ['10.0.0.1']); + try { + $this->guard->check('https://internal.example.com/token?secret=abc'); + $this->fail('Not refused'); + } catch (BlockedUrlException $e) { + $this->assertStringNotContainsString('secret', $e->getMessage()); + $this->assertStringNotContainsString('10.0.0.1', $e->getMessage()); + } + } +} diff --git a/tests/TestCase/Client/Http/GuardedHttpTest.php b/tests/TestCase/Client/Http/GuardedHttpTest.php new file mode 100644 index 0000000..9250403 --- /dev/null +++ b/tests/TestCase/Client/Http/GuardedHttpTest.php @@ -0,0 +1,115 @@ + ['93.184.216.34'], + 'other.example.com' => ['93.184.216.35'], + 'internal.example.com' => ['10.0.0.1'], + ]); + $this->transport = new ScriptedGuardedTransport(); + $this->http = new GuardedHttp(new EndpointGuard($resolver), $this->transport, 4096); + } + + private static function redirect(string $location, int $status = 302): HttpResponse + { + return new HttpResponse($status, ['Location' => [$location]], ''); + } + + public function testGetSendsTheExactUrlToThePinnedAddress(): void + { + $this->transport->json('https://auth.example.com/.well-known/x?resource=a%20b', ['ok' => true]); + + $response = $this->http->get('https://auth.example.com/.well-known/x?resource=a%20b', 5.0); + + $this->assertSame(['ok' => true], $response->json()); + $this->assertSame('93.184.216.34', $this->transport->sent[0]['ip']); + $this->assertSame(5.0, $this->transport->sent[0]['request']->timeout); + } + + public function testGetFollowsRedirectsCheckingEachHop(): void + { + $this->transport->on('GET', 'https://auth.example.com/a', self::redirect('/b')); + $this->transport->on('GET', 'https://auth.example.com/b', self::redirect('https://other.example.com/c', 301)); + $this->transport->json('https://other.example.com/c', ['ok' => 1]); + + $response = $this->http->get('https://auth.example.com/a', 5.0); + + $this->assertSame(['ok' => 1], $response->json()); + $this->assertSame('93.184.216.35', $this->transport->sent[2]['ip']); + } + + public function testARedirectToAPrivateHostIsRefusedBeforeItIsSent(): void + { + $this->transport->on('GET', 'https://auth.example.com/a', self::redirect('https://internal.example.com/meta')); + + try { + $this->http->get('https://auth.example.com/a', 5.0); + $this->fail('Not refused'); + } catch (BlockedUrlException) { + $this->assertSame(['GET https://auth.example.com/a'], $this->transport->urls()); + } + } + + public function testARedirectToHttpIsRefused(): void + { + $this->transport->on('GET', 'https://auth.example.com/a', self::redirect('http://auth.example.com/a')); + + $this->expectException(BlockedUrlException::class); + + $this->http->get('https://auth.example.com/a', 5.0); + } + + public function testTooManyRedirectsAreRefused(): void + { + foreach (['a' => 'b', 'b' => 'c', 'c' => 'd', 'd' => 'e'] as $from => $to) { + $this->transport->on('GET', 'https://auth.example.com/' . $from, self::redirect('/' . $to)); + } + + $this->expectException(BlockedUrlException::class); + $this->expectExceptionMessage('redirected too many times'); + + $this->http->get('https://auth.example.com/a', 5.0); + } + + public function testSendRefusesARedirect(): void + { + $this->transport->on('POST', 'https://auth.example.com/token', self::redirect('https://other.example.com/token')); + + try { + $this->http->send(new HttpRequest('POST', 'https://auth.example.com/token', [], 'code=abc')); + $this->fail('Not refused'); + } catch (BlockedUrlException) { + $this->assertSame(['POST https://auth.example.com/token'], $this->transport->urls()); + } + } + + public function testSendToAPrivateHostIsNeverSent(): void + { + try { + $this->http->send(new HttpRequest('POST', 'https://internal.example.com/token', [], 'code=abc')); + $this->fail('Not refused'); + } catch (BlockedUrlException) { + $this->assertSame([], $this->transport->sent); + } + } +} diff --git a/tests/TestCase/Client/Http/OutboundHttpTest.php b/tests/TestCase/Client/Http/OutboundHttpTest.php new file mode 100644 index 0000000..77f7c0d --- /dev/null +++ b/tests/TestCase/Client/Http/OutboundHttpTest.php @@ -0,0 +1,141 @@ +, answers: array} + */ + private ClientInterface $trusted; + + private OutboundHttp $http; + + protected function setUp(): void + { + parent::setUp(); + $this->guarded = new ScriptedGuardedTransport(); + $this->trusted = new class implements ClientInterface { + /** + * @var list<\Psr\Http\Message\RequestInterface> + */ + public array $sent = []; + + /** + * @var array + */ + public array $answers = []; + + public function sendRequest(RequestInterface $request): ResponseInterface + { + $this->sent[] = $request; + + return $this->answers[(string)$request->getUri()] ?? new Response(['HTTP/1.1 404 Not Found'], ''); + } + }; + $resolver = new StaticHostResolver([ + 'auth.example.com' => ['93.184.216.34'], + 'internal.example.com' => ['10.0.0.1'], + ]); + $this->http = new OutboundHttp(new GuardedHttp(new EndpointGuard($resolver), $this->guarded, 4096), $this->trusted); + } + + public function testTrustedRequestsUseTheConfiguredClient(): void + { + $this->trusted->answers['http://localhost:8765/.well-known/oauth-protected-resource'] = new Response( + ['HTTP/1.1 200 OK', 'Content-Type: application/json'], + '{"resource":"x"}', + ); + + $response = $this->http->get('http://localhost:8765/.well-known/oauth-protected-resource', true, 5.0); + + $this->assertSame(['resource' => 'x'], $response->json()); + $this->assertSame([], $this->guarded->sent); + $this->assertSame('application/json', $this->trusted->sent[0]->getHeaderLine('Accept')); + } + + public function testTrustedSendCarriesHeadersAndBody(): void + { + $this->trusted->answers['https://sso.internal/token'] = new Response(['HTTP/1.1 200 OK'], '{"access_token":"a"}'); + + $response = $this->http->send(new HttpRequest( + 'POST', + 'https://sso.internal/token', + ['Content-Type' => 'application/x-www-form-urlencoded'], + 'grant_type=x', + ), true); + + $this->assertSame(200, $response->status); + $this->assertSame('POST', $this->trusted->sent[0]->getMethod()); + $this->assertSame('grant_type=x', (string)$this->trusted->sent[0]->getBody()); + $this->assertSame('application/x-www-form-urlencoded', $this->trusted->sent[0]->getHeaderLine('Content-Type')); + } + + public function testUntrustedRequestsGoThroughTheGuard(): void + { + $this->guarded->json('https://auth.example.com/meta', ['ok' => true]); + + $this->assertSame(['ok' => true], $this->http->get('https://auth.example.com/meta', false, 5.0)->json()); + $this->assertSame([], $this->trusted->sent); + + $this->expectException(BlockedUrlException::class); + $this->http->get('https://internal.example.com/meta', false, 5.0); + } + + public function testATrustedRedirectToAPrivateHostIsRefused(): void + { + $this->trusted->answers['http://localhost:8765/meta'] = new Response( + ['HTTP/1.1 302 Found', 'Location: https://internal.example.com/meta'], + '', + ); + + try { + $this->http->get('http://localhost:8765/meta', true, 5.0); + $this->fail('Not refused'); + } catch (BlockedUrlException) { + $this->assertSame([], $this->guarded->sent); + } + } + + public function testATrustedRedirectToAPublicHostContinuesThroughTheGuard(): void + { + $this->trusted->answers['http://localhost:8765/meta'] = new Response( + ['HTTP/1.1 302 Found', 'Location: https://auth.example.com/meta'], + '', + ); + $this->guarded->json('https://auth.example.com/meta', ['ok' => 2]); + + $this->assertSame(['ok' => 2], $this->http->get('http://localhost:8765/meta', true, 5.0)->json()); + } + + public function testATrustedSendNeverFollowsARedirect(): void + { + $this->trusted->answers['https://sso.internal/token'] = new Response( + ['HTTP/1.1 307 Temporary Redirect', 'Location: https://auth.example.com/token'], + '', + ); + + try { + $this->http->send(new HttpRequest('POST', 'https://sso.internal/token', [], 'code=1'), true); + $this->fail('Not refused'); + } catch (BlockedUrlException) { + $this->assertSame([], $this->guarded->sent); + } + } +} From 2ba4f4ca8c1dc0c221fb0cfd2f668ccee10aad3a Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 21:28:28 +0100 Subject: [PATCH 039/181] MCP client: encrypted token store and its migration --- .../20261120120000_CreateMcpClientTables.php | 67 ++++++ src/Client/ClientConfig.php | 3 + src/Client/Store/ConnectionStoreInterface.php | 56 +++++ src/Client/Store/Registration.php | 29 +++ src/Client/Store/StoredConnection.php | 79 +++++++ src/Client/Store/TableConnectionStore.php | 215 ++++++++++++++++++ src/Model/Table/McpClientConnectionsTable.php | 25 ++ .../Table/McpClientRegistrationsTable.php | 25 ++ tests/TestCase/Client/ClientConfigTest.php | 3 + .../Client/Store/TableConnectionStoreTest.php | 134 +++++++++++ tests/bootstrap_suite.php | 5 +- 11 files changed, 640 insertions(+), 1 deletion(-) create mode 100644 config/Migrations/20261120120000_CreateMcpClientTables.php create mode 100644 src/Client/Store/ConnectionStoreInterface.php create mode 100644 src/Client/Store/Registration.php create mode 100644 src/Client/Store/StoredConnection.php create mode 100644 src/Client/Store/TableConnectionStore.php create mode 100644 src/Model/Table/McpClientConnectionsTable.php create mode 100644 src/Model/Table/McpClientRegistrationsTable.php create mode 100644 tests/TestCase/Client/Store/TableConnectionStoreTest.php diff --git a/config/Migrations/20261120120000_CreateMcpClientTables.php b/config/Migrations/20261120120000_CreateMcpClientTables.php new file mode 100644 index 0000000..250919c --- /dev/null +++ b/config/Migrations/20261120120000_CreateMcpClientTables.php @@ -0,0 +1,67 @@ +table('mcp_client_connections') + ->addColumn('client', 'string', ['limit' => 100, 'null' => false]) + ->addColumn('user_id', 'string', ['limit' => 191, 'null' => false]) + ->addColumn('access_token', 'text', ['null' => false]) + ->addColumn('refresh_token', 'text', ['null' => true]) + ->addColumn('expires', 'datetime', ['null' => true]) + ->addColumn('scope', 'text', ['null' => true]) + ->addColumn('issuer', 'text', ['null' => false]) + ->addColumn('token_url', 'text', ['null' => false]) + ->addColumn('revocation_url', 'text', ['null' => true]) + ->addColumn('oauth_client_id', 'text', ['null' => false]) + ->addColumn('client_secret', 'text', ['null' => true]) + ->addColumn('auth_method', 'string', ['limit' => 30, 'null' => false]) + ->addColumn('resource', 'text', ['null' => false]) + ->addColumn('created', 'datetime', ['null' => false]) + ->addColumn('modified', 'datetime', ['null' => false]) + ->addIndex(['client', 'user_id'], ['unique' => true]) + ->create(); + + $this->table('mcp_client_registrations') + ->addColumn('client', 'string', ['limit' => 100, 'null' => false]) + ->addColumn('issuer', 'string', ['limit' => 255, 'null' => false]) + ->addColumn('redirect_uri', 'text', ['null' => false]) + ->addColumn('oauth_client_id', 'text', ['null' => false]) + ->addColumn('client_secret', 'text', ['null' => true]) + ->addColumn('auth_method', 'string', ['limit' => 30, 'null' => false]) + ->addColumn('created', 'datetime', ['null' => false]) + ->addColumn('modified', 'datetime', ['null' => false]) + ->addIndex(['client', 'issuer'], ['unique' => true]) + ->create(); + } + + /** + * @return void + */ + public function down(): void + { + $this->table('mcp_client_registrations')->drop()->save(); + $this->table('mcp_client_connections')->drop()->save(); + } +} diff --git a/src/Client/ClientConfig.php b/src/Client/ClientConfig.php index c5c813e..107e797 100644 --- a/src/Client/ClientConfig.php +++ b/src/Client/ClientConfig.php @@ -4,6 +4,7 @@ namespace CakeDC\Mcp\Client; use Cake\Core\Configure; +use CakeDC\Mcp\Client\Store\TableConnectionStore; use InvalidArgumentException; use Mcp\Schema\Enum\ProtocolVersion; @@ -30,6 +31,8 @@ final class ClientConfig */ public const SETTINGS = [ 'route' => '/mcp-client', + 'store' => TableConnectionStore::class, + 'encryptionKey' => null, 'name' => 'CakePHP MCP Client', 'version' => '1.0.0', 'refreshLeeway' => 60, diff --git a/src/Client/Store/ConnectionStoreInterface.php b/src/Client/Store/ConnectionStoreInterface.php new file mode 100644 index 0000000..4bc9b0e --- /dev/null +++ b/src/Client/Store/ConnectionStoreInterface.php @@ -0,0 +1,56 @@ +client, + $this->userId, + $accessToken, + $refreshToken, + $expiresAt, + $scope, + $this->issuer, + $this->tokenUrl, + $this->revocationUrl, + $this->clientId, + $this->clientSecret, + $this->authMethod, + $this->resource, + ); + } + + /** + * @param int $seconds A margin. + * @param int $now The time now (Unix time). + * @return bool Whether the access token expires within $seconds of $now; false when its expiry is unknown. + */ + public function expiresWithin(int $seconds, int $now): bool + { + return $this->expiresAt !== null && $this->expiresAt - $now <= $seconds; + } +} diff --git a/src/Client/Store/TableConnectionStore.php b/src/Client/Store/TableConnectionStore.php new file mode 100644 index 0000000..860c943 --- /dev/null +++ b/src/Client/Store/TableConnectionStore.php @@ -0,0 +1,215 @@ +key = is_string($key) && $key !== '' ? $key : Security::getSalt(); + if (strlen($this->key) < 32) { + throw new InvalidArgumentException( + 'The MCP client token store needs a key of at least 32 bytes: set "Mcp.client.encryptionKey" or a ' + . 'longer Security.salt.', + ); + } + } + + /** + * @inheritDoc + */ + public function get(string $client, string $userId): ?StoredConnection + { + $row = $this->connections()->find()->where(['client' => $client, 'user_id' => $userId])->first(); + if (!$row instanceof EntityInterface) { + return null; + } + $access = $this->decrypt($row->get('access_token')); + $refresh = $this->decrypt($row->get('refresh_token')); + $secret = $this->decrypt($row->get('client_secret')); + if ( + $access === null + || ($row->get('refresh_token') !== null && $refresh === null) + || ($row->get('client_secret') !== null && $secret === null) + ) { + return null; + } + $expires = $row->get('expires'); + + return new StoredConnection( + $client, + $userId, + $access, + $refresh, + $expires instanceof DateTime ? $expires->getTimestamp() : null, + self::nullableString($row->get('scope')), + (string)$row->get('issuer'), + (string)$row->get('token_url'), + self::nullableString($row->get('revocation_url')), + (string)$row->get('oauth_client_id'), + $secret, + (string)$row->get('auth_method'), + (string)$row->get('resource'), + ); + } + + /** + * @inheritDoc + */ + public function save(StoredConnection $connection): void + { + $table = $this->connections(); + $row = $table->find()->where(['client' => $connection->client, 'user_id' => $connection->userId])->first(); + $data = [ + 'client' => $connection->client, + 'user_id' => $connection->userId, + 'access_token' => $this->encrypt($connection->accessToken), + 'refresh_token' => $this->encrypt($connection->refreshToken), + 'expires' => $connection->expiresAt === null ? null : DateTime::createFromTimestamp($connection->expiresAt), + 'scope' => $connection->scope, + 'issuer' => $connection->issuer, + 'token_url' => $connection->tokenUrl, + 'revocation_url' => $connection->revocationUrl, + 'oauth_client_id' => $connection->clientId, + 'client_secret' => $this->encrypt($connection->clientSecret), + 'auth_method' => $connection->authMethod, + 'resource' => $connection->resource, + ]; + $entity = $row instanceof EntityInterface + ? $table->patchEntity($row, $data, ['validate' => false]) + : $table->newEntity($data, ['validate' => false]); + $table->saveOrFail($entity); + } + + /** + * @inheritDoc + */ + public function delete(string $client, string $userId): void + { + $this->connections()->deleteAll(['client' => $client, 'user_id' => $userId]); + } + + /** + * @inheritDoc + */ + public function registration(string $client, string $issuer): ?Registration + { + $row = $this->registrations()->find()->where(['client' => $client, 'issuer' => $issuer])->first(); + if (!$row instanceof EntityInterface) { + return null; + } + $secret = $this->decrypt($row->get('client_secret')); + if ($row->get('client_secret') !== null && $secret === null) { + return null; + } + + return new Registration( + $client, + $issuer, + (string)$row->get('redirect_uri'), + (string)$row->get('oauth_client_id'), + $secret, + (string)$row->get('auth_method'), + ); + } + + /** + * @inheritDoc + */ + public function saveRegistration(Registration $registration): void + { + $table = $this->registrations(); + $row = $table->find()->where(['client' => $registration->client, 'issuer' => $registration->issuer])->first(); + $data = [ + 'client' => $registration->client, + 'issuer' => $registration->issuer, + 'redirect_uri' => $registration->redirectUri, + 'oauth_client_id' => $registration->clientId, + 'client_secret' => $this->encrypt($registration->clientSecret), + 'auth_method' => $registration->authMethod, + ]; + $entity = $row instanceof EntityInterface + ? $table->patchEntity($row, $data, ['validate' => false]) + : $table->newEntity($data, ['validate' => false]); + $table->saveOrFail($entity); + } + + /** + * @inheritDoc + */ + public function deleteRegistration(string $client, string $issuer): void + { + $this->registrations()->deleteAll(['client' => $client, 'issuer' => $issuer]); + } + + /** + * @return \Cake\ORM\Table + */ + protected function connections(): Table + { + return $this->fetchTable('CakeDC/Mcp.McpClientConnections'); + } + + /** + * @return \Cake\ORM\Table + */ + protected function registrations(): Table + { + return $this->fetchTable('CakeDC/Mcp.McpClientRegistrations'); + } + + /** + * @param string|null $plain A secret. + * @return string|null It encrypted and base64 encoded. + */ + private function encrypt(?string $plain): ?string + { + return $plain === null ? null : base64_encode(Security::encrypt($plain, $this->key)); + } + + /** + * @param mixed $stored A stored value. + * @return string|null The secret, or null when there is none or it does not decrypt. + */ + private function decrypt(mixed $stored): ?string + { + if (!is_string($stored) || $stored === '') { + return null; + } + $binary = base64_decode($stored, true); + + return $binary === false ? null : Security::decrypt($binary, $this->key); + } + + /** + * @param mixed $value A column value. + * @return string|null + */ + private static function nullableString(mixed $value): ?string + { + return is_string($value) && $value !== '' ? $value : null; + } +} diff --git a/src/Model/Table/McpClientConnectionsTable.php b/src/Model/Table/McpClientConnectionsTable.php new file mode 100644 index 0000000..ca5726f --- /dev/null +++ b/src/Model/Table/McpClientConnectionsTable.php @@ -0,0 +1,25 @@ + $config The config. + * @return void + */ + public function initialize(array $config): void + { + parent::initialize($config); + $this->setTable('mcp_client_connections'); + $this->setPrimaryKey('id'); + $this->addBehavior('Timestamp'); + } +} diff --git a/src/Model/Table/McpClientRegistrationsTable.php b/src/Model/Table/McpClientRegistrationsTable.php new file mode 100644 index 0000000..9511dce --- /dev/null +++ b/src/Model/Table/McpClientRegistrationsTable.php @@ -0,0 +1,25 @@ + $config The config. + * @return void + */ + public function initialize(array $config): void + { + parent::initialize($config); + $this->setTable('mcp_client_registrations'); + $this->setPrimaryKey('id'); + $this->addBehavior('Timestamp'); + } +} diff --git a/tests/TestCase/Client/ClientConfigTest.php b/tests/TestCase/Client/ClientConfigTest.php index 386f953..e9e820e 100644 --- a/tests/TestCase/Client/ClientConfigTest.php +++ b/tests/TestCase/Client/ClientConfigTest.php @@ -6,6 +6,7 @@ use Cake\Core\Configure; use Cake\TestSuite\TestCase; use CakeDC\Mcp\Client\ClientConfig; +use CakeDC\Mcp\Client\Store\TableConnectionStore; use InvalidArgumentException; use Mcp\Schema\Enum\ProtocolVersion; @@ -173,6 +174,8 @@ public function testSettingsHaveDefaults(): void { Configure::delete('Mcp.client'); $this->assertSame('/mcp-client', ClientConfig::setting('route')); + $this->assertSame(TableConnectionStore::class, ClientConfig::setting('store')); + $this->assertNull(ClientConfig::setting('encryptionKey')); $this->assertSame(60, ClientConfig::setting('refreshLeeway')); $this->assertSame(1024 * 1024, ClientConfig::setting('maxResponseBytes')); diff --git a/tests/TestCase/Client/Store/TableConnectionStoreTest.php b/tests/TestCase/Client/Store/TableConnectionStoreTest.php new file mode 100644 index 0000000..6bda650 --- /dev/null +++ b/tests/TestCase/Client/Store/TableConnectionStoreTest.php @@ -0,0 +1,134 @@ +store = new TableConnectionStore(); + $db = ConnectionManager::get('test'); + $db->execute('DELETE FROM mcp_client_connections'); + $db->execute('DELETE FROM mcp_client_registrations'); + } + + private static function connection(string $userId = '7', string $access = 'access-abc'): StoredConnection + { + return new StoredConnection( + client: 'linear', + userId: $userId, + accessToken: $access, + refreshToken: 'refresh-def', + expiresAt: 1_900_000_000, + scope: 'read write', + issuer: 'https://auth.example.com', + tokenUrl: 'https://auth.example.com/token', + revocationUrl: 'https://auth.example.com/revoke', + clientId: 'client-1', + clientSecret: 'client-secret-ghi', + authMethod: 'client_secret_basic', + resource: 'https://mcp.example.com/mcp', + ); + } + + public function testSavesAndReadsAConnection(): void + { + $this->store->save(self::connection()); + + $this->assertEquals(self::connection(), $this->store->get('linear', '7')); + $this->assertNull($this->store->get('linear', '8')); + $this->assertNull($this->store->get('github', '7')); + } + + public function testSecretsAreEncryptedAtRest(): void + { + $this->store->save(self::connection()); + $this->store->saveRegistration(new Registration( + 'linear', + 'https://auth.example.com', + 'https://app.example.com/cb', + 'client-1', + 'registration-secret-jkl', + 'client_secret_post', + )); + + $db = ConnectionManager::get('test'); + $rows = json_encode([ + $db->execute('SELECT * FROM mcp_client_connections')->fetchAll('assoc'), + $db->execute('SELECT * FROM mcp_client_registrations')->fetchAll('assoc'), + ]); + foreach (['access-abc', 'refresh-def', 'client-secret-ghi', 'registration-secret-jkl'] as $secret) { + $this->assertStringNotContainsString($secret, (string)$rows); + } + $this->assertStringContainsString('client-1', (string)$rows); + } + + public function testSaveReplacesTheUsersConnection(): void + { + $this->store->save(self::connection()); + $this->store->save(self::connection('7', 'access-new')->withTokens('access-new', null, null, null)); + + $stored = $this->store->get('linear', '7'); + $this->assertNotNull($stored); + $this->assertSame('access-new', $stored->accessToken); + $this->assertNull($stored->refreshToken); + $this->assertNull($stored->expiresAt); + $this->assertSame(1, ConnectionManager::get('test') + ->execute('SELECT COUNT(*) AS n FROM mcp_client_connections')->fetch('assoc')['n'] ?? null); + } + + public function testDeleteRemovesOnlyThatUser(): void + { + $this->store->save(self::connection('7')); + $this->store->save(self::connection('8')); + + $this->store->delete('linear', '7'); + + $this->assertNull($this->store->get('linear', '7')); + $this->assertNotNull($this->store->get('linear', '8')); + } + + public function testRegistrationsRoundTrip(): void + { + $registration = new Registration('linear', 'https://auth.example.com', 'https://app/cb', 'c-1', null, 'none'); + $this->store->saveRegistration($registration); + + $this->assertEquals($registration, $this->store->registration('linear', 'https://auth.example.com')); + $this->assertNull($this->store->registration('linear', 'https://other.example.com')); + + $replaced = new Registration('linear', 'https://auth.example.com', 'https://app/cb', 'c-2', 's', 'client_secret_basic'); + $this->store->saveRegistration($replaced); + $this->assertEquals($replaced, $this->store->registration('linear', 'https://auth.example.com')); + + $this->store->deleteRegistration('linear', 'https://auth.example.com'); + $this->assertNull($this->store->registration('linear', 'https://auth.example.com')); + } + + public function testAnotherKeyCannotReadTheTokens(): void + { + $this->store->save(self::connection()); + + $other = new TableConnectionStore(str_repeat('another-key-', 4)); + + $this->assertNull($other->get('linear', '7')); + } + + public function testExpiresWithin(): void + { + $connection = self::connection(); + + $this->assertFalse($connection->expiresWithin(60, 1_900_000_000 - 61)); + $this->assertTrue($connection->expiresWithin(60, 1_900_000_000 - 60)); + $this->assertFalse($connection->withTokens('a', null, null, null)->expiresWithin(60, 2_000_000_000)); + } +} diff --git a/tests/bootstrap_suite.php b/tests/bootstrap_suite.php index 1408b66..cb77df9 100644 --- a/tests/bootstrap_suite.php +++ b/tests/bootstrap_suite.php @@ -9,6 +9,7 @@ use Cake\Core\Configure; use Cake\Core\Plugin; use Cake\Datasource\ConnectionManager; +use CakeDC\Mcp\McpPlugin; use CakeDC\OAuthServer\OAuthServerPlugin; use Migrations\TestSuite\Migrator; use TestApp\OAuthTestConfig; @@ -34,4 +35,6 @@ Configure::write('OAuthServer', OAuthTestConfig::SERVER); Plugin::getCollection()->add(new OAuthServerPlugin()); -(new Migrator())->runMany([['plugin' => 'CakeDC/OAuthServer'], []]); +// The MCP client's user mode tables (config/Migrations of this plugin). +Plugin::getCollection()->add(new McpPlugin()); +(new Migrator())->runMany([['plugin' => 'CakeDC/OAuthServer'], ['plugin' => 'CakeDC/Mcp'], []]); From 910b598ea94ee270dbdb79f7a0444022dd83edb2 Mon Sep 17 00:00:00 2001 From: Alejandro Ibarra Date: Fri, 20 Nov 2026 21:38:02 +0100 Subject: [PATCH 040/181] MCP client: OAuth sign-in for user mode clients --- src/Client/ClientRegistry.php | 96 +++- src/Client/Http/GuardedHttp.php | 12 + src/Client/Http/OutboundHttp.php | 12 + src/Client/OAuth/AuthServer.php | 36 ++ src/Client/OAuth/Discovery.php | 431 ++++++++++++++++++ src/Client/OAuth/OAuthException.php | 31 ++ src/Client/OAuth/OAuthFlow.php | 184 ++++++++ src/Client/OAuth/PendingAuthorization.php | 106 +++++ src/Client/OAuth/Registrar.php | 141 ++++++ src/Client/OAuth/TokenClient.php | 221 +++++++++ src/Client/OAuth/TokenSet.php | 24 + src/Client/UserId.php | 38 ++ src/Controller/McpClientController.php | 197 ++++++++ src/McpConfig.php | 17 +- src/McpPlugin.php | 12 + tests/Support/FakeOAuthServer.php | 182 ++++++++ tests/Support/SdkServerHttpClient.php | 25 +- tests/TestCase/Client/OAuth/DiscoveryTest.php | 198 ++++++++ tests/TestCase/Client/OAuth/OAuthFlowTest.php | 196 ++++++++ tests/TestCase/Client/OAuth/RegistrarTest.php | 109 +++++ tests/TestCase/Client/UserIdTest.php | 41 ++ .../Controller/McpClientControllerTest.php | 207 +++++++++ 22 files changed, 2512 insertions(+), 4 deletions(-) create mode 100644 src/Client/OAuth/AuthServer.php create mode 100644 src/Client/OAuth/Discovery.php create mode 100644 src/Client/OAuth/OAuthException.php create mode 100644 src/Client/OAuth/OAuthFlow.php create mode 100644 src/Client/OAuth/PendingAuthorization.php create mode 100644 src/Client/OAuth/Registrar.php create mode 100644 src/Client/OAuth/TokenClient.php create mode 100644 src/Client/OAuth/TokenSet.php create mode 100644 src/Client/UserId.php create mode 100644 src/Controller/McpClientController.php create mode 100644 tests/Support/FakeOAuthServer.php create mode 100644 tests/TestCase/Client/OAuth/DiscoveryTest.php create mode 100644 tests/TestCase/Client/OAuth/OAuthFlowTest.php create mode 100644 tests/TestCase/Client/OAuth/RegistrarTest.php create mode 100644 tests/TestCase/Client/UserIdTest.php create mode 100644 tests/TestCase/Controller/McpClientControllerTest.php diff --git a/src/Client/ClientRegistry.php b/src/Client/ClientRegistry.php index d37c873..a882047 100644 --- a/src/Client/ClientRegistry.php +++ b/src/Client/ClientRegistry.php @@ -3,6 +3,19 @@ namespace CakeDC\Mcp\Client; +use CakeDC\Mcp\Client\Http\CakeGuardedTransport; +use CakeDC\Mcp\Client\Http\DnsHostResolver; +use CakeDC\Mcp\Client\Http\EndpointGuard; +use CakeDC\Mcp\Client\Http\GuardedHttp; +use CakeDC\Mcp\Client\Http\OutboundHttp; +use CakeDC\Mcp\Client\OAuth\Discovery; +use CakeDC\Mcp\Client\OAuth\OAuthFlow; +use CakeDC\Mcp\Client\OAuth\Registrar; +use CakeDC\Mcp\Client\OAuth\TokenClient; +use CakeDC\Mcp\Client\Store\ConnectionStoreInterface; +use InvalidArgumentException; +use LogicException; + /** * Builds the named clients and holds what they share: the HTTP client factory, the token store and the guarded HTTP * layer. McpClients uses one for the whole process; tests give it doubles. @@ -17,9 +30,16 @@ class ClientRegistry /** * @param \CakeDC\Mcp\Client\HttpClientFactoryInterface|null $http The PSR-18 client for configured URLs; Cake's * HTTP client by default. + * @param \CakeDC\Mcp\Client\Store\ConnectionStoreInterface|null $store The token store; `Mcp.client.store` by + * default, built on first use (only user mode needs it). + * @param \CakeDC\Mcp\Client\Http\GuardedHttp|null $guarded The layer for URLs learned from remote servers; the + * server's DNS and Cake's Curl adapter by default. */ - public function __construct(private ?HttpClientFactoryInterface $http = null) - { + public function __construct( + private ?HttpClientFactoryInterface $http = null, + private ?ConnectionStoreInterface $store = null, + private ?GuardedHttp $guarded = null, + ) { } /** @@ -40,6 +60,78 @@ public function http(): HttpClientFactoryInterface return $this->http ??= new CakeHttpClientFactory(); } + /** + * @return \CakeDC\Mcp\Client\Store\ConnectionStoreInterface + * @throws \InvalidArgumentException When `Mcp.client.store` is not a store class. + */ + public function store(): ConnectionStoreInterface + { + if ($this->store === null) { + $class = ClientConfig::setting('store'); + if (!is_string($class) || !is_subclass_of($class, ConnectionStoreInterface::class)) { + throw new InvalidArgumentException(sprintf( + '"Mcp.client.store" must be the name of a class implementing %s.', + ConnectionStoreInterface::class, + )); + } + $this->store = new $class(); + } + + return $this->store; + } + + /** + * @return \CakeDC\Mcp\Client\Http\GuardedHttp + */ + public function guarded(): GuardedHttp + { + return $this->guarded ??= new GuardedHttp( + new EndpointGuard(new DnsHostResolver()), + new CakeGuardedTransport(), + (int)ClientConfig::setting('maxResponseBytes'), + ); + } + + /** + * @param \CakeDC\Mcp\Client\ClientConfig $config A client. + * @return \CakeDC\Mcp\Client\Http\OutboundHttp Its OAuth requests, at the trust level of each URL. + */ + public function outbound(ClientConfig $config): OutboundHttp + { + return new OutboundHttp($this->guarded(), $this->http()->create($config)); + } + + /** + * @param \CakeDC\Mcp\Client\ClientConfig $config A user mode client. + * @return \CakeDC\Mcp\Client\OAuth\TokenClient + */ + public function tokens(ClientConfig $config): TokenClient + { + return new TokenClient($this->outbound($config), $config->timeout); + } + + /** + * @param string $name A user mode client of `Mcp.clients`. + * @return \CakeDC\Mcp\Client\OAuth\OAuthFlow Its sign-in. + * @throws \LogicException When it is not a user mode client. + */ + public function flow(string $name): OAuthFlow + { + $config = $this->get($name)->config(); + if (!$config->isUser()) { + throw new LogicException(sprintf('"Mcp.clients.%s" is not a user mode client.', $name)); + } + $outbound = $this->outbound($config); + + return new OAuthFlow( + $config, + new Discovery($outbound, $config), + new Registrar($outbound, $this->store(), $config), + new TokenClient($outbound, $config->timeout), + $this->store(), + ); + } + /** * Closes every client's connection. * diff --git a/src/Client/Http/GuardedHttp.php b/src/Client/Http/GuardedHttp.php index 0e65fcb..8006553 100644 --- a/src/Client/Http/GuardedHttp.php +++ b/src/Client/Http/GuardedHttp.php @@ -60,6 +60,18 @@ public function get(string $url, float $timeout): HttpResponse } } + /** + * Checks a learned URL without sending anything, so a bad endpoint fails as soon as it is read. + * + * @param string $url An absolute URL. + * @return void + * @throws \CakeDC\Mcp\Client\Http\BlockedUrlException + */ + public function check(string $url): void + { + $this->guard->check($url); + } + /** * A request that may carry credentials. Never follows a redirect. * diff --git a/src/Client/Http/OutboundHttp.php b/src/Client/Http/OutboundHttp.php index 2f31f6c..45b8784 100644 --- a/src/Client/Http/OutboundHttp.php +++ b/src/Client/Http/OutboundHttp.php @@ -46,6 +46,18 @@ public function get(string $url, bool $trusted, float $timeout): HttpResponse return $response; } + /** + * Checks a learned URL with the guard, without sending anything. + * + * @param string $url An absolute URL. + * @return void + * @throws \CakeDC\Mcp\Client\Http\BlockedUrlException + */ + public function check(string $url): void + { + $this->guarded->check($url); + } + /** * A request that may carry credentials; a redirect is refused. * diff --git a/src/Client/OAuth/AuthServer.php b/src/Client/OAuth/AuthServer.php new file mode 100644 index 0000000..c2cac19 --- /dev/null +++ b/src/Client/OAuth/AuthServer.php @@ -0,0 +1,36 @@ + $scopes The scopes to ask for. + * @param string $resource The MCP server, as the `resource` parameter (RFC 8707). + * @param bool $issParameter Whether the authorization response carries `iss` (RFC 9207). + * @param list $authMethods `token_endpoint_auth_methods_supported`. + * @param bool $trusted Whether the endpoints come from the config (then not through the guard). + */ + public function __construct( + public readonly string $issuer, + public readonly string $authorizationUrl, + public readonly string $tokenUrl, + public readonly ?string $registrationUrl, + public readonly ?string $revocationUrl, + public readonly array $scopes, + public readonly string $resource, + public readonly bool $issParameter, + public readonly array $authMethods, + public readonly bool $trusted, + ) { + } +} diff --git a/src/Client/OAuth/Discovery.php b/src/Client/OAuth/Discovery.php new file mode 100644 index 0000000..a38df5d --- /dev/null +++ b/src/Client/OAuth/Discovery.php @@ -0,0 +1,431 @@ +config; + $server = (string)$config->url; + if ($config->hasConfiguredEndpoints()) { + $parts = (array)parse_url((string)$config->tokenUrl); + + return new AuthServer( + (string)($parts['scheme'] ?? 'https') . '://' . ($parts['host'] ?? '') + . (isset($parts['port']) ? ':' . $parts['port'] : ''), + (string)$config->authorizationUrl, + (string)$config->tokenUrl, + null, + $config->revocationUrl, + $config->scopes, + $server, + false, + [], + true, + ); + } + + $challenge = $this->probe($server); + $metadataUrl = $challenge['resource_metadata'] ?? null; + if ($metadataUrl !== null) { + // Named by the server: learned, so through the guard, and its resource must be this server exactly. + $resourceMetadata = $this->firstDocument([self::httpsUrl($metadataUrl)], false); + $prefixAllowed = false; + } else { + $resourceMetadata = $this->firstDocument(self::protectedResourceUrls($server), true); + $prefixAllowed = true; + } + if ($resourceMetadata === null) { + throw new OAuthException( + sprintf('The server of "%s" does not publish how to sign in to it.', $config->name), + ); + } + $resource = $resourceMetadata['resource'] ?? null; + if (!is_string($resource) || $resource === '') { + throw self::unusable($config->name); + } + if (!self::resourceMatches($resource, $server, $prefixAllowed)) { + throw new OAuthException(sprintf( + 'The server of "%s" publishes sign-in details that belong to another server.', + $config->name, + )); + } + $servers = $resourceMetadata['authorization_servers'] ?? null; + $issuer = is_array($servers) && array_is_list($servers) ? ($servers[0] ?? null) : null; + if (!is_string($issuer) || $issuer === '') { + throw new OAuthException(sprintf('The server of "%s" names no authorization server.', $config->name)); + } + + $document = $this->firstDocument(self::authorizationServerUrls($issuer), false); + if ($document === null) { + throw new OAuthException(sprintf( + 'The authorization server of "%s" does not publish its details.', + $config->name, + )); + } + // Simple string comparison: no case folding, no trailing slash, no default port (RFC 8414 3.3). + if (($document['issuer'] ?? null) !== $issuer) { + throw new OAuthException(sprintf( + 'The authorization server of "%s" names a different issuer than the one the server gave.', + $config->name, + )); + } + $methods = $document['code_challenge_methods_supported'] ?? null; + if (!is_array($methods) || !in_array('S256', $methods, true)) { + throw new OAuthException(sprintf( + 'The authorization server of "%s" does not support PKCE with S256, which the MCP client requires.', + $config->name, + )); + } + $tokenUrl = $this->learnedEndpoint($document['token_endpoint'] ?? null); + $registrationUrl = $this->optionalEndpoint($document['registration_endpoint'] ?? null); + $revocationUrl = $this->optionalEndpoint($document['revocation_endpoint'] ?? null); + $authMethods = $document['token_endpoint_auth_methods_supported'] ?? null; + $challenged = $challenge['scope'] ?? null; + $scopes = $config->scopes; + if ($scopes === []) { + $scopes = $challenged !== null && trim($challenged) !== '' + ? self::scopes(explode(' ', $challenged)) + : self::scopes($resourceMetadata['scopes_supported'] ?? []); + } + + return new AuthServer( + $issuer, + self::httpsUrl($document['authorization_endpoint'] ?? null), + (string)$tokenUrl, + $registrationUrl, + $revocationUrl, + $scopes, + $resource, + ($document['authorization_response_iss_parameter_supported'] ?? null) === true, + is_array($authMethods) ? array_values(array_filter($authMethods, 'is_string')) : [], + false, + ); + } + + /** + * An unauthenticated request to the configured server, which answers 401 with a challenge. + * + * @param string $server The MCP server. + * @return array The Bearer challenge's parameters; empty when there are none. + * @throws \CakeDC\Mcp\Client\OAuth\OAuthException On a 200: the server asks for no sign-in. + */ + private function probe(string $server): array + { + $body = (string)json_encode([ + 'jsonrpc' => '2.0', + 'id' => 1, + 'method' => 'initialize', + 'params' => [ + 'protocolVersion' => '2025-11-25', + 'capabilities' => (object)[], + 'clientInfo' => ['name' => (string)ClientConfig::setting('name'), 'version' => '1.0.0'], + ], + ]); + $response = $this->http->send(new HttpRequest( + 'POST', + $server, + ['Content-Type' => 'application/json', 'Accept' => 'application/json, text/event-stream'], + $body, + (float)$this->config->timeout, + ), true); + if ($response->status >= 200 && $response->status < 300) { + throw new OAuthException(sprintf( + 'The server of "%s" does not ask for a sign-in; use it in app mode (without "auth" => "user").', + $this->config->name, + )); + } + if ($response->status !== 401) { + return []; + } + + return self::bearerParameters((string)$response->header('WWW-Authenticate')); + } + + /** + * @param list $urls Candidate URLs, in order. + * @param bool $trusted Whether they come from the config. + * @return array|null The first JSON object answered with a 200, or null. + */ + private function firstDocument(array $urls, bool $trusted): ?array + { + foreach ($urls as $url) { + $response = $this->http->get($url, $trusted, (float)$this->config->timeout); + if ($response->status === 200) { + $document = $response->json(); + if ($document !== null) { + return $document; + } + } + } + + return null; + } + + /** + * @param mixed $value An endpoint from the metadata. + * @return string It, checked by the guard now, so a private endpoint fails discovery rather than a later step. + */ + private function learnedEndpoint(mixed $value): string + { + $url = self::httpsUrl($value); + $this->http->check($url); + + return $url; + } + + /** + * @param mixed $value An optional endpoint. + * @return string|null + */ + private function optionalEndpoint(mixed $value): ?string + { + return $value === null ? null : $this->learnedEndpoint($value); + } + + /** + * @param string $server The configured server URL. + * @return list Its well-known resource metadata URLs: at its path (when it has one), then at the root. + */ + private static function protectedResourceUrls(string $server): array + { + $parts = (array)parse_url($server); + $origin = self::origin($parts); + $path = rtrim((string)($parts['path'] ?? ''), '/'); + $query = isset($parts['query']) && $parts['query'] !== '' ? '?' . $parts['query'] : ''; + if ($path === '') { + return [$origin . self::PROTECTED_RESOURCE . $query]; + } + + return [$origin . self::PROTECTED_RESOURCE . $path . $query, $origin . self::PROTECTED_RESOURCE]; + } + + /** + * @param string $issuer The expected issuer. + * @return list Its metadata URLs in the order RFC 8414 and OpenID Connect Discovery give. + */ + private static function authorizationServerUrls(string $issuer): array + { + $parts = (array)parse_url(self::httpsUrl($issuer)); + if (isset($parts['query'])) { + throw self::unusable(''); + } + $origin = self::origin($parts); + $path = rtrim((string)($parts['path'] ?? ''), '/'); + if ($path === '') { + return [$origin . self::OAUTH_SERVER, $origin . self::OPENID]; + } + + return [$origin . self::OAUTH_SERVER . $path, $origin . self::OPENID . $path, $origin . $path . self::OPENID]; + } + + /** + * Equal means the same scheme, host, port and path (without a trailing slash) and the same query. A prefix + * must end on a path segment: `/mc` is not a prefix of `/mcp`. + * + * @param string $resource The document's `resource`. + * @param string $server The configured server URL. + * @param bool $prefixAllowed Whether a same-origin path prefix is accepted. + * @return bool + */ + private static function resourceMatches(string $resource, string $server, bool $prefixAllowed): bool + { + $theirs = self::comparison($resource); + $ours = self::comparison($server); + if ($theirs === null || $ours === null) { + return false; + } + if ($theirs === $ours) { + return true; + } + [$theirsBase, $theirsQuery] = $theirs; + [$oursBase] = $ours; + + return $prefixAllowed && $theirsQuery === '' && str_starts_with($oursBase, $theirsBase . '/'); + } + + /** + * @param string $url A URL. + * @return array{0: string, 1: string}|null Its lowercase origin without a default port plus its path without a + * trailing slash, and its query; null when it is not a URL. + */ + private static function comparison(string $url): ?array + { + $parts = parse_url($url); + if (!is_array($parts) || !isset($parts['scheme'], $parts['host'])) { + return null; + } + + return [self::origin($parts) . rtrim((string)($parts['path'] ?? ''), '/'), (string)($parts['query'] ?? '')]; + } + + /** + * @param array $parts parse_url() parts. + * @return string Scheme, host and port (left out when it is the scheme's default), lowercase. + */ + private static function origin(array $parts): string + { + $scheme = strtolower((string)($parts['scheme'] ?? 'https')); + $host = strtolower((string)($parts['host'] ?? '')); + $port = $parts['port'] ?? null; + $default = $scheme === 'https' ? 443 : 80; + + return $scheme . '://' . $host . ($port === null || $port === $default ? '' : ':' . $port); + } + + /** + * @param mixed $value A URL from a remote document. + * @return string It, when it is an absolute https URL without user info or fragment. + * @throws \CakeDC\Mcp\Client\OAuth\OAuthException Otherwise. + */ + private static function httpsUrl(mixed $value): string + { + $parts = is_string($value) ? parse_url($value) : false; + if ( + !is_string($value) + || !is_array($parts) + || strtolower((string)($parts['scheme'] ?? '')) !== 'https' + || ($parts['host'] ?? '') === '' + || isset($parts['user']) + || isset($parts['pass']) + || isset($parts['fragment']) + || preg_match('/\s/', $value) === 1 + ) { + throw self::unusable(''); + } + + return $value; + } + + /** + * @param string $client The client name, or empty. + * @return \CakeDC\Mcp\Client\OAuth\OAuthException + */ + private static function unusable(string $client): OAuthException + { + return new OAuthException($client === '' + ? 'The server\'s sign-in details name an address the MCP client cannot use.' + : sprintf('The server of "%s" publishes sign-in details the MCP client cannot use.', $client)); + } + + /** + * @param mixed $values Scope names, as a list. + * @return list The valid scope tokens, once each, in order, without `offline_access`. + */ + private static function scopes(mixed $values): array + { + if (!is_array($values)) { + return []; + } + $scopes = []; + foreach ($values as $value) { + if ( + is_string($value) + && $value !== 'offline_access' + && preg_match(self::SCOPE_TOKEN, $value) === 1 + && !in_array($value, $scopes, true) + ) { + $scopes[] = $value; + } + } + + return $scopes; + } + + /** + * Reads the Bearer challenge's parameters from a WWW-Authenticate header that may hold several challenges. + * + * @param string $header The header's values. + * @return array Lowercase parameter name => value, the first of each name. + */ + private static function bearerParameters(string $header): array + { + $parameters = []; + $inBearer = false; + $offset = 0; + $length = strlen($header); + while ($offset < $length) { + $offset += strspn($header, " \t,", $offset); + if (preg_match('/\G[!#$%&\'*+\-.^_`|~0-9A-Za-z]+/', $header, $match, 0, $offset) !== 1) { + break; + } + $name = $match[0]; + $offset += strlen($name); + $afterSpaces = $offset + strspn($header, " \t", $offset); + if (($header[$afterSpaces] ?? '') !== '=') { + // A new challenge's scheme. + if ($inBearer) { + break; + } + $inBearer = strcasecmp($name, 'Bearer') === 0; + continue; + } + $offset = $afterSpaces + 1; + $offset += strspn($header, " \t", $offset); + if (($header[$offset] ?? '') === '"') { + if (preg_match('/\G"((?:[^"\\\\]|\\\\.)*)"/s', $header, $match, 0, $offset) !== 1) { + break; + } + $value = (string)preg_replace('/\\\\(.)/s', '$1', $match[1]); + } elseif (preg_match('/\G[^\s,]*/', $header, $match, 0, $offset) === 1) { + $value = $match[0]; + } else { + break; + } + $offset += strlen($match[0]); + $key = strtolower($name); + if ($inBearer && !isset($parameters[$key])) { + $parameters[$key] = $value; + } + } + + return $parameters; + } +} diff --git a/src/Client/OAuth/OAuthException.php b/src/Client/OAuth/OAuthException.php new file mode 100644 index 0000000..fa983da --- /dev/null +++ b/src/Client/OAuth/OAuthException.php @@ -0,0 +1,31 @@ +discovery->discover(); + $registration = $this->registrar->clientFor($server, $redirectUri); + $verifier = self::base64Url(random_bytes(32)); + $pending = new PendingAuthorization( + $this->config->name, + $userId, + self::base64Url(random_bytes(32)), + $verifier, + $redirectUri, + $returnTo, + DateTime::now()->getTimestamp(), + $server->issuer, + $server->tokenUrl, + $server->revocationUrl, + $server->trusted, + $server->issParameter, + $server->resource, + $registration->clientId, + $registration->authMethod, + ); + $query = [ + 'response_type' => 'code', + 'client_id' => $registration->clientId, + 'redirect_uri' => $redirectUri, + 'state' => $pending->state, + 'code_challenge' => self::base64Url(hash('sha256', $verifier, true)), + 'code_challenge_method' => 'S256', + 'resource' => $server->resource, + ]; + if ($server->scopes !== []) { + $query['scope'] = implode(' ', $server->scopes); + } + $url = $server->authorizationUrl; + $url .= (str_contains($url, '?') ? '&' : '?') . http_build_query($query, '', '&', PHP_QUERY_RFC3986); + + return [$pending, $url]; + } + + /** + * @param \CakeDC\Mcp\Client\OAuth\PendingAuthorization $pending The sign-in started. + * @param array $query The callback's query. + * @return \CakeDC\Mcp\Client\Store\StoredConnection The stored grant. + * @throws \CakeDC\Mcp\Client\OAuth\OAuthException When the response does not match the sign-in started. + * @throws \CakeDC\Mcp\Client\Exception\ClientException + */ + public function complete(PendingAuthorization $pending, array $query): StoredConnection + { + $state = $query['state'] ?? null; + if (!is_string($state) || !hash_equals($pending->state, $state) || $pending->client !== $this->config->name) { + throw new OAuthException('The sign-in response does not match the sign-in that was started.'); + } + $now = DateTime::now()->getTimestamp(); + if ($now - $pending->createdAt > PendingAuthorization::LIFETIME) { + throw new OAuthException('The sign-in took too long; connect again.'); + } + if (isset($query['error'])) { + $error = OAuthException::code($query['error']) ?? 'error'; + + throw new OAuthException(sprintf('The authorization server answered %s.', $error), $error); + } + $iss = $query['iss'] ?? null; + if (($iss !== null && $iss !== $pending->issuer) || ($iss === null && $pending->issParameter)) { + // RFC 9207: the response must come from the server the flow started with (mix-up). + throw new OAuthException('The sign-in response came from another authorization server.'); + } + $code = $query['code'] ?? null; + if (!is_string($code) || $code === '') { + throw new OAuthException('The sign-in response has no code.'); + } + + $secret = $this->secret($pending); + try { + $tokens = $this->tokens->exchange( + $pending->tokenUrl, + $pending->trusted, + $pending->clientId, + $secret, + $pending->authMethod, + [ + 'code' => $code, + 'code_verifier' => $pending->verifier, + 'redirect_uri' => $pending->redirectUri, + 'resource' => $pending->resource, + ], + ); + } catch (OAuthException $e) { + if ($e->error === 'invalid_client' && $this->config->clientId === null) { + // A registration the server dropped: the next connect registers again. + $this->store->deleteRegistration($this->config->name, $pending->issuer); + } + + throw $e; + } + + $connection = new StoredConnection( + $this->config->name, + $pending->userId, + $tokens->accessToken, + $tokens->refreshToken, + $tokens->expiresIn === null ? null : $now + $tokens->expiresIn, + $tokens->scope, + $pending->issuer, + $pending->tokenUrl, + $pending->revocationUrl, + $pending->clientId, + $secret, + $pending->authMethod, + $pending->resource, + ); + $this->store->save($connection); + + return $connection; + } + + /** + * @param \CakeDC\Mcp\Client\OAuth\PendingAuthorization $pending The sign-in. + * @return string|null The client secret of its client id: configured, or from the stored registration. + */ + private function secret(PendingAuthorization $pending): ?string + { + if ($this->config->clientId !== null) { + return $this->config->clientId === $pending->clientId ? $this->config->clientSecret : null; + } + $registration = $this->store->registration($this->config->name, $pending->issuer); + + return $registration !== null && $registration->clientId === $pending->clientId + ? $registration->clientSecret + : null; + } + + /** + * @param string $bytes Binary data. + * @return string Base64url without padding. + */ + private static function base64Url(string $bytes): string + { + return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '='); + } +} diff --git a/src/Client/OAuth/PendingAuthorization.php b/src/Client/OAuth/PendingAuthorization.php new file mode 100644 index 0000000..92e4b46 --- /dev/null +++ b/src/Client/OAuth/PendingAuthorization.php @@ -0,0 +1,106 @@ + For the session. + */ + public function toArray(): array + { + return get_object_vars($this); + } + + /** + * @param mixed $data What toArray() gave, read back from the session. + * @return self|null Null when it is not a whole pending sign-in. + */ + public static function fromArray(mixed $data): ?self + { + if (!is_array($data)) { + return null; + } + $strings = [ + 'client', 'userId', 'state', 'verifier', 'redirectUri', 'returnTo', 'issuer', 'tokenUrl', 'resource', + 'clientId', 'authMethod', + ]; + foreach ($strings as $key) { + if (!is_string($data[$key] ?? null)) { + return null; + } + } + if ( + !is_int($data['createdAt'] ?? null) + || !is_bool($data['trusted'] ?? null) + || !is_bool($data['issParameter'] ?? null) + || !(is_string($data['revocationUrl'] ?? null) || ($data['revocationUrl'] ?? null) === null) + ) { + return null; + } + + return new self( + $data['client'], + $data['userId'], + $data['state'], + $data['verifier'], + $data['redirectUri'], + $data['returnTo'], + $data['createdAt'], + $data['issuer'], + $data['tokenUrl'], + $data['revocationUrl'], + $data['trusted'], + $data['issParameter'], + $data['resource'], + $data['clientId'], + $data['authMethod'], + ); + } +} diff --git a/src/Client/OAuth/Registrar.php b/src/Client/OAuth/Registrar.php new file mode 100644 index 0000000..44061d5 --- /dev/null +++ b/src/Client/OAuth/Registrar.php @@ -0,0 +1,141 @@ +config; + if ($config->clientId !== null) { + return new Registration( + $config->name, + $server->issuer, + $redirectUri, + $config->clientId, + $config->clientSecret, + self::automaticMethod($config->clientSecret !== null, $server->authMethods), + ); + } + $existing = $this->store->registration($config->name, $server->issuer); + if ($existing !== null && $existing->redirectUri === $redirectUri) { + return $existing; + } + if ($server->registrationUrl === null) { + throw new OAuthException(sprintf( + 'The authorization server of "%s" does not register clients automatically: ask its owner for a ' + . 'client id and set "Mcp.clients.%s.clientId" (and "clientSecret" if it has one).', + $config->name, + $config->name, + )); + } + + $response = $this->http->send(new HttpRequest( + 'POST', + $server->registrationUrl, + ['Content-Type' => 'application/json', 'Accept' => 'application/json'], + (string)json_encode([ + 'client_name' => (string)ClientConfig::setting('name'), + 'redirect_uris' => [$redirectUri], + 'grant_types' => ['authorization_code', 'refresh_token'], + 'response_types' => ['code'], + 'token_endpoint_auth_method' => 'none', + ], JSON_UNESCAPED_SLASHES), + (float)$config->timeout, + ), false); + $answer = $response->json(); + $clientId = $answer['client_id'] ?? null; + $secret = $answer['client_secret'] ?? null; + if ( + ($response->status !== 200 && $response->status !== 201) + || !self::isCredential($clientId) + || ($secret !== null && !self::isCredential($secret)) + ) { + throw new OAuthException(sprintf( + 'The authorization server of "%s" refused to register the application.', + $config->name, + )); + } + $method = $answer['token_endpoint_auth_method'] ?? null; + if (!in_array($method, self::AUTH_METHODS, true)) { + $method = $secret === null ? 'none' : 'client_secret_basic'; + } + /** @var string $clientId */ + /** @var string|null $secret */ + $registration = new Registration($config->name, $server->issuer, $redirectUri, $clientId, $secret, $method); + $this->store->saveRegistration($registration); + + return $registration; + } + + /** + * How a configured client authenticates: `none` without a secret; with one, `client_secret_basic` (the RFC 8414 + * default) unless the server lists `client_secret_post` and not basic. + * + * @param bool $hasSecret Whether there is a client secret. + * @param list $supported The server's `token_endpoint_auth_methods_supported`. + * @return string + */ + public static function automaticMethod(bool $hasSecret, array $supported): string + { + if (!$hasSecret) { + return 'none'; + } + if (!in_array('client_secret_basic', $supported, true) && in_array('client_secret_post', $supported, true)) { + return 'client_secret_post'; + } + + return 'client_secret_basic'; + } + + /** + * @param mixed $value A client id or secret from the server. + * @return bool Whether it can be kept and sent back. + */ + private static function isCredential(mixed $value): bool + { + return is_string($value) + && $value !== '' + && strlen($value) <= self::MAX_LENGTH + && preg_match('/\A[\x20-\x7E]+\z/', $value) === 1; + } +} diff --git a/src/Client/OAuth/TokenClient.php b/src/Client/OAuth/TokenClient.php new file mode 100644 index 0000000..d15efb2 --- /dev/null +++ b/src/Client/OAuth/TokenClient.php @@ -0,0 +1,221 @@ + $grant `code`, `code_verifier`, `redirect_uri` and `resource`. + * @return \CakeDC\Mcp\Client\OAuth\TokenSet + * @throws \CakeDC\Mcp\Client\OAuth\OAuthException + */ + public function exchange( + string $tokenUrl, + bool $trusted, + string $clientId, + ?string $clientSecret, + string $authMethod, + array $grant, + ): TokenSet { + $form = ['grant_type' => 'authorization_code'] + $grant; + + return self::read($this->http->send( + $this->post($tokenUrl, $form, $clientId, $clientSecret, $authMethod), + $trusted, + )); + } + + /** + * @param \CakeDC\Mcp\Client\Store\StoredConnection $connection A grant with a refresh token. + * @param bool $trusted Whether its token endpoint comes from the config. + * @return \CakeDC\Mcp\Client\OAuth\TokenSet + * @throws \CakeDC\Mcp\Client\OAuth\OAuthException `invalid_grant` when the refresh token is no longer accepted. + */ + public function refresh(StoredConnection $connection, bool $trusted): TokenSet + { + return self::read($this->http->send($this->post( + $connection->tokenUrl, + [ + 'grant_type' => 'refresh_token', + 'refresh_token' => (string)$connection->refreshToken, + 'resource' => $connection->resource, + ], + $connection->clientId, + $connection->clientSecret, + $connection->authMethod, + ), $trusted)); + } + + /** + * Revokes the refresh token, or the access token when there is no refresh token or its revocation failed. + * Best effort: a failure is logged without the token and never thrown. + * + * @param \CakeDC\Mcp\Client\Store\StoredConnection $connection The grant. + * @param bool $trusted Whether its revocation endpoint comes from the config. + * @return void + */ + public function revoke(StoredConnection $connection, bool $trusted): void + { + if ($connection->revocationUrl === null) { + return; + } + $tokens = []; + if ($connection->refreshToken !== null) { + $tokens['refresh_token'] = $connection->refreshToken; + } + $tokens['access_token'] = $connection->accessToken; + foreach ($tokens as $hint => $token) { + try { + $response = $this->http->send($this->post( + $connection->revocationUrl, + ['token' => $token, 'token_type_hint' => $hint], + $connection->clientId, + $connection->clientSecret, + $connection->authMethod, + ), $trusted); + if ($response->status >= 200 && $response->status < 300) { + // Revoking a refresh token revokes the access tokens of its grant (RFC 7009 2.1). + return; + } + Log::warning(sprintf( + 'MCP client "%s": token revocation answered with status %d.', + $connection->client, + $response->status, + ), ['scope' => [McpLogger::SCOPE]]); + } catch (ClientException $e) { + Log::warning( + sprintf('MCP client "%s": token revocation failed: %s', $connection->client, $e->getMessage()), + ['scope' => [McpLogger::SCOPE]], + ); + } + } + } + + /** + * @param string $url The endpoint. + * @param array $form The form fields. + * @param string $clientId The client id. + * @param string|null $clientSecret The client secret, if any. + * @param string $authMethod How the client authenticates. + * @return \CakeDC\Mcp\Client\Http\HttpRequest + */ + private function post( + string $url, + array $form, + string $clientId, + ?string $clientSecret, + string $authMethod, + ): HttpRequest { + $headers = ['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json']; + if ($authMethod === 'client_secret_basic' && $clientSecret !== null) { + // RFC 6749 2.3.1: both form-encoded before they are joined. + $headers['Authorization'] = 'Basic ' . base64_encode(urlencode($clientId) . ':' . urlencode($clientSecret)); + } else { + $form['client_id'] = $clientId; + if ($authMethod === 'client_secret_post' && $clientSecret !== null) { + $form['client_secret'] = $clientSecret; + } + } + + return new HttpRequest('POST', $url, $headers, http_build_query($form), (float)$this->timeout); + } + + /** + * @param \CakeDC\Mcp\Client\Http\HttpResponse $response A token endpoint's answer. + * @return \CakeDC\Mcp\Client\OAuth\TokenSet + * @throws \CakeDC\Mcp\Client\OAuth\OAuthException + */ + private static function read(HttpResponse $response): TokenSet + { + $body = $response->json() ?? []; + if ($response->status === 400 || $response->status === 401) { + $error = OAuthException::code($body['error'] ?? null); + throw new OAuthException(match ($error) { + 'invalid_grant' => 'The sign-in expired or was revoked; connect again.', + 'invalid_client', 'unauthorized_client' => 'The authorization server no longer accepts this client.', + default => 'The authorization server refused the request.', + }, $error); + } + $access = $body['access_token'] ?? null; + $refresh = $body['refresh_token'] ?? null; + $type = $body['token_type'] ?? null; + if ( + $response->status !== 200 + || !self::isToken($access) + || ($refresh !== null && !self::isToken($refresh)) + || !is_string($type) + || strcasecmp($type, 'bearer') !== 0 + ) { + throw new OAuthException('The authorization server gave an answer the MCP client cannot use.'); + } + $expiresIn = $body['expires_in'] ?? null; + if (is_string($expiresIn) && ctype_digit($expiresIn)) { + $expiresIn = (int)$expiresIn; + } + $scope = $body['scope'] ?? null; + + /** @var string|null $refresh */ + return new TokenSet( + $access, + $refresh, + is_int($expiresIn) && $expiresIn > 0 ? min($expiresIn, self::MAX_EXPIRES_IN) : null, + is_string($scope) && $scope !== '' && strlen($scope) <= 2000 ? $scope : null, + ); + } + + /** + * Visible ASCII only: a control character or a space would make an Authorization header the HTTP client refuses. + * + * @param mixed $value A field of the answer. + * @return bool Whether it can be a token to keep. + * @phpstan-assert-if-true string $value + */ + private static function isToken(mixed $value): bool + { + return is_string($value) + && $value !== '' + && strlen($value) <= self::MAX_TOKEN_LENGTH + && preg_match('/\A[\x21-\x7E]+\z/', $value) === 1; + } +} diff --git a/src/Client/OAuth/TokenSet.php b/src/Client/OAuth/TokenSet.php new file mode 100644 index 0000000..acd12f8 --- /dev/null +++ b/src/Client/OAuth/TokenSet.php @@ -0,0 +1,24 @@ + $user, + is_object($user) && method_exists($user, 'getIdentifier') => $user->getIdentifier(), + $user instanceof EntityInterface => $user->get('id'), + is_array($user), $user instanceof ArrayAccess => $user['id'] ?? null, + default => null, + }; + if ((!is_int($id) && !is_string($id)) || $id === '') { + throw new InvalidArgumentException( + 'The MCP client needs the user: pass an id, an identity, or a user entity or array with an "id".', + ); + } + + return (string)$id; + } +} diff --git a/src/Controller/McpClientController.php b/src/Controller/McpClientController.php new file mode 100644 index 0000000..a8f5cde --- /dev/null +++ b/src/Controller/McpClientController.php @@ -0,0 +1,197 @@ +loadComponent('Flash'); + } + + /** + * @param string $client The client's name. + * @return \Cake\Http\Response|null + */ + public function connect(string $client): ?Response + { + $this->skipHostAuthorization(); + $config = $this->userModeClient($client); + if ($config === null) { + return $this->plain(404, 'Not Found'); + } + $userId = $this->currentUserId(); + if ($userId === null) { + return $this->plain(401, 'Log in to connect.'); + } + $returnTo = self::localPath($this->request->getQuery('redirect')); + $redirectUri = Router::url( + ['plugin' => 'CakeDC/Mcp', 'controller' => 'McpClient', 'action' => 'callback', $config->name], + true, + ); + + try { + [$pending, $url] = McpClients::registry()->flow($config->name)->start($userId, $redirectUri, $returnTo); + } catch (ClientException $e) { + Log::warning( + sprintf('MCP client "%s": the sign-in could not start: %s', $config->name, $e->getMessage()), + ['scope' => [McpLogger::SCOPE]], + ); + $this->Flash->error(sprintf('The connection to %s could not be started. Try again later.', $config->name)); + + return $this->redirect($returnTo); + } + $this->request->getSession()->write(self::SESSION_KEY . '.' . $config->name, $pending->toArray()); + + return $this->redirect($url); + } + + /** + * @param string $client The client's name. + * @return \Cake\Http\Response|null + */ + public function callback(string $client): ?Response + { + $this->skipHostAuthorization(); + $config = $this->userModeClient($client); + if ($config === null) { + return $this->plain(404, 'Not Found'); + } + $session = $this->request->getSession(); + $key = self::SESSION_KEY . '.' . $config->name; + // Used once, whatever happens next. + $pending = PendingAuthorization::fromArray($session->consume($key)); + $failed = sprintf('The connection to %s could not be completed. Try again.', $config->name); + if ($pending === null) { + $this->Flash->error($failed); + + return $this->redirect('/'); + } + $userId = $this->currentUserId(); + if ($userId === null || !hash_equals($pending->userId, $userId)) { + $this->Flash->error($failed); + + return $this->redirect($pending->returnTo); + } + + try { + McpClients::registry()->flow($config->name)->complete($pending, $this->request->getQueryParams()); + } catch (OAuthException $e) { + Log::warning( + sprintf('MCP client "%s": the sign-in failed: %s', $config->name, $e->getMessage()), + ['scope' => [McpLogger::SCOPE]], + ); + $this->Flash->error($e->error === null + ? $failed + : sprintf('The connection to %s could not be completed: %s.', $config->name, $e->error)); + + return $this->redirect($pending->returnTo); + } catch (ClientException $e) { + Log::warning( + sprintf('MCP client "%s": the sign-in failed: %s', $config->name, $e->getMessage()), + ['scope' => [McpLogger::SCOPE]], + ); + $this->Flash->error($failed); + + return $this->redirect($pending->returnTo); + } + $this->Flash->success(sprintf('Connected to %s.', $config->name)); + + return $this->redirect($pending->returnTo); + } + + /** + * @param string $client The client's name. + * @return \CakeDC\Mcp\Client\ClientConfig|null The user mode client, or null when there is none of that name. + */ + private function userModeClient(string $client): ?ClientConfig + { + try { + $config = ClientConfig::fromConfig($client); + } catch (InvalidArgumentException) { + return null; + } + + return $config->isUser() ? $config : null; + } + + /** + * @return string|null The logged-in user's id, null when no one is logged in. + */ + private function currentUserId(): ?string + { + $identity = $this->request->getAttribute((string)ClientConfig::setting('identityAttribute')); + if ($identity === null) { + return null; + } + try { + return UserId::of($identity); + } catch (InvalidArgumentException) { + return null; + } + } + + /** + * A plain answer, independent of the application's error pages. + * + * @param int $status The status. + * @param string $text The text. + * @return \Cake\Http\Response + */ + private function plain(int $status, string $text): Response + { + return $this->response->withStatus($status)->withType('text/plain')->withStringBody($text); + } + + /** + * @param mixed $path The `redirect` query parameter. + * @return string It when it is a path on this site, else `/`. + */ + private static function localPath(mixed $path): string + { + if ( + !is_string($path) + || !str_starts_with($path, '/') + || str_starts_with($path, '//') + || str_contains($path, '\\') + || preg_match('/[\x00-\x1F\x7F]/', $path) === 1 + || strlen($path) > 2000 + ) { + return '/'; + } + + return $path; + } +} diff --git a/src/McpConfig.php b/src/McpConfig.php index 77d4ba9..81e8940 100644 --- a/src/McpConfig.php +++ b/src/McpConfig.php @@ -7,6 +7,7 @@ use Cake\Http\ServerRequest; use Cake\Utility\Hash; use CakeDC\Mcp\Authorization\AllowAllToolAuthorizer; +use CakeDC\Mcp\Client\ClientConfig; use InvalidArgumentException; use Psr\Http\Message\ServerRequestInterface; @@ -327,11 +328,14 @@ private static function merge(array $base, array $override): array * it an anonymous request is redirected to the login page instead of receiving the plugin's 401 and its * metadata. The plugin decides access itself (authentication, scopes, then the tool authorizer). * + * With a user mode client in `Mcp.clients`, a second rule lets logged-in users reach its connect and callback + * routes. + * * @return list> */ public static function rbacPermissions(): array { - return [ + $rules = [ [ 'role' => '*', 'plugin' => 'CakeDC/Mcp', @@ -340,6 +344,17 @@ public static function rbacPermissions(): array 'bypassAuth' => true, ], ]; + if (ClientConfig::anyUserMode()) { + // The sign-in routes of user mode clients: any logged-in user (the controller checks the rest). + $rules[] = [ + 'role' => '*', + 'plugin' => 'CakeDC/Mcp', + 'controller' => ['McpClient'], + 'action' => ['connect', 'callback'], + ]; + } + + return $rules; } /** diff --git a/src/McpPlugin.php b/src/McpPlugin.php index 0b50624..cf5897a 100644 --- a/src/McpPlugin.php +++ b/src/McpPlugin.php @@ -10,6 +10,7 @@ use Cake\Core\ContainerInterface; use Cake\Core\PluginApplicationInterface; use Cake\Routing\RouteBuilder; +use CakeDC\Mcp\Client\ClientConfig; use CakeDC\Mcp\Command\McpCheckCommand; use CakeDC\Mcp\Command\McpInspectorCommand; use CakeDC\Mcp\Command\McpServerCommand; @@ -85,6 +86,17 @@ public function routes(RouteBuilder $routes): void ['plugin' => 'CakeDC/Mcp', 'controller' => 'ProtectedResource', 'action' => 'metadata'] + $param, )->setMethods(['GET', 'OPTIONS']); } + + // The sign-in of user mode clients (Mcp.clients with `auth` `user`), only when one is configured. + if (ClientConfig::anyUserMode()) { + $base = '/' . trim((string)ClientConfig::setting('route'), '/'); + foreach (['connect', 'callback'] as $action) { + $routes->connect( + $base . '/{client}/' . $action, + ['plugin' => 'CakeDC/Mcp', 'controller' => 'McpClient', 'action' => $action], + )->setPass(['client'])->setPatterns(['client' => '[A-Za-z0-9_-]+'])->setMethods(['GET']); + } + } } /** diff --git a/tests/Support/FakeOAuthServer.php b/tests/Support/FakeOAuthServer.php new file mode 100644 index 0000000..da1a2f2 --- /dev/null +++ b/tests/Support/FakeOAuthServer.php @@ -0,0 +1,182 @@ +> + */ + public array $tokenRequests = []; + + /** + * @var list> + */ + public array $registrations = []; + + /** + * @var list> + */ + public array $revocations = []; + + /** + * The code the token endpoint accepts. + */ + public string $code = 'good-code'; + + /** + * Whether a refresh is answered with `invalid_grant`. + */ + public bool $rejectRefresh = false; + + /** + * Whether the revocation endpoint fails. + */ + public bool $revocationFails = false; + + private int $issued = 0; + + public function __construct() + { + $this->mcp = new SdkServerHttpClient(); + $this->mcp->tokens = []; + $this->mcp->challenge = sprintf( + 'Bearer resource_metadata="%s", scope="read write"', + self::RESOURCE_METADATA, + ); + $this->dns = new StaticHostResolver([ + 'mcp.example.com' => ['93.184.216.34'], + 'auth.example.com' => ['93.184.216.35'], + 'internal.example.com' => ['10.0.0.1'], + ]); + $this->guarded = new ScriptedGuardedTransport(); + $this->guarded->json(self::RESOURCE_METADATA, [ + 'resource' => self::MCP, + 'authorization_servers' => [self::ISSUER], + 'scopes_supported' => ['read', 'write', 'offline_access'], + ]); + $this->authorizationServer(); + $this->guarded->on('POST', self::ISSUER . '/register', function (HttpRequest $request): HttpResponse { + $this->registrations[] = (array)json_decode((string)$request->body, true); + + return self::json(201, ['client_id' => 'dyn-client-' . count($this->registrations)]); + }); + $this->guarded->on('POST', self::ISSUER . '/token', fn(HttpRequest $request): HttpResponse => $this->token($request)); + $this->guarded->on('POST', self::ISSUER . '/revoke', function (HttpRequest $request): HttpResponse { + parse_str((string)$request->body, $form); + $this->revocations[] = array_map('strval', $form); + + return $this->revocationFails ? new HttpResponse(503, [], '') : new HttpResponse(200, [], ''); + }); + } + + /** + * Serves the authorization server's metadata, with $overrides. + * + * @param array $overrides Fields to replace or add. + * @return void + */ + public function authorizationServer(array $overrides = []): void + { + $this->guarded->json(self::AS_METADATA, $overrides + [ + 'issuer' => self::ISSUER, + 'authorization_endpoint' => self::ISSUER . '/authorize', + 'token_endpoint' => self::ISSUER . '/token', + 'registration_endpoint' => self::ISSUER . '/register', + 'revocation_endpoint' => self::ISSUER . '/revoke', + 'code_challenge_methods_supported' => ['S256'], + 'authorization_response_iss_parameter_supported' => true, + 'token_endpoint_auth_methods_supported' => ['none', 'client_secret_basic'], + ]); + } + + /** + * @param \CakeDC\Mcp\Client\Store\ConnectionStoreInterface|null $store The store; the table store by default. + * @return \CakeDC\Mcp\Client\ClientRegistry A registry on these doubles. + */ + public function registry(?ConnectionStoreInterface $store = null): ClientRegistry + { + return new ClientRegistry( + new FixedHttpClientFactory($this->mcp), + $store ?? new TableConnectionStore(), + new GuardedHttp(new EndpointGuard($this->dns), $this->guarded, 1024 * 1024), + ); + } + + /** + * @param \CakeDC\Mcp\Client\Http\HttpRequest $request A token request. + * @return \CakeDC\Mcp\Client\Http\HttpResponse + */ + private function token(HttpRequest $request): HttpResponse + { + parse_str((string)$request->body, $form); + $form = array_map('strval', $form); + $form['_authorization'] = $request->headers['Authorization'] ?? ''; + $this->tokenRequests[] = $form; + $grant = $form['grant_type'] ?? ''; + if ($grant === 'authorization_code' && ($form['code'] ?? '') !== $this->code) { + return self::json(400, ['error' => 'invalid_grant', 'error_description' => 'bad code