diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index eb487b4..a8e6d3e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -84,7 +84,7 @@ jobs: working-directory: cakephp-mcp - run: vendor/bin/phpcs working-directory: cakephp-mcp - - run: vendor/bin/phpstan analyse --no-progress + - run: vendor/bin/phpstan analyse --no-progress --memory-limit=1G working-directory: cakephp-mcp conformance: @@ -118,3 +118,7 @@ jobs: node-version: '22' - run: tests/Conformance/run.sh working-directory: cakephp-mcp + # The client side: the plugin's MCP client (tests/Conformance/client.php) against the suite's own servers. + - run: tests/Conformance/run-client.sh + if: ${{ !cancelled() }} + working-directory: cakephp-mcp diff --git a/.gitignore b/.gitignore index 4970756..9e7c9fd 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ .phpunit.result.cache /tests/Conformance/tmp/ /tests/Conformance/results/ +/tests/Conformance/results-client/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 6523067..2fb0bb1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,63 @@ # Changelog +## 2.2.0 (2026-11-20) + +Behaviour changes a 2.1 application can notice, without changing its config or code: + +- The tool registry is loaded when the server is built, before the caller is authenticated. A loader added in `Mcp.server.configure` that registers tools depending on who calls now sees no identity; decide per caller in an authorizer instead. (2.1 already did this with the audit log on.) +- `initialize` and `server/discover` announce exactly what the server has: a server with only tools no longer announces `prompts` or `resources`. With an event bus set in `Mcp.server.configure`, `tools.listChanged` is no longer announced. +- `McpTestTrait::mcpCallTool()` sends a progress token (`_meta.progressToken`) and a `logging/setLevel` of `debug` before the call, so a tool's notifications can be checked (see `docs/testing.md`). +- A cache policy set in `Mcp.server.configure` is sent private on `tools/list` when the authorizer is not `AllowAllToolAuthorizer`, even when it says `CacheScope::Public`: the list depends on who asks. +- With a registry set in `Mcp.server.configure`, the audit log asks that registry whether a tool exists: a call to a tool it does not have is recorded as `invalid`, where 2.1 could record `denied`. +- `McpConfig::isEndpoint()` reads the path as the router does, so `/%6Dcp` is the `/mcp` endpoint (2.1 answered false and the CSRF check refused it), and once routing has run it follows the route that matched: a route the application connects itself to the plugin's controller is an endpoint. +- A call whose authorizer throws while the audit records it is still recorded (with the outcome its error gives); 2.1 dropped that record. +- `bin/cake mcp check` can fail where 2.1 passed: on a tool whose `_meta.ui.resourceUri` points to a resource that is not registered as an app resource (with its MIME type), on such a tool when the MCP Apps extension is not enabled, and on a key under `Mcp.clients` that is not a client setting. Its `Authorizer` line warns about an Rbac rule for plugin `CakeDC/Mcp` with a controller the plugin does not have. + +- Authorization of resources and prompts: an authorizer that also implements `ResourceAuthorizerInterface` (`canReadResource()`) or `PromptAuthorizerInterface` (`canGetPrompt()`) decides who reads which resource and gets which prompt. A denied one is left out of `resources/list`, `resources/templates/list` and `prompts/list`, reading, subscribing to, unsubscribing from, getting or completing it answers like an unknown one, a denied template also denies every URI it serves, a `subscriptions/listen` stream carries no update of a resource the caller cannot read, and with cache hints those lists and `resources/read` are sent private. `RbacToolAuthorizer` implements both, as controllers `Resources` (the URI as action) and `Prompts`, only once a rule names plugin `CakeDC/Mcp` and that controller, so 2.1 rule sets change nothing. The `mcp check` `Authorizer` line says whether resources and prompts are covered. See `docs/authorization.md`. +- `McpTestTrait` for prompts, resources and completions: `mcpGetPrompt()`, `mcpReadResource()`, `mcpComplete()`, `mcpListPrompts()`, `mcpListResources()`, `mcpListResourceTemplates()`, and `assertMcpPromptMessages()`, `assertMcpPromptContains()`, `assertMcpPromptError()`, `assertMcpPromptDenied()`, `assertMcpResourceText()`, `assertMcpResourceContains()`, `assertMcpResourceError()`, `assertMcpResourceDenied()`, `assertMcpCompletionValues()`, and the `Listed` and `NotListed` assertions for prompts, resources and templates. The tests `bake mcp_resource` and `bake mcp_prompt` write use them. +- `docs/resources-and-prompts.md`: resources, templates, prompts, completions and content types with examples, their authorization and testing. +- MCP client, Client ID Metadata Document: each user mode client serves one at `//client.json`, and `Mcp.clients..registration` (`auto` by default, `metadata`, `dynamic`) uses its URL as `client_id` when the authorization server says `client_id_metadata_document_supported` and `App.fullBaseUrl` is public https on a name that resolves to public addresses only (a development site such as `*.ddev.site`, or a `.test` name, registers dynamically); otherwise dynamic registration as before. A configured `clientId` always wins. `McpConfig::rbacPermissions()` lets anyone fetch the document. The `mcp check` `Clients` line says which registration each client uses. +- MCP client, list cache: `Mcp.clients..cache`, a Cake cache config name, keeps list results that carry 2026-07-28 cache hints for their ttl, `private` ones per user (user mode) or per client (app mode) and always per credential they were asked with (never served for another token, nor after a reconnection with another account), `public` ones per client; a `list_changed` notification drops them. `readResource()` results (per URI, dropped on `resources/updated`) and the `server/discover` answer of a new connection are cached the same way. Off by default. `listResourceTemplates()` is new on clients. +- MCP client: `Mcp.clients..token` may be a callable returning the token, called for each request (for tokens that rotate); `mcp check` does not call it. +- MCP client: `Mcp.client.proxy` sends every client request through an outbound proxy, the addresses remote servers name included; their name checks stay, the address pin is dropped because the proxy resolves the name. A configured `url` on this machine is reached directly, `NO_PROXY` is not followed, and the SOCKS scheme is `socks5h` (the proxy resolves names). `mcp check` shows it. Learned addresses under local names (`.localhost`, `.local`, `.internal`, `.home.arpa`...) are now refused. +- MCP client: `Mcp.clients..allowPrivateNetwork` lets the OAuth endpoints learned for that client resolve to private, loopback or link-local addresses (plain http also needs `allowInsecure`); other clients are not affected and `mcp check` warns. +- Config mistakes of `Mcp.servers` and `Mcp.clients` entries are logged as errors to the loggers without a scope (the application skeleton's `error` log) as well as the `mcp` scope, once per PHP process (once per request under PHP-FPM). The `mcp check` `Cache hints` line reads a policy set in `server.configure`. +- Named servers on routes with parameters (`'route' => '/mcp/t/{tenant}'`): one config and one set of tools for every value; tools read it with `$request->getParam()` or the injectable `CakeDC\Mcp\Server\McpRoute`; in `oauth` and `external` modes each value is its own resource with its own protected resource metadata URL, so a token for one value is refused for another (a configured resource or audience must hold every parameter, or the server is not served, the mistake is logged and `mcp check` fails; `mcp check` warns in host mode, which binds nothing to the value; tools must still check that the identity belongs to it); sessions are kept apart per value, audit records carry a `route` field, `mcp check` checks the pattern and `McpTestTrait::mcpUseServer($server, $values)` sets them in tests. Parameters are for named servers only: a default `Mcp.route` with one is not served (every request fails with the reason logged) and `mcp check` fails on it. See `docs/configuration.md`. +- Named servers with `'route' => false` are served over stdio only (`bin/cake mcp server --server `), with no HTTP routes. +- `Mcp.server.icons`: icons in the server info. +- `find_tools` matches whole words in any language (a query in Spanish no longer matches single letters), also searches the names and descriptions of tool arguments, takes a query of at most 200 characters, and caps its result at 64 KiB of tools with `hasMore`. +- `McpTestTrait` with `Mcp.apps.enabled` on tells the server it renders apps, so `tools/list` and the `Listed` assertions see app-only tools as an MCP Apps host does. +- `McpTestTrait`: `assertMcpStructuredContentSubset()`, `assertMcpStructuredContentNotSubset()`, `assertMcpStructuredContentLacks()`, `assertMcpStructuredContentMissing()`, `assertMcpStructuredContentIgnoringOrder()`, `assertMcpStructuredContentKeys()`, `assertMcpStructuredContentCount()`, `assertMcpStructuredContentType()`, a closure as the expected value of `assertMcpStructuredContentPath()`, `assertMcpCompletionContains()`, and `assertMcpPromptListedFor()`, `assertMcpPromptNotListedFor()`, `assertMcpResourceListedFor()`, `assertMcpResourceNotListedFor()`. +- An `Mcp-*` header that is not valid UTF-8 is answered with `400` and a JSON-RPC `-32600` error naming the header, instead of a `500`. +- Docs: the sandbox `domain` of an MCP App page is left to the host, and set from its documentation. +- MCP client: `ping()`, `serverInfo()`, `capabilities()`, `instructions()` and `protocolVersion()`; a `$limit` on the list calls; one retry, never more, of a request the server refused before running it (a header mismatch, `-32020`, after fetching every page of the tool list again; an expired session, on a new one); answers to the server's `ping`; sessions closed when the PHP process ends. +- MCP client: dynamic registration sends `application_type` (`web`, or `native` for a callback on this machine) and `scope`. +- MCP client: `'auth' => 'client_credentials'` gets the application's own OAuth token with `clientId` and `clientSecret` from the configured `issuer` or `tokenUrl`, keeps it in the connection store until it expires (and only for the issuer, token URL, client id and scopes it was asked with), and renews it once on a `401`. +- MCP client, scope step-up: a `403 insufficient_scope` marks the user's grant (`needsMoreScope()`, `stepUpScopes()`), and the next connect asks for the scopes already granted plus the challenged ones. The mark is kept in the `step_up_scope` column of the client tables migration. A step-up is tried once per scope: the grant keeps what its sign-in asked for (`requested_scope`), and a challenge for scopes already asked for marks nothing, so there is no redirect loop. Tables created by a pre-release of 2.2 lack that column: `mcp check` says so (roll back and migrate again). +- MCP client discovery: a server whose unauthenticated probe needs no sign-in is still discovered through its well-known URLs; a server of the 2025-03-26 revision without protected resource metadata uses its origin as the authorization server; a token answer without `scope` keeps the scopes asked for. +- The client side of the official MCP conformance suite runs in CI next to the server side (`tests/Conformance/run-client.sh`, no Docker needed), with its expected failures listed with their reasons. See `docs/conformance.md`. +- `ToolValidation::checkPrompt()`: the Validator check for the arguments of a prompt, reported as the error of `prompts/get`. +- `docs/features.md`: an overview of what the plugin offers, with a link to the page for each part. +- MCP client (`Mcp.clients`): call the tools, resources and prompts of other MCP servers with `McpClients::get('name')`, over HTTP with a token or headers, or a local server over stdio, with `tools.only` and `tools.except`, `timeout` and `protocolVersion` per client. User mode (`'auth' => 'user'`) calls a server on behalf of each user after an OAuth sign-in: discovery (RFC 9728, RFC 8414), dynamic client registration, PKCE, connect and callback routes, tokens stored encrypted in the plugin's tables (migration shipped), refreshed before expiry (one request at a time per user) and revoked on `disconnect()`. Addresses a remote server names go through a guard against server-side request forgery. A configured `clientSecret` with discovery needs `issuer`, and is only sent to that authorization server. `mcp check` reports clients on a new `Clients` line. See `docs/mcp-client.md`. +- 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 (only with `Mcp.apps.enabled` on; a 2.1 hook that enables the extension keeps working), tools with an app never go behind the tool catalog, and their audit records carry `app=1`, refused calls included; `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`); a tool that asks the user for input ends its call with a tool error instead of making the client re-send the batch. `Mcp.catalog.maxResultBytes` (64 KiB) caps what one `find_tools` or `call_tools` answer holds: a result that does not fit says its tool ran, and the calls after it are not run. `find_tools` also searches allowed values and nested arguments of the input schemas. `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 (the strings `"false"`, `"0"`, `"off"`, `"no"` and `""` are off) or a callback (given the server name) returns true; on a method it adds to the class's condition; `mcp check` lists what was skipped on a new `Conditions` line. +- `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 (a named server's `auth` needs `mode` and its `authorization` needs `authorizer`, and unknown keys fail), `identity` is never inherited, an inherited `auth` gets the named server's own resource, and the rest is 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 for that server only (it is logged and its routes are not connected; the application, the other servers and `mcp check` keep working, and an invalid entry of `Mcp.clients` stops that client only); `mcp check`, `mcp server` and `mcp inspector` take `--server` (`mcp check --server` still runs the `Servers` line); `McpTestTrait::mcpUseServer()`. +- `bin/cake mcp check` reports the cache hints on a new `Cache hints` line: it says when `tools/list` is sent private because of the authorizer, and warns when `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. +- `Mcp.server.cache` sets the cache hints of the 2026-07-28 protocol (`ttl` and `scope`, sent as `ttlMs` and `cacheScope`), as a default and per method. Off by default (private, not cached). With an authorizer other than `AllowAllToolAuthorizer`, `tools/list` is always sent private. A named server drops the inherited hints with `'cache' => null` or `[]`. +- 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. +- 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) - `bin/cake mcp check` lists the tools the server offers and warns when there is none. diff --git a/README.md b/README.md index 1204cde..bfe433a 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ Built on the official [`mcp/sdk`](https://github.com/modelcontextprotocol/php-sd - Per-tool authorization, including `config/permissions.php` rules through `cakedc/auth`. - `McpTestTrait` to test your tools, and who may call them, from a regular Cake test case. - An audit log of MCP calls (`Mcp.audit`, off by default): who called which tool, with which arguments, and how it ended, to a log scope or your own table. +- Since 2.2: several MCP servers in one application (`Mcp.servers`), a tool catalog that keeps large tool sets out of `tools/list` (`find_tools` and `call_tools`), MCP Apps rendered from Cake templates, tools registered only when a flag is on (`#[McpWhen]`), cache hints, and an MCP client to call other MCP servers, on behalf of each user after an OAuth sign-in if needed. See the [features overview](docs/features.md). ## Requirements @@ -94,15 +95,19 @@ $service->loadAuthenticator('Authentication.Token', [ ## Documentation +- [Features](docs/features.md) - [Installation](docs/installation.md) - [Configuration](docs/configuration.md) - [Writing tools](docs/tools.md) +- [Resources and prompts](docs/resources-and-prompts.md) +- [MCP Apps](docs/apps.md) - [Authentication](docs/authentication.md) - [OAuth](docs/oauth.md) - [Authorization](docs/authorization.md) - [Testing your tools](docs/testing.md) - [stdio](docs/stdio.md) - [Connecting clients](docs/clients.md) +- [Calling other MCP servers](docs/mcp-client.md) - [Troubleshooting](docs/troubleshooting.md) - [Protocol conformance](docs/conformance.md) diff --git a/composer.json b/composer.json index 8b94eea..b9a0f55 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,8 @@ "psr/cache": "^2.0 || ^3.0" }, "suggest": { + "cakephp/bake": "Generates MCP tools, resources, prompts and apps with their tests (bin/cake bake mcp_tool, mcp_resource, mcp_prompt, mcp_app)", + "cakephp/migrations": "Creates the tables of the MCP client's user mode (bin/cake migrations migrate -p CakeDC/Mcp)", "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)", @@ -62,7 +65,7 @@ "test": "phpunit", "cs-check": "phpcs --colors -p", "cs-fix": "phpcbf --colors -p", - "stan": "phpstan analyse --no-progress" + "stan": "phpstan analyse --no-progress --memory-limit=1G" }, "config": { "sort-packages": true, diff --git a/config/Migrations/20261120120000_CreateMcpClientTables.php b/config/Migrations/20261120120000_CreateMcpClientTables.php new file mode 100644 index 0000000..3c6d9f4 --- /dev/null +++ b/config/Migrations/20261120120000_CreateMcpClientTables.php @@ -0,0 +1,82 @@ +table('mcp_client_connections') + ->addColumn('connection_key', 'string', ['limit' => 64, 'null' => false]) + ->addColumn('client', 'text', ['null' => false]) + ->addColumn('user_id', 'text', ['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]) + // The scopes a server asked this user for with `403 insufficient_scope`, which the next connect asks + // the authorization server for (scope step-up). + ->addColumn('step_up_scope', 'text', ['null' => true]) + // The scopes the sign-in that made this grant asked for: a step-up never asks again for scopes the + // authorization server was already asked for and did not grant (a retry limit, so no redirect loop). + ->addColumn('requested_scope', 'text', ['null' => true]) + // The request refreshing the grant, so that two requests never send the same refresh token. + ->addColumn('refresh_claim_id', 'string', ['limit' => 36, 'null' => true]) + ->addColumn('refresh_claimed_at', 'datetime', ['null' => true]) + ->addColumn('created', 'datetime', ['null' => false]) + ->addColumn('modified', 'datetime', ['null' => false]) + ->addIndex(['connection_key'], ['unique' => true]) + ->create(); + + $this->table('mcp_client_registrations') + ->addColumn('registration_key', 'string', ['limit' => 64, 'null' => false]) + ->addColumn('client', 'text', ['null' => false]) + ->addColumn('issuer', 'text', ['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(['registration_key'], ['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/docs/apps.md b/docs/apps.md new file mode 100644 index 0000000..4dd19a5 --- /dev/null +++ b/docs/apps.md @@ -0,0 +1,141 @@ +# 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. If `Mcp.server.configure` +already enables the extension (`$builder->enableExtension(new McpApps())`, as +a 2.1 application could), that keeps working, with or without this setting. +Leaving app-only tools out of `tools/list` for clients that do not render apps +happens only with `Mcp.apps.enabled` on. + +## 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. + +`UiResourceContentMeta` also has `domain`, a dedicated origin for the page's +sandbox, for pages that need a stable origin (an OAuth callback, a CORS policy +or an API key allowlist). The MCP Apps extension leaves its format to each host +(a hash-based subdomain of the host's own domain, or one derived from your +URL), so the plugin does not make one up: without `domain` the host uses its +default sandbox origin, usually one per conversation. Set it from the host's +documentation when you need it: + +```php +new UiResourceContentMeta(domain: 'a904794854a047f6.claudemcpcontent.com') +``` + +## 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. The tool +catalog leaves every tool with an app out, even when a pattern of +`Mcp.catalog.tools` matches it: `find_tools` does not offer it, `call_tools` +does not run it, and it stays in `tools/list`, where the host reads its +`_meta.ui` (an app-only tool for clients that render apps, a tool that links to +an app for every client). `bin/cake mcp check` names the tools with an app that +a pattern matched on its `Catalog` line. + +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`). The page itself is a resource: anyone who +may call the endpoint can read it with `resources/read`, unless your authorizer +also implements `ResourceAuthorizerInterface` (see +[Resources and prompts](authorization.md#resources-and-prompts)). Keep data out of the page template +and load it with a tool call from the page, where the authorizer and the scopes +apply. 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 the server does not announce apps (neither `Mcp.apps.enabled` nor +the hook). It also reads each page and warns about one that does not render +(a missing template, a template that throws). In tests, call the resource method directly to check the page (the +test `bake mcp_app` writes loads the plugin for the page's layout), and the +tools with `McpTestTrait` as usual. Empty `_meta.ui`, `csp` and `permissions` +of a page are left out, never sent as empty lists. diff --git a/docs/authentication.md b/docs/authentication.md index 84f0fe8..fb2301a 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -97,7 +97,10 @@ in the `identity` attribute, so the plugin reads it unchanged. Two defaults of permission rule for the endpoint and its protected resource metadata (used by [OAuth](oauth.md)) in your `config/permissions.php`, with `bypassAuth` so the request reaches the plugin, which then does its own 401 and per-tool - authorization. `McpConfig::rbacPermissions()` returns that rule: + authorization. `McpConfig::rbacPermissions()` returns that rule (and, with + a user mode client in `Mcp.clients`, two more: one for its sign-in routes, + and one with `bypassAuth` for its `client.json`, which authorization servers + fetch without a session): ```php // config/permissions.php @@ -110,7 +113,8 @@ in the `identity` attribute, so the plugin reads it unchanged. Two defaults of ]; ``` - It is this rule, which you can also write by hand: + The first is this rule, which you can also write by hand (the client rules + are in [Calling other MCP servers](mcp-client.md)): ```php [ diff --git a/docs/authorization.md b/docs/authorization.md index 572ba8b..817bbf9 100644 --- a/docs/authorization.md +++ b/docs/authorization.md @@ -67,8 +67,77 @@ With the [audit log](configuration.md#audit-log) on, the record of a denied call says `denied`, so you can tell it from an unknown tool even though the caller cannot. -Resources and prompts are not covered by the tool authorizer: any identified -caller can list and read them. +## Resources and prompts + +An authorizer that only implements `ToolAuthorizerInterface` leaves resources +and prompts open: any identified caller can list, read and get them, as in 2.1. +To decide who reads which resource and gets which prompt, implement one or both +of these interfaces in the same class: + +```php +use CakeDC\Mcp\Authorization\PromptAuthorizerInterface; +use CakeDC\Mcp\Authorization\ResourceAuthorizerInterface; +use CakeDC\Mcp\Authorization\ToolAuthorizerInterface; + +final class AppAuthorizer implements + ToolAuthorizerInterface, + ResourceAuthorizerInterface, + PromptAuthorizerInterface +{ + public function canCall(mixed $identity, string $tool): bool + { + return $identity !== null; + } + + public function canReadResource(mixed $identity, string $uri): bool + { + // A concrete URI read through a template, or the template's own URI + // (`orders://{number}`) when templates are listed or completed. + return !str_starts_with($uri, 'payroll://') || ($identity['role'] ?? null) === 'hr'; + } + + public function canGetPrompt(mixed $identity, string $name): bool + { + return $name !== 'payroll_summary' || ($identity['role'] ?? null) === 'hr'; + } +} +``` + +The URI is the one the client sent, not a canonical form. A template variable +takes any text but `/`, so `orders://2001`, `orders://02001`, +`orders://2001?x=1` and `orders://2001 ` (with a trailing space) all reach the +handler of `orders://{number}`, and a handler that reads the number as an +integer loads the same order for each. Do not deny one record by its exact +URI: deny by default and allow what the caller may read, decide by prefix as +above, or read the variable the way the handler does. + +What a denied resource or prompt does: + +- It is left out of `resources/list`, `resources/templates/list` and + `prompts/list`. +- Reading it (`resources/read`, also a URI a template matches), subscribing + to it or unsubscribing from it answers exactly like an unknown URI, getting + a denied prompt answers exactly like an unknown prompt, and a completion + for a denied prompt or template answers exactly like one for an unknown + reference, so a caller cannot tell it exists. +- A URI that a template serves is checked twice: the concrete URI + (`orders://1001`) and the template's URI (`orders://{number}`). Denying + either one denies the read, the subscription and the completion, so + denying a template denies every URI it serves. +- A `subscriptions/listen` stream (2026-07-28 revision) never carries a + `notifications/resources/updated` for a resource the caller cannot read, + even when the client listed its URI in `resourceSubscriptions`. It asks + the authorizer for each update, with the identity the stream was opened + with, also in a server where other requests of the same worker run while + the stream waits. +- [MCP App](apps.md) pages are resources and follow the same rule. +- With [cache hints](configuration.md#keys), the lists and `resources/read` + are always sent private, as `tools/list` is. + +`bin/cake mcp check` says on its `Authorizer` line whether resources and +prompts are covered. Test the rules with the `assertMcpResourceNotListed()`, +`assertMcpResourceDenied()`, `assertMcpPromptNotListed()` and +`assertMcpPromptDenied()` assertions of [McpTestTrait](testing.md). ## RbacToolAuthorizer (cakedc/auth) @@ -122,6 +191,41 @@ and configure the authorizer by instance. Identities that are not arrays or `ArrayAccess` objects are denied. +### Resources and prompts with Rbac + +`RbacToolAuthorizer` also checks resource `X` as plugin `CakeDC/Mcp`, +controller `Resources`, action `X` (the URI read, or the template's URI when +templates are listed or completed), and prompt `X` as controller `Prompts`, +action `X`. It does so only when at least one rule names plugin `CakeDC/Mcp` +and controller `Resources` (or `Prompts`), exactly or in a list. With no such +rule, every resource (or prompt) stays open, so a 2.1 rule set changes nothing, +and neither does a rule for a controller of your own that is also called +`Resources`. + +```php +[ + 'role' => 'editor', + 'plugin' => 'CakeDC/Mcp', + 'controller' => 'Resources', + 'action' => ['app://rules', 'orders://{number}'], +], +[ + // the orders a user may read, through the template + 'role' => 'editor', + 'plugin' => 'CakeDC/Mcp', + 'controller' => 'Resources', + 'action' => '*', + 'allowed' => fn ($user, $role, $request): bool + => str_starts_with((string)$request->getParam('action'), 'orders://'), +], +['role' => 'editor', 'plugin' => 'CakeDC/Mcp', 'controller' => 'Prompts', 'action' => '*'], +``` + +Actions match exactly, so the concrete URIs of a template need a `'*'` rule +with an `allowed` callback, as above. Reading `orders://1001` needs both +rules: one for the template's URI and one for the concrete URI. Once the `Resources` rules are on, the +host-wide wildcard rules of the next section grant resources too. + ### Warning: host rules without a plugin key cakedc/auth rules only constrain the keys they list. A host rule that has no diff --git a/docs/configuration.md b/docs/configuration.md index 2968dce..5d30ad3 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -13,10 +13,15 @@ want to change; everything else keeps its default. These are the defaults 'title' => null, 'description' => null, 'websiteUrl' => null, + 'icons' => null, 'instructions' => null, + 'cache' => null, 'configure' => null, ], 'discovery' => ['scanDirs' => ['src/Mcp'], 'excludeDirs' => [], 'cache' => '_cake_mcp_'], + 'schema' => ['normalize' => false], + 'catalog' => ['enabled' => false, 'tools' => [], 'maxCalls' => 5, 'maxResultBytes' => 65536], + 'apps' => ['enabled' => false], 'session' => ['cache' => 'mcp_sessions', 'ttl' => 3600], 'http' => ['allowedHosts' => null, 'allowedOrigins' => [], 'maxBodyBytes' => 4194304], 'identity' => ['required' => true, 'attribute' => 'identity', 'scopes' => null], @@ -40,19 +45,38 @@ want to change; everything else keeps its default. These are the defaults ], ], 'stdio' => ['identity' => null, 'trusted' => true], + 'audit' => [ + 'enabled' => false, + 'methods' => ['tools/call'], + 'log' => true, + 'arguments' => true, + 'redact' => ['password', 'token', 'secret'], + 'maxLength' => 200, + ], ], ``` +`Mcp.servers` (several servers), `Mcp.clients` and `Mcp.client` (the MCP +client) have no defaults of their own; they are described below. + ## Keys - `route`: path of the HTTP endpoint. `false` (or an empty string) connects no route. - `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.icons`: optional icons clients show for the server, a list of `['src' => 'https://app.example.com/icon.png', 'mimeType' => 'image/png', 'sizes' => ['48x48'], 'theme' => 'light']` (only `src` is required; `theme` is `light` or `dark`). `null` sends none. An entry without `src` fails with a message naming the setting. - `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: `tools/list` is always sent private when the authorizer is not `AllowAllToolAuthorizer` (it can give users different tools) or `apps.enabled` is on (a client that renders MCP Apps gets the app-only tools listed, and another does not), whatever `server.cache` or a policy set in `server.configure` says, and keep `resources/read` private when a resource depends on who reads it. `bin/cake mcp check` says so on its `Cache hints` line, and warns when `resources/read` is public. A named server inherits `server.cache` and replaces it whole when it sets it; it writes `'cache' => null` or `'cache' => []` in its `server` section for no hints. +- `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`. +- `catalog.maxResultBytes`: the most JSON bytes the tools one `find_tools` answer lists, and the results one `call_tools` answer holds, may take, a positive integer. Default `65536`. A `call_tools` result that does not fit is replaced by a note that the tool ran, and the calls after it are not run. See [Tools](tools.md#tool-catalog). +- `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. +- `discovery.excludeDirs`: directories to skip while scanning, relative to each `scanDirs` entry: with `'scanDirs' => ['src/Mcp']`, `'excludeDirs' => ['Admin']` skips `src/Mcp/Admin` (and any directory named `Admin` below it), while `['src/Mcp/Admin']` skips nothing. - `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 whose default is `null` loses `"null"` from its `type` and its `enum`, and that `default` is dropped. The same goes for the properties of nested objects and of array items, with their own `required`. 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`. @@ -67,6 +91,7 @@ want to change; everything else keeps its default. These are the defaults - `stdio.identity`: closure returning the identity for `bin/cake mcp server`. - `stdio.trusted`: skip per-tool authorization for stdio. - `audit`: the audit log of MCP calls, off by default. See [Audit log](#audit-log). +- `clients`, `client`: other MCP servers your application calls. See [MCP clients](#mcp-clients). ## Mcp.auth @@ -143,9 +168,265 @@ the server info (a `setServerInfo()` call in the callable is ignored; use the discovery when `discovery.scanDirs` has a directory. The authorizer applies to every tool, including the ones added here. -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. +A registry set here (`setRegistry()`) can be any +`Mcp\Capability\RegistryInterface`, as in 2.1. The plugin uses it through that +interface: it removes `#[McpWhen]` elements from it, links `#[McpApp]` tools in +it, runs the tool catalog on it and asks it, for the audit, whether a tool +exists. With the tool catalog on, request handlers, a reference +handler or a schema validator added here would not apply to the tools +`call_tools` runs, so the server refuses those too; put such rules in an +authorizer. A tool added here cannot be called `find_tools` or `call_tools` +while the catalog is on. + +A cache policy set here follows the same rule as `server.cache`: with an +authorizer other than `AllowAllToolAuthorizer` the list depends on who asks, so +the plugin sends `tools/list` private even when the policy says +`CacheScope::Public`. + +## 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'], + // A sibling of src/Mcp: discovery is recursive, so src/Mcp/Admin would also + // be scanned by the default server. + 'discovery' => ['scanDirs' => ['src/McpAdmin']], + 'auth' => ['mode' => 'oauth', 'scopes' => ['default' => ['admin']]], + ], + ], +], +``` + +Each named server needs a `route`. `'route' => false` makes a server that is +served over stdio only: no HTTP route and no metadata route are connected, +`bin/cake mcp server --server ` serves it, `bin/cake mcp check --server +` says so on its `Endpoint` line, and it does not inherit the default +server's `auth` (stdio takes no tokens). For example a server of maintenance +tools for developers only: + +```php +'servers' => [ + 'maintenance' => [ + 'route' => false, + 'discovery' => ['scanDirs' => ['src/McpMaintenance']], + ], +], +``` + +What a named server does not set comes from the default +server, in three ways: + +- `auth`, `authorization`, `discovery`, `server.configure` and `server.cache` 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, except that an inherited `auth` gets the named + server's own resource (see below). +- `identity` is never taken from the default server. A named server that does + not set it requires an identity (the plugin's default), even next to a public + default server; when it sets it, it is replaced whole, so the keys it leaves + out (`attribute`, `scopes`) go back to the plugin's defaults too, not to the + default server's. +- Every other section (`server`, `http`, `session`, `stdio`, `audit`, `schema`, + `catalog`, `apps`) is merged key by key, so `'server' => ['name' => ...]` + keeps the default server's version and instructions. Two keys of `server` + are values, not sections: `server.configure` and `server.cache` are replaced + whole when the named server sets them, so `'cache' => ['methods' => [...]]` + does not keep the default server's `ttl`. Turning the catalog or + apps on in the default server turns them on in every named server that does + not set them. + +A replaced section starts again from the plugin's defaults, which are the open +ones, so the key that decides how open it is must be written: a named server's +`auth` needs `mode` and its `authorization` needs `authorizer`. Without them +(`'authorization' => ['rbac' => $rules]` alone, or `'auth' => ['scopes' => ...]` +alone) the server is not served. An unknown key at the top level of a named +server or inside its `authorization` fails the same way, so a typo such as +`authorisation` never leaves the inherited section in place. A named server +whose security section is `null` or `[]` (an unset `env()` value, for example) +fails instead of falling back to the defaults. + +A mistake in one entry of `Mcp.servers` (no `route`, a name that is not a slug, +a section that is `null`) stops that server only. The plugin logs it as an +error, once per PHP process (under PHP-FPM that is once per request; a +long-running worker logs it once), to the loggers that take messages without a +scope (the application skeleton's `error` log) and to those of the `mcp` +scope, and does not connect its routes, so its URL reaches no MCP server. A +typo inside `discovery`, `identity` or `authorization` is such a mistake. An +entry named `default` is ignored, and logged: the top-level `Mcp` config is +the default server. +The rest of the application and the other servers keep working, and +`bin/cake mcp check` fails with a `Server ` line that names the mistake. + +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 is its own URL: derived from `App.fullBaseUrl` and its +route, or, when it inherits an `auth` that sets `resource`, that URL with the +default server's route replaced by its own (`https://example.com/mcp` becomes +`https://example.com/mcp/admin`). In `oauth` mode declare that URL in +`OAuthServer.resources` as well. A route parameter that `auth.resource` puts +in its host (`'resource' => 'https://{tenant}.example.com/mcp'`) is served only +in lowercase, as host names are compared: `/mcp/ACME` answers 404 rather than +share the resource and audience of `/mcp/acme`. Tokens stay 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 + write the same `auth.resource` in their own `auth`. +- In `external` mode tokens are accepted by audience, which is the resource + when `external.audience` is not set. An inherited `auth` that sets + `external.audience` is refused, because an audience cannot be derived for + another server: give that server its own `auth` with 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. + +Discovery is recursive, so keep each server's tools in its own directory, side +by side (`src/Mcp` and `src/McpAdmin`), not one inside the other. A server whose +scan directory holds another server's registers that server's tools, resources +and prompts too, unless its `discovery.excludeDirs` names the inner directory +relative to its own (`'excludeDirs' => ['Admin']` for `src/Mcp/Admin`). + +`bin/cake mcp check` checks every server and fails when two share a route or a +resource, and warns when a scan directory holds another server's. `mcp check`, `mcp server` and `mcp inspector` take +`--server ` (`mcp check --server ` still runs the `Servers` line +across all servers), and tests pick a server with `mcpUseServer('admin')`. + +### Routes with parameters + +A named server can serve many values of one route, such as one per tenant: + +```php +'servers' => [ + 'tenants' => [ + 'route' => '/mcp/t/{tenant}', + 'discovery' => ['scanDirs' => ['src/McpTenant']], + 'auth' => ['mode' => 'external', 'external' => ['issuer' => 'https://login.example.com']], + ], +], +``` + +Every value shares the server's config and tools. A parameter is a whole path +segment, `{name}` with letters, digits and `_`, each name once, and not a name +Cake routing uses (`server`, `plugin`, `controller`, `action`, `prefix`, +`pass`, or one starting with `_`); its values are +slugs (letters, digits, `-` and `_`), and any other path is not routed to the +server. A pattern that breaks these rules stops that server, and +`bin/cake mcp check` fails on it; its `Endpoint` line shows the pattern. + +The value reaches tools as a request param (`$request->getParam('tenant')`) +and through the `CakeDC\Mcp\Server\McpRoute` service, which a tool can take +in its constructor: + +```php +public function __construct(private McpRoute $route, private CurrentIdentity $identity) +{ +} + +#[McpTool(name: 'list_invoices')] +public function invoices(): array +{ + $tenant = (string)$this->route->get('tenant'); + // The caller chooses the value in the URL: check that it is theirs. + if (!$this->memberships->belongsTo($this->identity->get(), $tenant)) { + throw ToolError::message('You are not a member of this tenant.'); + } + + return $this->invoices->forTenant($tenant); +} +``` + +The value is input the caller chooses, like any part of a URL. Check in the +tools (or in your authorizer) that the identity belongs to it, in every mode: +an audience bound to the value only proves the token was issued for that +value, not that its user may have it, and host mode binds nothing to it at +all (`bin/cake mcp check` warns on such a server). + +In `oauth` and `external` modes each value is its own protected resource: the +resource (`https://app.example.com/mcp/t/acme`) and the protected resource +metadata URL (`/.well-known/oauth-protected-resource/mcp/t/acme`) are derived +with the value of the request, so a token issued for one tenant is refused for +another. A configured `auth.resource` or `external.audience` must hold the +same `{tenant}` placeholder (`'audience' => 'api://mcp/{tenant}'`), every +parameter of the route when it has several, kept apart by a character a value +cannot hold (`api://mcp/{org}/{team}`, not `{org}-{team}`, where `x-y`, `z` +and `x`, `y-z` would give the same audience). A fixed one would accept a token +for one value on another, so it stops that server: its routes are not +connected, the mistake is logged, and `bin/cake mcp check` fails on it, as +with any other mistake in a named server. In `oauth` mode, declare in +`OAuthServer.resources` the resource of each value you serve. Sessions of one +value are kept apart from the others, audit records carry the values (a +`route` field, `route=tenant:acme` on the log line), and tests give them with +`mcpUseServer('tenants', ['tenant' => 'acme'])`. Parameters are for named +servers only: with a `Mcp.route` that has one, the default server answers +every request with an error (`500`, the reason logged), and `bin/cake mcp +check` fails on it. + +## MCP clients + +`Mcp.clients` names the MCP servers your application calls, and `Mcp.client` +holds settings shared by all of them. They are not per server: `Mcp.servers` +does not change them. The guide is [Calling other MCP servers](mcp-client.md). + +```php +'Mcp' => [ + 'clients' => [ + 'github' => ['url' => 'https://api.githubcopilot.com/mcp/', 'token' => env('GITHUB_MCP_TOKEN')], + 'linear' => ['url' => 'https://mcp.linear.app/mcp', 'auth' => 'user'], + ], + 'client' => ['route' => '/mcp-client'], +], +``` + +Each client (a mistake fails with a message naming the key, and an unknown key +is refused). A mistake in one client stops that client only: it is logged as +an error the same way as a server's, the other clients and the application keep working, and +`bin/cake mcp check` fails on it. The settings: + +- `clients..url`: the server's HTTP address. https, or plain http for this machine or with `allowInsecure`. Set `url` or `command`, not both. +- `clients..command`: a local server to start, spoken to over stdio. +- `clients..args`: the command's arguments, a list of strings. +- `clients..env`: environment variables for the command, on top of `PATH`, `HOME`, `USER`, the locale and the temp directories (nothing else of your environment is passed). +- `clients..cwd`: the command's working directory. +- `clients..token`: sent as `Authorization: Bearer `. Set but empty fails. Spaces and line breaks around it are dropped (a secret file read whole ends with one); a token with other characters a header cannot carry fails, without being quoted. A callable returning the token string is called for each request instead (for tokens that rotate); `bin/cake mcp check` does not call it. See [MCP client](mcp-client.md#app-mode-one-set-of-credentials). +- `clients..headers`: headers sent with every HTTP request, name => value. +- `clients..auth`: `app` (the default, the application's own credentials), `user` (each user signs in with OAuth; needs `url`, takes no token) or `client_credentials` (the application gets its own OAuth token with `clientId` and `clientSecret` from `issuer` or `tokenUrl`; needs `url`, takes no token; see [MCP client](mcp-client.md#the-applications-own-oauth-token)). +- `clients..timeout`: seconds for the connection and each request, and in user mode for all the requests of one sign-in step together. Default `30`. +- `clients..tools.only`: patterns (`fnmatch()`) of the tools the client may list and call. Empty allows all. +- `clients..tools.except`: patterns of the tools it may not. Wins over `only`. +- `clients..protocolVersion`: the protocol revision to ask for, such as `2025-06-18`. Default: the SDK's. +- `clients..allowInsecure`: `true` accepts plain http to a host other than this machine for the configured addresses. Default `false`. +- `clients..cache`: the name of a Cake cache config in which results (`tools/list`, `resources/list`, `resources/templates/list`, `prompts/list`, `resources/read` and `server/discover`) that carry 2026-07-28 cache hints are kept for their ttl: `private` ones per user in user mode and per client in app mode, `public` ones per client. Default `null`: no caching. An unknown cache config fails, and so does a `cache` on a stdio client. See [MCP client](mcp-client.md#caching-lists-and-reads). +- `clients..registration`: user mode, without a `clientId`: `'auto'` (default) uses the client's Client ID Metadata Document (`//client.json`) when the authorization server supports it and `App.fullBaseUrl` is public https, and dynamic registration otherwise; `'metadata'` always uses the document; `'dynamic'` always registers. See [MCP client](mcp-client.md#client-id-metadata-document). +- `clients..allowPrivateNetwork`: `true` lets the OAuth endpoints learned for this client resolve to private, loopback or link-local addresses (an authorization server on your own network). Plain http for them also needs `allowInsecure`. Other clients are not affected, and `bin/cake mcp check` warns. Default `false`. See [MCP client](mcp-client.md#which-addresses-the-client-calls). +- `clients..clientId`: user mode and `client_credentials` (required there): the OAuth client id the authorization server's owner gave you. Without it, the application registers itself (dynamic client registration). +- `clients..clientSecret`: user mode: that client's secret, if it has one; required with `client_credentials`. +- `clients..scopes`: user mode and `client_credentials`: the scopes to ask for, sent as written (with `client_credentials`, none means the authorization server's default); in user mode, after a `403 insufficient_scope`, the next connect adds the scopes the server named (see [MCP client](mcp-client.md#when-the-server-asks-for-more-scope)). Default: the ones the server names, plus `offline_access` when the authorization server or the server lists it (so a refresh token is issued). +- `clients..authorizationUrl`, `clients..tokenUrl`, `clients..revocationUrl`: user mode: the authorization server's endpoints, to skip discovery (for example on your own network). `authorizationUrl`, `tokenUrl` and `clientId` go together. They are trusted like `url`. With `client_credentials`, `tokenUrl` alone replaces `issuer`. +- `clients..issuer`: the issuer the authorization server names itself by (for Keycloak, `https://sso.example.com/realms/`). When set, the `iss` of each sign-in response must match it, and with discovery the MCP server must name exactly this authorization server or the sign-in fails. Required with `clientSecret` and discovery (no configured endpoints), so the secret only goes to the server that issued it. Default `null`: the client does not know the issuer and does not compare `iss`. With `client_credentials` (and no `tokenUrl`), the token endpoint is read from this issuer's metadata, which must name the same issuer. + +Shared settings (a key that is not one of these, or a value of the wrong type, is logged and fails `bin/cake mcp check`): + +- `client.route`: the path under which user mode clients get their connect and callback routes (`//connect`, `//callback`). Default `/mcp-client`. Connected only when a client uses user mode. A value that is not a path (`false`, `''`, `'/'`) connects nothing, is logged, and fails `bin/cake mcp check`. +- `client.store`: the class of the `ConnectionStoreInterface` that keeps user grants. Default `TableConnectionStore` (the plugin's tables; run `bin/cake migrations migrate -p CakeDC/Mcp`). +- `client.encryptionKey`: the key tokens and client secrets are encrypted with, at least 32 bytes. Default `null`: `Security.salt`. +- `client.name`, `client.version`: how the application introduces itself to servers and authorization servers. Default `CakePHP MCP Client`, `1.0.0`. +- `client.refreshLeeway`: seconds before expiry when an access token is refreshed. Default `60`. +- `client.maxResponseBytes`: the largest answer read from an address a remote server named. Default `1048576` (1 MiB). Those addresses are asked for uncompressed answers (`Accept-Encoding: identity`) and a compressed one is refused, so the cap applies to what is read. +- `client.identityAttribute`: the request attribute that holds the logged-in user on the connect and callback routes. Default `identity`. +- `client.proxy`: a proxy URL (`http`, `https` or `socks5h`, no path) that every client HTTP request goes through, the addresses remote servers name included, except a configured `url` on this machine, which is reached directly. `NO_PROXY` is not followed. Default `null`: no proxy. The guard on learned addresses then keeps its name checks but no longer pins the connection to an address, because the proxy resolves the name. See [MCP client](mcp-client.md#behind-an-outbound-proxy). ## Caches @@ -216,7 +497,10 @@ Who the limit counts: authentication, slows down floods of requests without a token. `McpConfig::isEndpoint()` matches the MCP route and its protected resource -metadata route. Use a cache shared by every PHP worker (Redis, for example): +metadata route, reading the path as the router does (`/%6Dcp` is `/mcp`). +Once routing has run it asks the router: a route of your application wins +over a server's pattern, and a route you connect yourself to the plugin's +controller counts. Use a cache shared by every PHP worker (Redis, for example): with a per-process cache every worker counts on its own. A request refused with `429` never reaches the endpoint, so the [audit log](#audit-log) does not record it. @@ -258,20 +542,24 @@ named in the `mcp` log) and makes `bin/cake mcp check` fail. | `arguments` | the arguments, redacted and cut | | `error` | the error message, for an outcome that is not `ok`; for `tool_error`, the first text the tool returned (kept even with `audit.arguments` off: a tool may repeat its input there) | | `durationMs` | how long the call took, `null` when it is not known | +| `via` | `call_tools` when the tool catalog ran the call; left out otherwise (`via=call_tools` on the log line) | +| `app` | `true` for a call of an app-only tool, refused calls included; left out otherwise (`app=1` on the log line) | +| `server` | the named server that took the call; left out for the default server (`server=admin` on the log line) | +| `route` | the values of the parameters of the server's route, such as `{"tenant": "acme"}`; left out when the route has none (`route=tenant:acme` on the log line) | | Outcome | When | Log level | |---|---|---| | `ok` | the call worked | `info` | | `tool_error` | the tool answered with an error (`ToolCallException`, `ToolError::invalid()`) | `notice` | | `invalid` | an unknown tool or invalid arguments | `notice` | -| `denied` | the authorizer denied the tool | `warning` | +| `denied` | the authorizer denied the tool, or the resource read or prompt got (when `Mcp.audit.methods` lists `resources/read` or `prompts/get`) | `warning` | | `error` | the tool threw, or another JSON-RPC error | `warning` | | `unauthorized` | `401` from authentication, before the server runs | `warning` | | `insufficient_scope` | `403`: the access token lacks a scope | `warning` | -A denied tool still gets the same answer as an unknown one (see -[Authorization](authorization.md#what-a-denied-caller-sees)); only the record -tells them apart. +A denied tool, resource or prompt still gets the same answer as an unknown one +(see [Authorization](authorization.md#what-a-denied-caller-sees)); only the +record tells them apart. Limits: @@ -283,10 +571,10 @@ Limits: time the person took to answer. In the stateless revision every round that still waits for input is skipped, and the call is recorded once, when it finishes. -- To tell a denied tool from an unknown one, the audit hands the SDK the - tool registry it keeps (tools are then loaded when the server is built). - If `server.configure` sets a registry of its own, an unknown tool that the - authorizer refuses is recorded as `denied`. +- To tell a denied tool from an unknown one, the audit asks the server's + registry (the plugin's, or the one `server.configure` set) whether the tool + exists: an unknown tool is recorded as `invalid`, even when the authorizer + would refuse it. Tools are loaded when the server is built. - The access token never appears in a record. - Over stdio the identity is `stdio.identity`, and a trusted server (`stdio.trusted`) denies nothing. diff --git a/docs/conformance.md b/docs/conformance.md index 225d15d..047fe10 100644 --- a/docs/conformance.md +++ b/docs/conformance.md @@ -34,6 +34,36 @@ The container uses the PHP version of the host that runs the script (8.4 in CI), because it runs the `vendor/` directory installed there. Set `CONFORMANCE_PHP` to use another one. +## The client side + +`tests/Conformance/run-client.sh` runs the client scenarios of the same suite +against the plugin's MCP client: the suite starts its own scenario servers +(and authorization servers) on this machine and runs +`php tests/Conformance/client.php `, which uses `McpClients` the +way an application does. It needs Node.js 22, PHP and the Composer +dependencies, not Docker: + +```bash +tests/Conformance/run-client.sh # both protocol revisions +tests/Conformance/run-client.sh 2026-07-28 # one revision +``` + +For the sign-in scenarios the script runs the user mode sign-in without a +browser (the suite's authorization server approves at once), with an +in-memory token store, and with `allowPrivateNetwork` and `allowInsecure` on +the client, because those servers are on `localhost` over plain http; an +application would not set them for a server on the internet. + +`baseline-client-.yml` lists the client scenarios expected to fail, +with the reason: elicitation and the input requests of an +`InputRequiredResult`, which the client does not answer; the Client ID +Metadata Document scenario, which expects a client id the suite names; a scope +step-up server that challenges only after the client's probe; and two +behaviours of the SDK itself (the version retry after an +`UnsupportedProtocolVersion` error, and the `Mcp-Param` header of an empty +string). Results go to `tests/Conformance/results-client/`. The CI workflow +runs it in the same job as the server side. + ## How it is set up - `webroot/index.php` serves the test application with the plugin's `/mcp` diff --git a/docs/features.md b/docs/features.md new file mode 100644 index 0000000..752157e --- /dev/null +++ b/docs/features.md @@ -0,0 +1,98 @@ +# Features + +What the plugin offers, and where each part is described. The plugin runs on +the official MCP PHP SDK (`mcp/sdk`), so everything the SDK implements is +available too; those parts are listed at the end. + +## Servers + +- One endpoint at `Mcp.route`, or several servers in one application, each with + its route, tools, authentication and authorizer: + [Several servers](configuration.md#several-servers), also one per value of a route parameter + (`/mcp/t/{tenant}`, [Routes with parameters](configuration.md#routes-with-parameters)) and servers for + stdio only (`'route' => false`). +- Local clients over stdio (`bin/cake mcp server`): [stdio](stdio.md). +- Cache hints for the 2026-07-28 protocol revision (`Mcp.server.cache`): + [Configuration](configuration.md#keys). +- Anything else the SDK builder offers, through `Mcp.server.configure`: + [Using the SDK builder](configuration.md#using-the-sdk-builder). + +## Tools, resources and prompts + +- Declared with the SDK's attributes on plain classes in `src/Mcp/`, with + constructor injection from Cake's container and the caller's identity: + [Writing tools](tools.md). +- Input schemas from PHP types, docblocks and `#[Schema]`, with + `Mcp.schema.normalize` for hosts that reject type arrays: + [Input schemas](tools.md#input-schemas). +- Results as text, structured content and output schemas: + [Results](tools.md#results). +- Errors the model can act on (`ToolError::message()`, `ToolError::invalid()`) + and validation with a Cake `Validator` (`ToolValidation::check()`, and + `checkPrompt()` for prompt arguments): [Errors](tools.md#errors). +- Progress and log notifications from long tools: + [Progress and logs](tools.md#progress-and-logs). +- A searchable tool catalog (`find_tools`, `call_tools`) for servers with many + tools, searching names, descriptions and arguments in any language: + [Tool catalog](tools.md#tool-catalog). +- Registration on a condition, for configuration and feature flags + (`#[McpWhen]`): [Registering only when](tools.md#registering-only-when). +- Generated classes and tests: `bin/cake bake mcp_tool`, `mcp_resource`, + `mcp_prompt`, `mcp_app`: [Generating classes with bake](tools.md#generating-classes-with-bake). +- Resources, resource templates, prompts, completions and every content type, + with who may read and get them: [Resources and prompts](resources-and-prompts.md). + +## MCP Apps + +Interactive pages hosts show next to the conversation, rendered from Cake +templates with the official client inlined, tools linked with `#[McpApp]`, and +app-only tools: [MCP Apps](apps.md). + +## Security + +- Authentication with the application's own login, with OAuth 2.1 sign-in + through `cakedc/cakephp-oauth-server`, or with access tokens of an external + authorization server: [Authentication](authentication.md), [OAuth](oauth.md). +- Scopes per method and per tool, answered with `403 insufficient_scope` and a + challenge the client can act on: [Mcp.auth](configuration.md#mcpauth). +- An authorizer per tool, including `RbacToolAuthorizer` over + `config/permissions.php`, with denied tools answered like unknown ones: + [Authorization](authorization.md). +- Per-resource and per-prompt authorization (`ResourceAuthorizerInterface`, + `PromptAuthorizerInterface`, `RbacToolAuthorizer` rules for `Resources` and + `Prompts`): [Resources and prompts](authorization.md#resources-and-prompts). +- An audit log of calls, refusals included: [Audit log](configuration.md#audit-log). +- Rate limiting, allowed hosts and origins, a body size limit: + [Rate limiting](configuration.md#rate-limiting), [Configuration](configuration.md). +- `bin/cake mcp check`, which reviews the whole setup without network calls: + [Troubleshooting](troubleshooting.md). + +## MCP client + +Named clients that call other MCP servers, with an application credential (a +fixed token, or a callable for tokens that rotate) or with each user's own +account through OAuth (a Client ID Metadata Document or dynamic registration), +behind an SSRF guard for addresses remote servers name, through an outbound +proxy if needed, with a cache for list results that carry cache hints: +[MCP client](mcp-client.md). + +## Testing + +`McpTestTrait` calls tools, gets prompts, reads resources, asks for +completions and lists them all as a given identity, with scopes, on a given +server, and asserts results, structured content, errors, denials, +missing scopes and notifications; `bin/cake mcp inspector` opens the MCP +Inspector: [Testing your tools](testing.md). + +## From the SDK + +Also available, from `mcp/sdk`: resource templates, completions, tool and +resource annotations, icons and `_meta`, every content type (text, image, +audio, embedded resources, resource links), pagination, protocol revisions from +2024-11-05 to 2026-07-28 (with `server/discover`), elicitation, sampling, +logging and resource subscriptions. + +Not yet, because `mcp/sdk` 0.9 has no place for them: icons on resource +templates, the `lastModified` annotation, `_meta` on a single content block, +and completions that see the other arguments already filled in (a completion +provider gets only the value being typed). They will come with the SDK. 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/mcp-client.md b/docs/mcp-client.md new file mode 100644 index 0000000..65c5677 --- /dev/null +++ b/docs/mcp-client.md @@ -0,0 +1,667 @@ +# Calling other MCP servers + +The plugin is also an MCP client. Your application can list and call the tools, +resources and prompts of other MCP servers: a SaaS server with your own API key, +a local server started as a process, or a server where each of your users signs +in with their own account. + +Clients are named in `Mcp.clients` and reached with `McpClients::get()`: + +```php +use CakeDC\Mcp\Client\McpClients; + +$result = McpClients::get('github')->callTool('search_issues', ['query' => 'is:open label:bug']); +``` + +The client is built on the SDK's client (`Mcp\Client`) and its HTTP and stdio +transports. HTTP goes through Cake's HTTP client, so nothing else needs +installing. + +(For connecting Claude and other clients to your own MCP server, see +[Connecting clients](clients.md).) + +## App mode: one set of credentials + +The application calls the server as itself, with a token or headers you +configure: + +```php +// config/app_local.php +'Mcp' => [ + 'clients' => [ + 'github' => [ + 'url' => 'https://api.githubcopilot.com/mcp/', + 'token' => env('GITHUB_MCP_TOKEN'), + ], + 'stripe' => [ + 'url' => 'https://mcp.stripe.com', + 'headers' => ['Authorization' => 'Bearer ' . env('STRIPE_SECRET_KEY')], + 'timeout' => 20, + ], + ], +], +``` + +`token` is sent as `Authorization: Bearer `; `headers` are sent as they +are. A `token` that is set but empty (an `env()` that is not defined) fails +with a message instead of sending no credentials. + +For a token that rotates, or that you read from a vault, give `token` a +callable that returns the token string. It is called for each HTTP request the +client sends, so a new token is used as soon as the callable returns it. When +it returns something that is not a non-empty string, the call fails with a +`ClientException` naming the client. `bin/cake mcp check` never calls it (its +`Clients` line says `token from a callable`). A string is always a token, even +one that is also the name of a PHP function. + +```php +'github' => [ + 'url' => 'https://api.githubcopilot.com/mcp/', + 'token' => fn(): string => Vault::read('github-mcp-token'), +], +``` + +Config files that are cached or exported cannot hold a closure; set such a +client in `config/bootstrap.php` or in your `Application::bootstrap()` with +`Configure::write()`. + +```php +$github = McpClients::get('github'); + +foreach ($github->listTools() as $tool) { + echo $tool->name, ': ', $tool->description, "\n"; +} +$result = $github->callTool('get_issue', ['owner' => 'cakephp', 'repo' => 'cakephp', 'issue_number' => 1]); +if ($result->isError) { + // The tool failed; $result->content says why. +} +``` + +The calls: + +- `listTools()`: the server's tools (every page), without the ones your tool filters leave out. +- `callTool($name, $arguments)`: a `Mcp\Schema\Result\CallToolResult` (`content`, `structuredContent`, `isError`). +- `listResources()`, `listResourceTemplates()`, `readResource($uri)`: resources, resource templates and contents. +- `listPrompts()`, `getPrompt($name, $arguments)`: prompts and their messages. +- `ping()`: checks that the server answers (`ping`, or `server/discover` in the 2026-07-28 revision). +- `serverInfo()`, `capabilities()`, `instructions()`: what the server said about itself when the connection + started (`Mcp\Schema\Implementation`, `Mcp\Schema\ServerCapabilities`, its instructions for the model). +- `protocolVersion()`: the protocol revision the client and the server speak (`'2026-07-28'`, + `'2025-11-25'`...), which may be another than the `protocolVersion` you asked for if the server offered one it + supports. +- `close()`: ends the connection now. It is opened on the first call and kept for the rest of the request (or the command), and closed when the PHP process ends (a server of the handshake revisions gets its `DELETE`). + +The list calls take an optional `$limit` (`listTools(20)`): they stop fetching +pages once they have that many, and return at most that many. + +A request the server refused before running it is sent once more, never more: +after a header mismatch (`-32020`, the headers of the 2026-07-28 revision do +not match the body), the tool list is fetched again first, every page of it +(100 at most), so the SDK learns +the headers each tool needs, as the specification advises; after an expired +session (HTTP `404` in the handshake revisions), on a new session. Any other +error is thrown as it is, so a call that may have run is never run twice. In +user mode and with `client_credentials`, a `401` the server gives before it +accepts any request of the call is sent once more with a new token; a `401` +after that (to the request that resumes a stream, say) is thrown. The client +also answers the `ping` a server of the handshake revisions sends. + +Results are the SDK's classes. A server or network error is thrown as the SDK's +exception (`Mcp\Exception\ExceptionInterface`, for example +`Mcp\Exception\RequestException` or `ConnectionException`). + +The client logs to the `mcp` scope. Headers and tokens are never logged, and +the configured `url` is logged without its query. At `debug` level the bodies +sent and received are logged as they are, so keep `debug` off for the `mcp` +scope in production when tool arguments or results are private. + +### The application's own OAuth token + +Some servers give machine clients an OAuth client of their own (the client +credentials grant of OAuth 2.1), instead of a fixed token: + +```php +'reports' => [ + 'url' => 'https://mcp.reports.example/mcp', + 'auth' => 'client_credentials', + 'clientId' => env('REPORTS_CLIENT_ID'), + 'clientSecret' => env('REPORTS_CLIENT_SECRET'), + 'issuer' => 'https://login.reports.example', // or 'tokenUrl' => 'https://login.reports.example/oauth/token' + 'scopes' => ['reports:read'], +], +``` + +The application asks the token endpoint for a token with `grant_type` +`client_credentials`, its scopes and the `resource` parameter (the server's +`url`), authenticating with its secret (`client_secret_basic`, or +`client_secret_post` when that is the only one the authorization server +lists). The token endpoint is the configured `tokenUrl`, or the one in the +metadata of the configured `issuer`, which must name itself exactly as +`issuer`: the secret only ever goes to the authorization server you named, +never to one the MCP server names. The token is kept in the connection store, +encrypted like the user grants (run the plugin's migrations), and used until it +expires within `Mcp.client.refreshLeeway` seconds; when the server refuses it +(`401`), a new one is asked for once. The token is kept for the `issuer`, +`tokenUrl`, `clientId` and `scopes` it was asked with: once you change one of +them, the stored token is no longer used and a new one is asked for. `bin/cake mcp check` shows such clients +on its `Clients` line, without their secret. + +## A local server over stdio + +`command` starts the server as a process and talks to it on stdin and stdout: + +```php +'Mcp' => [ + 'clients' => [ + 'files' => [ + 'command' => 'npx', + 'args' => ['-y', '@modelcontextprotocol/server-filesystem', ROOT . 'webroot' . DS . 'files'], + 'env' => ['NODE_ENV' => 'production'], + ], + ], +], +``` + +The process gets `PATH`, `HOME`, `USER`, the locale and temp directory +variables, and what you put in `env`. Nothing else of your application's +environment (database passwords, keys) is passed on. `cwd` sets its working +directory. + +Give the program in `command` and each argument in `args`: arguments are +quoted, so a value with spaces stays one argument. A `command` that is the path +of a program with a space in it (`ROOT . 'bin/my server'`, a project under +`/Users/me/My Projects`) works on Linux and macOS. On Windows such a path does +not start yet; put the program in a directory without spaces. + +## User mode: each user signs in + +With `auth` set to `user`, the server is called on behalf of each user, with +the access token that user got by signing in to the server's own authorization +server (OAuth 2.1). This is how servers like Linear, Notion or Sentry work. + +```php +'Mcp' => [ + 'clients' => [ + 'linear' => [ + 'url' => 'https://mcp.linear.app/mcp', + 'auth' => 'user', + ], + ], +], +``` + +```php +$linear = McpClients::get('linear')->for($this->Authentication->getIdentity()); + +if (!$linear->isConnected()) { + return $this->redirect($linear->connectUrl('/settings/integrations')); +} +$issues = $linear->callTool('list_issues', ['assignee' => 'me']); +``` + +`for()` takes a user id, an identity (`getIdentifier()`), or a user entity or +array with an `id`. The connection offers the same calls as app mode, plus: + +- `isConnected()`: whether the user has a grant the client can use. +- `connectUrl($redirect)`: the plugin's connect page for this client. Send the logged-in user there; after signing in they come back to `$redirect` (a path on your site) with a flash message. +- `disconnect()`: revokes the user's tokens at the authorization server and deletes them. + +When the user is not connected, or the server stopped accepting their grant, a +call throws `CakeDC\Mcp\Client\Exception\NotConnectedException`: catch it and +offer `connectUrl()` again. + +### What happens when a user connects + +1. `GET /mcp-client/linear/connect` (the path is `Mcp.client.route`) needs a + logged-in user (the `identity` request attribute of cakephp/authentication; + `Mcp.client.identityAttribute` to change it). It finds the server's + authorization server: the server's `401` challenge and its protected + resource metadata (RFC 9728), then the authorization server's metadata + (RFC 8414). The issuer must name itself exactly as the server said, and + PKCE with S256 must be supported. A server that lets the unauthenticated + probe through (it asks for a sign-in only on later calls) is still + discovered through its well-known metadata URLs. When a token answer has no + `scope`, the scopes asked for are kept as the ones granted (RFC 6749). A + server of the 2025-03-26 revision may + publish no protected resource metadata: then its origin (`url` without the + path) is taken as the authorization server, as that revision says, and its + metadata must be at `/.well-known/oauth-authorization-server` (or + the OpenID Connect path) and name the origin as its issuer. +2. Without a `clientId`, the application gets a client id in one of two + ways, chosen by `registration` (see + [Client ID Metadata Document](#client-id-metadata-document) below). With a + Client ID Metadata Document, the client id is the URL of a document the + application serves, and nothing is registered or stored. Otherwise the + application registers itself there once (dynamic client registration, RFC + 7591) as a public client, and keeps the registration for every user. The + registration names the scopes it will ask for (`scope`) and an + `application_type`: `web`, or `native` when the callback is on this machine + (`localhost`), as the MCP specification asks for OpenID Connect servers. The callback URL it registers is built from + `App.fullBaseUrl`, which by default comes from the `Host` header of the + request: set `App.fullBaseUrl` in production, or a request with another + host registers the application again with that callback. When the + authorization server forgets the registration, a token request answered + with `invalid_client` deletes it and the next connect registers again. If + it fails some other way (the authorize page refuses the client, say), + delete it yourself, for example with + `(new TableConnectionStore())->deleteRegistration('linear', $issuer)` or + by deleting the rows of `mcp_client_registrations` whose `client` is that + client's name. +3. The browser goes to the authorization server with PKCE, a `state` and the + `resource` parameter (RFC 8707). The sign-in in progress is kept in the + user's session. The scopes asked for are the ones the server names (its + challenge, or its metadata), plus `offline_access` when the authorization + server or the server lists it: servers in the OpenID Connect style (Auth0, + Okta, Microsoft Entra ID) only issue a refresh token for it. A configured + `scopes` is sent as written, so add `offline_access` there yourself if you + set it. +4. The authorization server sends the browser to + `GET /mcp-client/linear/callback`. The `state` must match the one in the + session (it is used once), the same user must still be logged in, the + response must come from the same issuer (`iss`, RFC 9207; an error answer + too, whose error is not shown otherwise), and the sign-in must finish + within 10 minutes. The code is exchanged and the tokens are + stored. + +Calls then send the user's access token. It is refreshed when it expires +within `Mcp.client.refreshLeeway` seconds (60), and once more if the server +answers `401`. When the refresh is refused, the grant is deleted and the user +connects again. + +Only one request refreshes a user's grant at a time: many authorization +servers end the whole grant when the same refresh token is used twice. Other +requests of that user wait for the new token, up to 10 seconds, and then fail +with a `ClientException` (the user stays connected). + +### Client ID Metadata Document + +The MCP authorization specification prefers a Client ID Metadata Document +(draft-ietf-oauth-client-id-metadata-document) to dynamic registration: the +client id is an https URL, and the authorization server fetches the client's +details from it. The plugin serves one for each user mode client at +`GET /mcp-client//client.json` (under `Mcp.client.route`), with no login: + +```json +{ + "client_id": "https://app.example.com/mcp-client/linear/client.json", + "client_name": "CakePHP MCP Client", + "redirect_uris": ["https://app.example.com/mcp-client/linear/callback"], + "grant_types": ["authorization_code", "refresh_token"], + "response_types": ["code"], + "token_endpoint_auth_method": "none", + "token_endpoint_auth_methods_supported": ["none"], + "application_type": "web" +} +``` + +It never holds a secret: the client signs in with PKCE and no client +authentication. `client_name` is `Mcp.client.name`, and the URLs are built +from `App.fullBaseUrl`, so set it in production. The route must be reachable +without a session: with cakedc/users, `McpConfig::rbacPermissions()` has a rule +for it. + +`Mcp.clients..registration` picks how a client without a configured +`clientId` gets one: + +- `auto` (the default): the document, when the authorization server's + metadata says `client_id_metadata_document_supported: true` and + `App.fullBaseUrl` is https on a public host, so the authorization server + can fetch it: not `localhost`, a local or reserved name (`.internal`, + `.local`, `.test`, `.example`, `.invalid`), a private address, or a name + that does not resolve or resolves to a private or loopback address (a + development site such as `shop.ddev.site` resolves to your machine). + Otherwise dynamic registration, as before. A site with public addresses + that the authorization server still cannot reach (a staging site behind a + VPN) needs `dynamic`: the sign-in would end on the authorization server's + error page. +- `metadata`: always the document. The sign-in fails with a message when the + base URL is not public https or the authorization server does not support + it. The name is not resolved, so this also works for a private + authorization server that reaches a site on the same network. +- `dynamic`: always dynamic registration. + +A configured `clientId` always wins over both. `bin/cake mcp check` says on +its `Clients` line which one each client uses, as far as it can tell without +asking the authorization server. + +The connect, callback and `client.json` routes are only connected when a +client uses user mode. With cakedc/users, `McpConfig::rbacPermissions()` then +also lets any logged-in user reach the first two, and anyone the document, so add it to `config/permissions.php` as the +[OAuth guide](oauth.md) shows for the endpoint. + +### When the server asks for more scope + +A server can refuse a call because the user's token lacks a scope: it answers +`403` with a `WWW-Authenticate: Bearer error="insufficient_scope", scope="..."` +challenge. The call still throws, and the user's grant is marked with the +scopes they already had plus the ones the server asked for. `needsMoreScope()` +says so, `stepUpScopes()` lists them, and the next connect of that user +(`connectUrl()`) asks the authorization server for all of them, so nothing +granted before is lost. Configured `scopes` are no limit here: the scopes the +server names are added to them, except `offline_access`, which is only asked +for when the authorization server lists it, as on the first sign-in. The mark +keeps 50 scopes and 2048 bytes at most, the ones the user already had first: + +```php +$linear = McpClients::get('linear')->for($identity); +try { + $linear->callTool('delete_issue', ['id' => $id]); +} catch (ExceptionInterface $e) { + if ($linear->needsMoreScope()) { + return $this->redirect($linear->connectUrl('/issues')); + } + throw $e; +} +``` + +The mark is kept with the grant (column `step_up_scope` of +`mcp_client_connections`) and cleared when the user connects again. The user stays connected meanwhile. + +A step-up is tried once per scope. The grant remembers what the sign-in that +made it asked for (column `requested_scope`), and a challenge that names only +scopes that sign-in already asked for marks nothing: the authorization server +was asked and did not grant them (the user does not have them, or it trims +scopes), so connecting again would ask for the same. `needsMoreScope()` stays +false and the call's error reaches your code, so the example above does not +send the user round in a loop. A challenge with a scope not asked for yet +marks the grant as usual. + +### Storing tokens + +By default grants are stored in two tables of the plugin, +`mcp_client_connections` and `mcp_client_registrations`. Rows are found by a +SHA-256 key of the client name and the user id (or the issuer), so user ids +that differ only in case or accents never share a grant, whatever the +database's collation, and ids and issuers of any length fit. Create the tables +when you use user mode: + +``` +bin/cake migrations migrate -p CakeDC/Mcp +``` + +Access tokens, refresh tokens and client secrets are stored encrypted with +`Security::encrypt()`, keyed with `Mcp.client.encryptionKey` or, when it is not +set, your `Security.salt`. Changing that key disconnects every user (their +grants can no longer be read, so they sign in again). With your own key, the +salt can change without that. + +To keep grants elsewhere, implement +`CakeDC\Mcp\Client\Store\ConnectionStoreInterface` and set its class in +`Mcp.client.store`. Keep tokens and secrets unreadable at rest, and make +`claimRefresh()` atomic (one conditional update, for example), since it is what +keeps two requests from refreshing the same grant. `saveRefreshed()` stores what +a refresh produced only while the request still holds that claim (one +conditional update on the claim id), so a user who disconnects while a refresh +is running stays disconnected. `save()` ends any claim on the grant it +replaces, so a refresh of the old grant that finishes after the user signed in +again stores nothing, and two requests that save a user's first grant at the +same time must both succeed (the last one wins). `markStepUp()` updates only +the step-up mark of a grant that is still there: never the tokens, and never a +row the user deleted by disconnecting. + +After it claims the refresh, a request reads the grant again: when another +request refreshed it in the meantime, it uses that token and never sends the +refresh token that request already spent. + +### A server whose owner gave you a client + +Some authorization servers do not register clients automatically. Register +the callback URL with them (`https://your-app.example.com/mcp-client//callback`) +and set what they give you: + +```php +'notion' => [ + 'url' => 'https://mcp.notion.com/mcp', + 'auth' => 'user', + 'clientId' => env('NOTION_CLIENT_ID'), + 'clientSecret' => env('NOTION_CLIENT_SECRET'), + // The authorization server that gave you the client, as its metadata names itself + // (the "issuer" of its /.well-known/oauth-authorization-server document). + 'issuer' => env('NOTION_ISSUER'), + 'scopes' => ['read'], +], +``` + +With a `clientSecret` and discovery, `issuer` is required. The MCP server names +its authorization server on every sign-in, so without it the secret would go to +whatever authorization server the MCP server names, a compromised one included. +With `issuer` set, the client only signs in when the MCP server names that +issuer, compared exactly; otherwise the sign-in fails with an error naming both. +Nothing is sent to the other server. + +For an authorization server on your own network, set its endpoints too. They +are then trusted like `url` and nothing is discovered: + +```php +'intranet' => [ + 'url' => 'https://mcp.intranet.example/mcp', + 'auth' => 'user', + 'authorizationUrl' => 'https://sso.intranet.example/oauth/authorize', + 'tokenUrl' => 'https://sso.intranet.example/oauth/token', + 'revocationUrl' => 'https://sso.intranet.example/oauth/revoke', + 'clientId' => 'cake-app', + 'clientSecret' => env('SSO_CLIENT_SECRET'), + // What the server names itself in its metadata, so the client can check sign-in responses. + 'issuer' => 'https://sso.intranet.example/realms/corp', +], +``` + +Without `issuer`, the client cannot know which server a sign-in response comes +from and does not check its `iss`; with configured endpoints that is the +server you wrote, so set it when you know it. With discovery, `issuer` also +pins the authorization server, as above. + +## Which addresses the client calls + +There are two levels of trust: + +- **Addresses you write in `Mcp.clients`** (`url`, `authorizationUrl`, + `tokenUrl`, `revocationUrl`, the well-known metadata paths of `url`, and a + metadata URL in the server's challenge on the same origin as `url`: scheme, + host and port) are trusted, internal hosts included, so a server on your + network or on `localhost` can be discovered. Plain `http` is accepted only for this + machine (`localhost`, a `.localhost` name, a loopback address); for another + host set `'allowInsecure' => true` on the client, and only on a network you + trust, since tokens travel in the clear. +- **Addresses a remote server hands the client** (the metadata URL in its + challenge on another origin, the authorization server, its token, registration and revocation + endpoints, and any redirect) go through a guard against server-side request + forgery: https only, a host name (not an IP address, not `localhost` or a + name under `.localhost`, `.local`, `.localdomain`, `.internal`, + `.home.arpa` or `.arpa`) whose every address is public, the connection + pinned to the address that was checked, no proxy from the environment, + and answers capped at `Mcp.client.maxResponseBytes` (1 MiB), uncompressed + (a compressed answer is refused, so the cap applies to what is read). A redirect is + followed only for metadata, and checked again; requests that carry a code, + a secret or a token never follow one. +- **The MCP endpoint itself** is never followed when it redirects (http to + https, a trailing slash, a login page): the call throws a `ClientException` + that names the status and the target (without its query) and asks you to + set the client's `url` to the final address. + +An authorization server on a private address is therefore refused when it is +discovered. Configure its endpoints, as above, to use it, or set +`allowPrivateNetwork` on that client: + +```php +'intranet-tools' => [ + 'url' => 'https://mcp.corp.example/mcp', + 'auth' => 'user', + 'allowPrivateNetwork' => true, +], +``` + +With it, the OAuth endpoints learned for that client (its authorization +server, token, registration and revocation endpoints and the metadata URLs) +may be names that resolve to private, loopback or link-local addresses, and +names under `.internal`, `.local` and the other local names, and `localhost` +itself (with `allowInsecure` too, an authorization server on this machine in +development). A name the DNS has no record of is looked up as the system does, +so `localhost` and the names in `/etc/hosts` work. IP addresses and other single-label names stay refused, the connection is still pinned to the +address that was checked, and plain `http` stays refused unless the client +also has `allowInsecure`. Other clients are not affected. Only set it for a +server you trust as much as your own network: a compromised server could make +the application call internal addresses. `bin/cake mcp check` warns on its +`Clients` line for each client that sets it. + +### Behind an outbound proxy + +On a network where the application reaches the internet only through a +proxy, set `Mcp.client.proxy`: + +```php +'Mcp' => [ + 'client' => [ + 'proxy' => env('MCP_CLIENT_PROXY'), // 'http://user:password@proxy.corp.example:3128' + ], +], +``` + +Every HTTP request of every client then goes through it: the MCP sessions, +configured endpoints and the addresses a remote server names. The one +exception is a configured address on this machine (`localhost` and its +subdomains, any `127.x.y.z`, `::1`), which is reached directly: through the proxy its token would cross the +network in clear and land on the proxy's own `localhost`. `NO_PROXY` in the +environment is not followed. It is an `http`, `https` or `socks5h` URL with no +path; anything else fails with a message naming the setting. Use `socks5h`, +not `socks5`: with `socks5` curl resolves the host name in the application, +which is what the proxy is there to avoid. Its user name and password are sent to the proxy +only, and `bin/cake mcp check` shows the proxy on its `Clients` line without +them. Default `null`: no proxy, and a proxy from the environment +(`https_proxy`) is not used for the addresses a remote server names. + +What changes in the guard for those addresses: the proxy resolves the host +name, so the connection is no longer pinned to an address the application +checked, and a name the application itself cannot resolve is allowed. What +stays: https only, no IP addresses, no `localhost` or other local names, no +user name or fragment, and a name that does resolve on the application's side +to a private address is still refused. The proxy can still reach hosts of your +own network that the application cannot tell apart from public ones, so +restrict what the proxy itself lets through where that matters. + +## Caching lists and reads + +A server on the 2026-07-28 revision can say how long a list result, a resource +read or its `server/discover` answer stays fresh (`ttlMs`) and who may share +it (`cacheScope`, `private` or `public`). +Set `cache` on a client to keep such results in a Cake cache config: + +```php +'github' => [ + 'url' => 'https://api.githubcopilot.com/mcp/', + 'token' => env('GITHUB_MCP_TOKEN'), + 'cache' => 'default', +], +``` + +`listTools()`, `listResources()`, `listResourceTemplates()`, +`listPrompts()` and `readResource()` then use a cached result while it is +fresh, without asking the server, and a new connection takes the server's +`server/discover` answer (`serverInfo()`, `capabilities()`, `instructions()`) +from the cache too. `ping()` always asks the server. A read is kept per exact +URI, and a result over 512 KiB is not kept. A `private` result is kept per user in user mode and per client in app +mode, and always per credential it was asked with: the user's access token, +the configured `token` or `headers`, or what a `token` callable returns (which +is then called once more for each list). So it is never served for another +token, to another user, or after a user reconnects with another account. A +`public` one is shared by every user of that client. A result without hints, or with a ttl of 0, is not +kept. A `notifications/tools/list_changed` (or the resources and prompts ones) +from the server drops that client's entries for those lists, for every user; +`notifications/resources/list_changed` also drops every cached read, and +`notifications/resources/updated` the reads of its URI. +In user mode a cached list is only used for a user who is still connected. A +tool list whose tools have `x-mcp-header` annotations is never cached, because +the SDK learns the headers it must send for those tools from the listing it +fetches. `cache` must name an existing cache config, or the client fails with +a message. Default `null`: nothing is cached, as before. + +## Tool filters, timeouts and protocol version + +```php +'github' => [ + 'url' => 'https://api.githubcopilot.com/mcp/', + 'token' => env('GITHUB_MCP_TOKEN'), + 'tools' => [ + 'only' => ['get_*', 'list_*', 'search_*'], + 'except' => ['get_secret_*'], + ], + 'timeout' => 15, + 'protocolVersion' => '2025-06-18', +], +``` + +- `tools.only` and `tools.except` are shell patterns (`fnmatch()`, case sensitive). `except` wins. A tool they leave out is not listed, and calling it throws `CakeDC\Mcp\Client\Exception\ClientException` without sending anything. +- `timeout` is in seconds, for the connection and for each request (default 30). In user mode it is also the limit for all the requests of one sign-in step together (the discovery and registration of `connect`, the token exchange of `callback`), so a slow authorization server holds a web worker about that long: each request still gets at least one second, so a step can run up to a second over. +- `protocolVersion` asks for a revision of the protocol; leave it out to let the SDK negotiate. + +## Presets for well-known servers + +These snippets are starting points; check each provider's documentation for +its current address, scopes and how to get a token. + +```php +'Mcp' => [ + 'clients' => [ + // GitHub: a personal access token or a GitHub App token. + 'github' => ['url' => 'https://api.githubcopilot.com/mcp/', 'token' => env('GITHUB_MCP_TOKEN')], + // Stripe: a restricted API key. + 'stripe' => ['url' => 'https://mcp.stripe.com', 'token' => env('STRIPE_RESTRICTED_KEY')], + // Linear, Sentry and Notion: each user signs in. + 'linear' => ['url' => 'https://mcp.linear.app/mcp', 'auth' => 'user'], + 'sentry' => ['url' => 'https://mcp.sentry.dev/mcp', 'auth' => 'user'], + 'notion' => ['url' => 'https://mcp.notion.com/mcp', 'auth' => 'user'], + // A filesystem server on this machine. + 'files' => [ + 'command' => 'npx', + 'args' => ['-y', '@modelcontextprotocol/server-filesystem', ROOT . 'storage'], + ], + ], +], +``` + +## Checking the setup + +`bin/cake mcp check` lists the clients on its `Clients` line, and fails when a +client config is invalid, when a user mode client is configured but the +plugin routes are not loaded, or when the default store's tables are missing. + +## Testing code that uses a client + +Give `McpClients` a registry built on test doubles, and reset it after the +test. The HTTP client comes from a `CakeDC\Mcp\Client\HttpClientFactoryInterface`, +so a PSR-18 double can answer for the server: + +```php +use CakeDC\Mcp\Client\ClientConfig; +use CakeDC\Mcp\Client\ClientRegistry; +use CakeDC\Mcp\Client\HttpClientFactoryInterface; +use CakeDC\Mcp\Client\McpClients; +use Psr\Http\Client\ClientInterface; + +protected function setUp(): void +{ + parent::setUp(); + $double = $this->myPsr18Double(); // answers the JSON-RPC requests your code makes + McpClients::setRegistry(new ClientRegistry(new class ($double) implements HttpClientFactoryInterface { + public function __construct(private ClientInterface $client) + { + } + + public function create(ClientConfig $config): ClientInterface + { + return $this->client; + } + })); +} + +protected function tearDown(): void +{ + McpClients::reset(); + parent::tearDown(); +} +``` + +`ClientRegistry` also takes a `ConnectionStoreInterface` (an in-memory store +for user mode tests) and the `GuardedHttp` layer, whose transport +(`GuardedTransportInterface`) and DNS (`HostResolverInterface`) can be doubles +too, so tests never reach the network. diff --git a/docs/oauth.md b/docs/oauth.md index 8c78181..ec4d6b4 100644 --- a/docs/oauth.md +++ b/docs/oauth.md @@ -146,7 +146,8 @@ $csrf->skipCheckCallback( ``` `McpConfig::isEndpoint()` is true for the MCP route and for its metadata path, -and follows `Mcp.route`, so you do not hard code `/mcp`. +and follows `Mcp.route`, so you do not hard code `/mcp`. It reads the path as +the router does, and once routing has run it follows the route that matched. ### 5. Keep the oauth Token authenticator off the MCP route @@ -208,18 +209,26 @@ expected: this plugin validates the MCP tokens itself. | Check | What it looks at | | --- | --- | -| Endpoint | The URL of the endpoint, or a warning when `Mcp.route` is disabled. | +| Endpoint | The URL of the endpoint, or a warning when `Mcp.route` is disabled. For a named server on a route with parameters, the pattern and its parameters and a warning in host mode (a server whose configured resource or audience lacks a parameter is not served, and its `Server` line fails); for one with `'route' => false`, that it is served over stdio only. Fails when `Mcp.route` has parameters. | | Authentication | The mode, or the `Mcp.auth` setting that is invalid. | | Resource | The resource URL, the metadata URL and the scopes it advertises. In `oauth` mode it fails when the resource is not declared in `OAuthServer.resources`. In `external` mode it lists the accepted audiences and warns when the resource URL is not among them. | | Metadata route | That the plugin routes are connected, and warns when the path the application serves differs from the advertised one (subdirectory installs need a rewrite, see below). | | Allowed hosts | That the host of the resource is in `Mcp.http.allowedHosts`. | | CSRF | That the CSRF middleware skips POST requests to the MCP route. | | Authenticators | In `oauth` mode, that no authenticator of the application answers access tokens on the MCP route before the plugin. On a `cakedc/users` application it reads `Auth.Authenticators` (see [cakedc/users](#cakedcusers)). Fails with an install hint when `cakedc/cakephp-oauth-server` is missing. | -| Tools | The tools the server offers, built as the endpoint builds it. Warns when there is none (a class outside `Mcp.discovery.scanDirs`, or without a namespace, is skipped without an error). | -| Authorizer | The configured authorizer. With `RbacToolAuthorizer` it warns when there are no rules, or no rule for plugin `CakeDC/Mcp` and controller `Tools` (wildcards count), because then no one can call a tool. | -| Tool scopes | In `oauth` and `external` modes, warns about tools that need no scope (no line in `Mcp.auth.scopes.tools`, and no `default` or `tools/call` scope), which any valid token may call, and about names in `Mcp.auth.scopes.tools` that are not tools. | +| Discovery | Fails when `Mcp.discovery.scanDirs` is set and `symfony/finder` is missing: the SDK then skips discovery and the server has no tools. | +| Tools | Every tool registered on the server, built as the endpoint builds it, catalogued and app-only tools included. Warns when there is none (a class outside `Mcp.discovery.scanDirs`, or without a namespace, is skipped without an error). | +| Tool schemas | Warns about type arrays, arrays without an item type and optional parameters without a description, in every registered tool, nested objects and array items included (`filter.date_from`, `rows[].tags`). | +| Conditions | What `#[McpWhen]` left out of the server, and why. | +| Catalog | With `Mcp.catalog` on, the tools behind `find_tools` and `call_tools`, the tools a pattern matched that stay in `tools/list` because they link to an app, and patterns that match no tool. | +| Apps | With apps announced (`Mcp.apps.enabled`, or the extension enabled in `Mcp.server.configure`), the app pages; fails when a tool links to something that is not an app page, or when tools link to apps the server does not announce; it reads each page through the server and warns about one that does not render (it reads them without a caller, so a page that needs one may warn here and render for a user). | +| Authorizer | The configured authorizer. With `RbacToolAuthorizer` it warns when there are no rules, or no rule for plugin `CakeDC/Mcp` and controller `Tools` (wildcards count), because then no one can call a tool, and when a rule for plugin `CakeDC/Mcp` names a controller the plugin does not have (`Resource` for `Resources`, say), which decides nothing. It also says whether resources and prompts are covered: by an authorizer that implements `ResourceAuthorizerInterface` or `PromptAuthorizerInterface`, and for `RbacToolAuthorizer` only with rules for controller `Resources` or `Prompts` (see [Authorization](authorization.md#resources-and-prompts)). | +| Tool scopes | In `oauth` and `external` modes, warns about registered tools (catalogued and app-only ones included, `find_tools` and `call_tools` left out) that need no scope (no line in `Mcp.auth.scopes.tools`, and no `default` or `tools/call` scope), which any valid token may call, and about names in `Mcp.auth.scopes.tools` that are not tools. In host mode it warns when `auth.scopes` is set, since host mode checks no scopes. | +| Cache hints | The `Mcp.server.cache` hints: says when `tools/list` is sent private because the authorizer can give users different tools or MCP Apps is on, and warns when `resources/read` is public (an authorizer that decides who reads which resource makes it private, and the line says so). | | Logging | That a Log engine takes the errors of the `mcp` scope. Without one, a failing tool only answers "Error while executing tool" and its error is lost (the `debug` and `error` engines of the skeleton have `'scopes' => null`). See [Logging](configuration.md#logging). | | Audit | When the [audit log](configuration.md#audit-log) is on, that a Log engine takes its lines. | +| Servers | With several servers, after the lines of each one (also with `--server`): fails when two share a route (also two patterns of the same shape, `/mcp/{tenant}` and `/mcp/{partner}`), when a fixed route fits another server's pattern (the router sends that value to the fixed one), or when two share a resource or an external audience, and warns when a scan directory of one holds another's. A `Server ` line fails for an entry of `Mcp.servers` that is not served because of a mistake. | +| Clients | The MCP clients of `Mcp.clients`: each config valid, and for user mode and `client_credentials` the connect and callback routes and the token store's tables and columns. It says which registration each user mode client uses (configured client id, metadata document, dynamic registration), shows `Mcp.client.proxy` without its password and a token callable without calling it, and warns for each client with `allowPrivateNetwork`. | Sample output: @@ -231,11 +240,25 @@ Sample output: [PASS] Allowed hosts: example.com, localhost, 127.0.0.1, [::1] [PASS] CSRF: the MCP route is skipped [PASS] Authenticators: no authenticator answers access tokens at the MCP route first +[PASS] Discovery: scans src/Mcp [PASS] Tools: 3 tools: find_posts, create_post, publish_post -[PASS] Authorizer: RbacToolAuthorizer, 2 of 14 rules for the tools +[PASS] Tool schemas: 3 tools, no problems +[PASS] Conditions: nothing skipped +[PASS] Catalog: off +[PASS] Apps: off +[PASS] Authorizer: RbacToolAuthorizer, 2 of 14 rules for the tools; resources and prompts are not covered (no rule for controller Resources or Prompts) [PASS] Tool scopes: every tool needs a scope +[PASS] Cache hints: off (private, not cached) [PASS] Logging: the mcp scope goes to mcp [PASS] Audit: off +[PASS] Clients: none +``` + +With `Mcp.servers`, each server's lines come under a `Server ` heading, +followed by one line for all of them before `Clients`: + +``` +[PASS] Servers: 2 servers: default, admin ``` A failing check looks like this, and the command exits with an error code: @@ -280,7 +303,12 @@ return [ `McpConfig::rbacPermissions()` returns one rule: role `*`, plugin `CakeDC/Mcp`, controllers `Mcp` and `ProtectedResource`, actions `handle` and -`metadata`, `bypassAuth` `true`. The plugin decides access itself. The oauth +`metadata`, `bypassAuth` `true`. With a user mode client in `Mcp.clients` it +returns two more: one for any logged-in user on the client's `connect` and +`callback` routes, and one with `bypassAuth` on its `metadata` action, so an +authorization server can fetch the client's `client.json` without a session +(see [Calling other MCP servers](mcp-client.md)). The plugin decides access +itself. The oauth plugin adds the rule for its own endpoints, see its [cakedc/users page](https://github.com/CakeDC/cakephp-oauth-server/blob/1.next-cake5/docs/cakedc-users.md). diff --git a/docs/resources-and-prompts.md b/docs/resources-and-prompts.md new file mode 100644 index 0000000..837057d --- /dev/null +++ b/docs/resources-and-prompts.md @@ -0,0 +1,221 @@ +# Resources and prompts + +Next to tools, an MCP server offers two other kinds of things: + +- **Resources**: data the client reads by URI and shows to the model or the + user, such as a policy, a report or an order. A **resource template** is a + family of resources with one URI pattern, such as `shop://orders/{number}`. +- **Prompts**: ready-made messages the user picks from a list in the client, + such as "summarize this order", with arguments the client asks for. + +Both are declared like tools, with the SDK's attributes on plain classes in +`src/Mcp/` (or another directory of `Mcp.discovery.scanDirs`), and get +constructor injection from Cake's container. See [Writing tools](tools.md) for +discovery, the container and the caller's identity, which work the same way. + +The examples on this page are those of `tests/test_app/src/McpDocs/ShopContent.php` +in the plugin, and the plugin's tests check that they answer as shown. + +## Resources + +```php +namespace App\Mcp; + +use Mcp\Capability\Attribute\McpResource; + +class ShopContent +{ + /** + * How returns work. + */ + #[McpResource(uri: 'shop://policies/returns', name: 'return_policy', mimeType: 'text/markdown')] + public function returnPolicy(): string + { + return "# Returns\n\nWithin 30 days, with the receipt."; + } + + /** + * Today's numbers. + */ + #[McpResource(uri: 'shop://stats', name: 'shop_stats', mimeType: 'application/json')] + public function stats(): array + { + return ['orders' => 42, 'open' => 3]; + } +} +``` + +The docblock is the description clients show. What the method returns +becomes the contents of `resources/read`: + +- A string is sent as text, with the `mimeType` of the attribute. +- An array is sent as JSON text when the `mimeType` is JSON + (`application/json`). +- `['blob' => base64, 'mimeType' => ...]` is sent as binary content, for + images, PDFs and other files: + + ```php + #[McpResource(uri: 'shop://logo', name: 'logo', mimeType: 'image/png')] + public function logo(): array + { + return ['blob' => base64_encode((string)file_get_contents(WWW_ROOT . 'img/logo.png')), 'mimeType' => 'image/png']; + } + ``` + +- An `SplFileInfo` is read and sent as binary content, and a + `TextResourceContents` or `BlobResourceContents` of the SDK is sent as it + is, when you need full control. + +`bin/cake bake mcp_resource OrderGuide` writes a resource class and its test +(see [Generating classes with bake](tools.md#generating-classes-with-bake)). + +## Resource templates + +A template declares the URI pattern; its variables are the method's +arguments: + +```php +use Mcp\Capability\Attribute\CompletionProvider; +use Mcp\Capability\Attribute\McpResourceTemplate; + +#[McpResourceTemplate(uriTemplate: 'shop://orders/{number}', name: 'order', mimeType: 'application/json')] +public function order( + #[CompletionProvider(provider: OrderNumbers::class)] + string $number, +): array { + return ['number' => $number, 'status' => 'shipped']; +} +``` + +Templates are listed by `resources/templates/list`, and the client reads a +concrete URI (`shop://orders/A-1001`) with `resources/read`, like any +resource. + +## Prompts + +```php +use Mcp\Capability\Attribute\McpPrompt; + +/** + * Writes a summary of an order for the customer. + * + * @param string $number The order number. + */ +#[McpPrompt(name: 'summarize_order')] +public function summarizeOrder( + #[CompletionProvider(provider: OrderNumbers::class)] + string $number, +): array { + return [ + ['role' => 'user', 'content' => 'Summarize order ' . $number . ' for the customer.'], + ]; +} +``` + +The arguments become the prompt's arguments, with the `@param` descriptions. +The method returns a list of messages, each with a `role` (`user` or +`assistant`) and a `content`. Check arguments with +`ToolValidation::checkPrompt()` (see [Errors](tools.md#errors)). +`bin/cake bake mcp_prompt WeeklyReport` writes a prompt class and its test. + +## Content types + +A message's `content` is a string (sent as text) or one of the SDK's content +classes: + +```php +use Mcp\Schema\Content\AudioContent; +use Mcp\Schema\Content\EmbeddedResource; +use Mcp\Schema\Content\ImageContent; +use Mcp\Schema\Content\ResourceLink; +use Mcp\Schema\Content\TextResourceContents; + +return [ + ['role' => 'user', 'content' => 'Summarize order ' . $number . ' for the customer.'], + // The order itself, inside the message. + ['role' => 'user', 'content' => new EmbeddedResource( + new TextResourceContents('shop://orders/' . $number, 'application/json', $order), + )], + // A pointer to a resource the client can read when it needs it. + ['role' => 'user', 'content' => new ResourceLink('shop://policies/returns', 'return_policy', mimeType: 'text/markdown')], +]; +``` + +- `ImageContent($base64, 'image/png')`: an image, as the `describe_photo` + prompt of the example sends with "Describe this product photo in one + sentence." +- `AudioContent($base64, 'audio/wav')`: a recording, as the + `transcribe_voicemail` prompt sends with "Transcribe this voicemail." +- `EmbeddedResource`: the contents of a resource inside the message, text + (`TextResourceContents`) or binary (`BlobResourceContents`). +- `ResourceLink`: the URI of a resource, with its name and MIME type, without + its contents. + +Tools return the same content classes, see [Results](tools.md#results). + +## Completions + +Clients ask for completions while the user types an argument of a prompt or a +variable of a template (`completion/complete`). Declare them with +`#[CompletionProvider]` on the argument, as above: `values: [...]` for a +fixed list, `enum: Status::class` for the cases of an enum, or +`provider: OrderNumbers::class` for a class that implements the SDK's +`ProviderInterface`, built from the container: + +```php +use Mcp\Capability\Completion\ProviderInterface; + +class OrderNumbers implements ProviderInterface +{ + public function __construct(private OrdersTable $orders) + { + } + + public function getCompletions(string $currentValue): array + { + return $this->orders->find() + ->select(['number']) + ->where(['number LIKE' => $currentValue . '%']) + ->limit(20) + ->all() + ->extract('number') + ->toList(); + } +} +``` + +The example class of the plugin's tests completes `A-` to `A-1001` and +`A-1002` from a fixed list instead of a table. + +## Authorization + +By default every identified caller can list and read every resource and get +every prompt. An authorizer that implements `ResourceAuthorizerInterface` or +`PromptAuthorizerInterface` decides who sees which one: a denied resource or +prompt is left out of the lists, answers like an unknown one, and completes +nothing. `RbacToolAuthorizer` checks them as controllers `Resources` and +`Prompts` once your rules name them. See +[Resources and prompts](authorization.md#resources-and-prompts) in +Authorization. + +## Testing + +`McpTestTrait` reads resources, gets prompts and asks for completions through +the server, as the current identity: + +```php +$this->mcpReadResource('shop://orders/A-1001'); +$this->assertMcpResourceContains('"status": "shipped"'); + +$this->mcpGetPrompt('summarize_order', ['number' => 'A-1001']); +$this->assertMcpPromptContains('Summarize order A-1001'); + +$this->mcpComplete(['type' => 'ref/resource', 'uri' => 'shop://orders/{number}'], 'number', 'A-'); +$this->assertMcpCompletionValues(['A-1001', 'A-1002']); + +$this->mcpActingAs($clerk); +$this->assertMcpResourceNotListed('shop://stats'); +``` + +See [Prompts, resources and completions](testing.md#prompts-resources-and-completions) +for every helper and assertion. 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 dee2750..0debeb4 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -117,11 +117,121 @@ 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. `$expected` may be a closure that gets the value: it passes when the closure returns `true`, and is not called for a missing path. | +| `assertMcpStructuredContentHas($path)` | returned a `structuredContent` with that dot path, even with a `null` value. | +| `assertMcpStructuredContentMissing($paths)` | returned a `structuredContent` without that dot path, or without any of a list of them. A key with a `null` value is there, so it fails. | +| `assertMcpStructuredContentSubset($expected)` | returned a `structuredContent` that holds `$expected`: each key of an object with the same value, other keys allowed, lists compared whole, starting at the top of the structured content. Value types matter; the order of an object's keys never does, here or in the other structured content assertions. | +| `assertMcpStructuredContentNotSubset($fragment)` | returned a `structuredContent` that does not hold `$fragment`, by the same rule: it fails exactly when `assertMcpStructuredContentSubset($fragment)` would pass. | +| `assertMcpStructuredContentLacks($pairs)` | returned a `structuredContent` where none of the key and value pairs of `$pairs` appears in any object, at any depth. | +| `assertMcpStructuredContentIgnoringOrder($expected, $path = '')` | returned `$expected` (at a dot path, or as the whole structured content) once the order of list items is ignored at every level. Value types matter and duplicates count; a missing path fails. | +| `assertMcpStructuredContentKeys($shape, $exact = false)` | returned the keys `$shape` describes, values not looked at: `['order' => ['id', 'lines' => ['*' => ['sku']]], 'total']`, where `'*'` is every item of a list (an empty list fails). With `$exact`, a described level has no other keys. | +| `assertMcpStructuredContentCount($path, $count)` | returned a list or object with `$count` items at that dot path (`''` for the whole structured content). | +| `assertMcpStructuredContentType($path, $type)` | returned a value of that JSON type at that dot path: `string`, `number` (integers count), `integer`, `boolean`, `array`, `object` or `null`. | +| `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. `assertMcpToolNotListed()` also checks that the tool exists, for the same -reason as `assertMcpToolDenied()`. +reason as `assertMcpToolDenied()`. With `Mcp.apps.enabled` on, the trait tells +the server it renders apps, as an MCP Apps host does, so app-only tools are +listed to it unless the authorizer hides them. + +`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'); +``` + +## Prompts, resources and completions + +The same trait gets prompts, reads resources and asks for completions, through +the server as the current identity, scopes and server, like `mcpCallTool()`: + +```php +public function testTheGreetingPrompt(): void +{ + $this->mcpActingAs(['id' => 1]); + + $this->mcpGetPrompt('greet', ['name' => 'Ada']); + + $this->assertMcpPromptMessages([ + ['role' => 'user', 'text' => 'Say hello to Ada.'], + ['role' => 'assistant', 'text' => 'Hello, Ada!'], + ]); +} + +public function testAnOrderReadsThroughItsTemplate(): void +{ + $this->mcpReadResource('orders://1002'); + + $this->assertMcpResourceText('Order 1002', 'text/plain'); +} + +public function testOrderNumbersComplete(): void +{ + $this->mcpComplete(['type' => 'ref/resource', 'uri' => 'orders://{number}'], 'number', '10'); + + $this->assertMcpCompletionValues(['1001', '1002']); +} +``` + +| Method | Does | +| --- | --- | +| `mcpGetPrompt($name, $arguments)` | Gets a prompt and keeps the response. | +| `mcpReadResource($uri)` | Reads a resource, also a URI a resource template matches, and keeps the response. | +| `mcpComplete($ref, $argument, $value)` | Asks for the completions of a prompt argument (`['type' => 'ref/prompt', 'name' => 'greet']`) or of a template variable (`['type' => 'ref/resource', 'uri' => 'orders://{number}']`) and keeps the response. | +| `mcpListPrompts()`, `mcpListResources()`, `mcpListResourceTemplates()` | Return what the current identity sees in `prompts/list`, `resources/list` and `resources/templates/list`, every page. | + +| Assertion | Passes when | +| --- | --- | +| `assertMcpPromptMessages($expected)` | the last prompt returned these messages, in order, each as `['role' => ..., 'text' => ...]` (`text` is null for a message that is not text). | +| `assertMcpPromptContains($text)` | a text message of the last prompt contains `$text`. | +| `assertMcpPromptError(?$contains)` | the last prompt was answered with a JSON-RPC error: an unknown prompt, a missing argument, a prompt that failed. | +| `assertMcpResourceText($text, ?$mimeType)` | a content of the last resource read has exactly this text, and this MIME type when given. | +| `assertMcpResourceContains($text)` | a text content of the last resource read contains `$text`. | +| `assertMcpResourceError(?$contains)` | the last resource read was answered with a JSON-RPC error: an unknown URI or a resource that failed. The SDK sends `Error while reading resource` for an exception, not its message. | +| `assertMcpCompletionValues($values)` | the last completion returned these values, in order. | +| `assertMcpCompletionContains($value)` | the values of the last completion include `$value`. | +| `assertMcpPromptListed($name)`, `assertMcpPromptNotListed($name)` | the current identity sees, or does not see, the prompt in `prompts/list`. | +| `assertMcpResourceListed($uri)`, `assertMcpResourceNotListed($uri)` | the same for a resource in `resources/list`. | +| `assertMcpResourceTemplateListed($uriTemplate)`, `assertMcpResourceTemplateNotListed($uriTemplate)` | the same for a template in `resources/templates/list`. | + +`assertMcpPromptListedFor($identity, $name)`, `assertMcpPromptNotListedFor()`, +`assertMcpResourceListedFor($identity, $uri)` and +`assertMcpResourceNotListedFor()` check what another identity sees, like +`assertMcpToolListedFor()`, and leave the test's own identity as it was. +`assertMcpPromptDenied()` and `assertMcpResourceDenied()` check that the last +get or read was refused by your authorizer (see +[Authorization](authorization.md#resources-and-prompts)). + +The `NotListed` assertions also check that the prompt, resource or template +exists, so a typo cannot pass as hidden. `mcpResponse()` and +`assertMcpJsonRpcError()` work on the last of all these calls. The tests that +`bin/cake bake mcp_resource` and `bin/cake bake mcp_prompt` write use these +helpers. + +## 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 diff --git a/docs/tools.md b/docs/tools.md index c9c0446..b1a1546 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -19,7 +19,70 @@ 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. -## Example returning structured data +## 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. +- 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; +use Mcp\Capability\Attribute\Schema; + +/** + * Orders in a date range. + * + * @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. Leave it out for all. + */ +#[McpTool(name: 'list_orders')] +public function list( + #[Schema(format: 'date')] ?string $from = null, + #[Schema(enum: ['open', 'closed'])] string $status = 'open', + array $facilities = [], +): array { + // ... +} +``` + +`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. + +## 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. 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: ```php namespace App\Mcp; @@ -51,6 +114,234 @@ class OrderTools } ``` +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 +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)). + +## 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. + +## 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 + 'maxResultBytes' => 65536, // the most JSON one find_tools or call_tools answer holds + ], +], +``` + +- `find_tools` takes a `query` (words to look for, at most 200 characters) and + a `limit` (1 to 50, default 10), and returns the matching tools with their + descriptions and input schemas, best matches first. It looks in the tool + names, titles and descriptions, in the names and descriptions of their + arguments, and, with less weight, in the rest of the input schema: allowed + values (`enum`, `const`, `examples`) and nested arguments, so `celsius` finds + a tool whose `unit` is `celsius` or `fahrenheit`. Words are matched in any language (`año` is one word, not `a` and + `o`), without regard to case. It only returns tools the caller may call. The + tools it returns take at most `maxResultBytes` of JSON (64 KiB by default; the + first match is returned even when it alone is larger); `hasMore` is `true` when more + tools matched than it returned, so the model can search with other words or + a smaller `limit`. +- `call_tools` takes `calls`, a list of `{"name": ..., "arguments": {...}}`, runs + them in order and returns each result. It stops at the first error. Its + results take at most `maxResultBytes` of JSON too: a tool whose output does + not fit has still run, so its result says so (`outputLeftOut`, with the size) + and tells the model to call it on its own for the output rather than run it + again for its effects; the calls after it are not run, and each says so + (`notRun`). + +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. The two names are the catalog's: +with the catalog on, a tool of your own with one of them (discovered or added +in `Mcp.server.configure`) stops the server from being built, with a message +that names it. + +Hosts ask the user before running a tool they do not know to be safe, and an +"always allow" for `call_tools` covers every tool in the catalog. `find_tools` +returns each tool's annotations (`readOnlyHint`, `destructiveHint`) so the +model knows what it is about to run, but keep tools that change or delete data +out of the catalog unless that blanket approval is acceptable. A tool run by +`call_tools` does not get the caller's progress token. The audit record of the +`call_tools` call itself never holds what the tools it ran returned; when one +fails, its `error` names that tool with the first text of its error (`b failed: +`). + +A tool that returns an `InputRequiredResult` cannot finish inside `call_tools`, +in either protocol revision: the client would answer by sending the whole batch +again, and the tools before it would run a second time. So that call ends with +the tool error ` needs input from the user: call it on its own, not +through call_tools.`, the results of the calls before it are kept, and its +audit record carries its name. An elicitation through `ClientGateway` is +different in each revision. In the 2025-11-25 revision (the one with the +`initialize` handshake) the request goes to the client over the session and the +tool goes on with the answer, inside `call_tools` too. In the 2026-07-28 +revision it would turn the whole batch into an `input_required` answer, so the +call ends with the same tool error. Keep such tools out of the catalog, or let +the model call them directly. The same goes for a tool that needs a client +capability the client did not declare (` needs a capability the client +did not declare: ...`), and for anything a tool or the authorizer throws +(`Error while executing tool`, the exception in the `mcp` log): that call +fails, the ones before it keep their results, and it has its own audit +record. + +Tools with an app (`#[McpApp]`, see [MCP Apps](apps.md)) never go behind the +catalog, even when a pattern matches them: they stay in `tools/list`, where the +host reads their app. + +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, +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. The +strings `"false"`, `"0"`, `"off"`, `"no"` and `""` (any case) count as off, so +`env('FEATURE_REPORTS', false)` with `FEATURE_REPORTS=false` in `.env` turns +the element off. 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 `#[McpWhen]` on a method adds to the one on its class: both must +hold, so a class that is off keeps all its methods off. As with any PHP +attribute, a `#[McpWhen]` on a parent class does not reach the classes that +extend it: put it on each class whose elements it should cover. 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, four 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 +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. `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 +`--force` overwrites an existing file. A class baked into a plugin lands in +`plugins/Shop/src/Mcp`, outside the default `Mcp.discovery.scanDirs` +(`src/Mcp` of the application): add its path, relative to the application +root (`plugins/Shop/src/Mcp`), to `scanDirs`, or +the server and the baked test do not find the tool. + ## Annotations Annotations tell the client how a tool behaves. Clients such as Claude use them @@ -148,18 +439,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.'; @@ -213,3 +506,32 @@ 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. + +Prompts take arguments too. `ToolValidation::checkPrompt()` runs the same +check in a prompt method, and the client gets the same lines as the error of +`prompts/get`. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index f401310..4196557 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 @@ -49,6 +50,15 @@ Before 2.0.0 (in the 2.x betas) the `oauth` and `external` modes answered the same request with a `400` Bearer `invalid_request` challenge, which clients read as a token problem. +## 400 "header is not valid UTF-8" + +A request whose `Mcp-Method`, `Mcp-Name`, `Mcp-Param-*`, `Mcp-Session-Id` or +`MCP-Protocol-Version` header is not valid UTF-8 is refused with `400` and a +JSON-RPC `-32600` error that names the header. These headers mirror the JSON +body, which is UTF-8, so the client is sending them wrong: a header value that +is not ASCII must be sent the way the MCP specification says (the +`=?base64?...?=` form), not as raw bytes in another encoding. + ## 403 or a redirect to the login page (cakedc/users) On a `cakedc/users` host, `RequestAuthorizationMiddleware` authorizes the @@ -85,8 +95,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/phpcs.xml b/phpcs.xml index ea48954..1c0f878 100644 --- a/phpcs.xml +++ b/phpcs.xml @@ -10,4 +10,5 @@ tests/Conformance/Sdk/* tests/Conformance/tmp/* tests/Conformance/results/* + tests/Conformance/results-client/* diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 31270e4..5c0ec77 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -4,6 +4,9 @@ bootstrap="tests/bootstrap_suite.php" cacheDirectory=".phpunit.cache" colors="true"> + + + tests/TestCase/ 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 @@ +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..b0380bb --- /dev/null +++ b/src/App/AppTools.php @@ -0,0 +1,58 @@ +getTools()->references as $tool) { + $reference = $registry->getTool($tool->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/App/AppView.php b/src/App/AppView.php new file mode 100644 index 0000000..60ea77d --- /dev/null +++ b/src/App/AppView.php @@ -0,0 +1,52 @@ + $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(); + + // Hosts validate `_meta.ui`, `csp` and `permissions` as objects: an empty one would be sent as `[]`, a list. + $ui = $meta?->jsonSerialize() ?? []; + foreach (['csp', 'permissions'] as $key) { + $value = $ui[$key] ?? null; + if ($value instanceof JsonSerializable && $value->jsonSerialize() === []) { + unset($ui[$key]); + } + } + + return new TextResourceContents($uri, McpApps::MIME_TYPE, $html, $ui === [] ? null : ['ui' => $ui]); + } +} 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/Attribute/McpWhen.php b/src/Attribute/McpWhen.php new file mode 100644 index 0000000..0416cd8 --- /dev/null +++ b/src/Attribute/McpWhen.php @@ -0,0 +1,72 @@ +config !== null) { + $value = Configure::read($this->config); + // An env() value is a string: "false", "off" or "no" in a .env file means off. + if (is_string($value)) { + return !in_array(strtolower(trim($value)), ['', '0', 'false', 'off', 'no'], true); + } + + return (bool)$value; + } + 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/Audit/AuditRecord.php b/src/Audit/AuditRecord.php index 0fe6555..4d586ca 100644 --- a/src/Audit/AuditRecord.php +++ b/src/Audit/AuditRecord.php @@ -38,6 +38,8 @@ 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. + * @param bool $app Whether the tool is for MCP Apps only. */ public function __construct( public readonly string $method, @@ -50,6 +52,8 @@ public function __construct( public readonly array $arguments, public readonly ?string $error, public readonly ?int $durationMs, + public readonly ?string $via = null, + public readonly bool $app = false, ) { } @@ -80,6 +84,6 @@ public function toArray(): array 'arguments' => $this->arguments, 'error' => $this->error, 'durationMs' => $this->durationMs, - ]; + ] + ($this->via === null ? [] : ['via' => $this->via]) + ($this->app ? ['app' => true] : []); } } diff --git a/src/Audit/AuditSettings.php b/src/Audit/AuditSettings.php index 7d68006..82ba4b0 100644 --- a/src/Audit/AuditSettings.php +++ b/src/Audit/AuditSettings.php @@ -26,6 +26,8 @@ final class AuditSettings * @param bool $arguments Record the call arguments. * @param list $redact Argument names whose value is hidden, lower case. * @param int $maxLength Longest string value kept, in characters. + * @param string $server The server. + * @param array $route The values of the server's route parameters, which records carry. */ private function __construct( public readonly bool $enabled, @@ -34,18 +36,22 @@ private function __construct( public readonly bool $arguments, public readonly array $redact, public readonly int $maxLength, + public readonly string $server = McpConfig::DEFAULT_SERVER, + public readonly array $route = [], ) { } /** * Reads and validates `Mcp.audit`. * + * @param string $server The MCP server whose audit settings to read. + * @param array $route The values of its route's parameters, which records carry. * @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, array $route = []): 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 +86,8 @@ public static function fromConfig(): self self::flag($audit['arguments'], 'arguments'), array_map('strtolower', $redact), $maxLength, + $server, + $route, ); } diff --git a/src/Audit/AuditWriter.php b/src/Audit/AuditWriter.php index da9fa23..6f59fca 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,14 @@ 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; + } + if ($this->settings->route !== []) { + $data['route'] = $this->settings->route; + } + 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 +126,22 @@ 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->route !== []) { + $pairs = []; + foreach ($this->settings->route as $name => $value) { + $pairs[] = $name . ':' . $value; + } + $line .= ' route=' . $this->field(implode(',', $pairs)); + } + 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/Authorization/ContentGate.php b/src/Authorization/ContentGate.php new file mode 100644 index 0000000..6e12377 --- /dev/null +++ b/src/Authorization/ContentGate.php @@ -0,0 +1,119 @@ +set($this->identity->get()); + + return new self($this->authorizer, $identity, $this->trusted, $this->templateOf); + } + + /** + * Whether the authorizer decides for resources or prompts at all; when not, nothing is filtered. + * + * @return bool + */ + public function active(): bool + { + return $this->decidesResources() || $this->decidesPrompts(); + } + + /** + * Whether the authorizer can give callers different resources: it implements `ResourceAuthorizerInterface` + * and, for `RbacToolAuthorizer`, has rules for controller `Resources`. + * + * @return bool + */ + public function decidesResources(): bool + { + return !$this->trusted && $this->authorizer instanceof ResourceAuthorizerInterface && ( + !$this->authorizer instanceof RbacToolAuthorizer + || $this->authorizer->decidesFor(RbacToolAuthorizer::RESOURCES) + ); + } + + /** + * Whether the authorizer can give callers different prompts. + * + * @return bool + */ + public function decidesPrompts(): bool + { + return !$this->trusted && $this->authorizer instanceof PromptAuthorizerInterface && ( + !$this->authorizer instanceof RbacToolAuthorizer + || $this->authorizer->decidesFor(RbacToolAuthorizer::PROMPTS) + ); + } + + /** + * @param string $uri A resource URI, a concrete URI read through a template, or a template's URI. + * @return bool + */ + public function allowsResource(string $uri): bool + { + return $this->trusted + || !$this->authorizer instanceof ResourceAuthorizerInterface + || $this->authorizer->canReadResource($this->identity->get(), $uri); + } + + /** + * Whether a URI may be read, subscribed to or completed: the URI itself is allowed and, when a resource + * template serves it, so is the template's URI. A template that is denied denies every URI it serves. + * + * @param string $uri A resource URI or a concrete URI a template serves. + * @return bool + */ + public function allowsRead(string $uri): bool + { + if (!$this->allowsResource($uri)) { + return false; + } + $template = $this->trusted || $this->templateOf === null ? null : ($this->templateOf)($uri); + + return $template === null || $template === $uri || $this->allowsResource($template); + } + + /** + * @param string $name The prompt name. + * @return bool + */ + public function allowsPrompt(string $name): bool + { + return $this->trusted + || !$this->authorizer instanceof PromptAuthorizerInterface + || $this->authorizer->canGetPrompt($this->identity->get(), $name); + } +} diff --git a/src/Authorization/ContentGuard.php b/src/Authorization/ContentGuard.php new file mode 100644 index 0000000..30ecbfb --- /dev/null +++ b/src/Authorization/ContentGuard.php @@ -0,0 +1,86 @@ + + */ +final class ContentGuard implements RequestHandlerInterface +{ + /** + * @param \CakeDC\Mcp\Authorization\ContentGate $gate The gate. + */ + public function __construct(private readonly ContentGate $gate) + { + } + + /** + * @inheritDoc + */ + public function supports(Request $request): bool + { + return match (true) { + $request instanceof ReadResourceRequest, + $request instanceof ResourceSubscribeRequest, + $request instanceof ResourceUnsubscribeRequest => !$this->gate->allowsRead($request->uri), + $request instanceof GetPromptRequest => !$this->gate->allowsPrompt($request->name), + $request instanceof CompletionCompleteRequest => $request->ref instanceof PromptReference + ? !$this->gate->allowsPrompt($request->ref->name) + : !$this->gate->allowsRead($request->ref->uri), + default => false, + }; + } + + /** + * @param \Mcp\Schema\JsonRpc\Request $request The request. + * @param \Mcp\Server\Session\SessionInterface $session The session. + * @return \Mcp\Schema\JsonRpc\Error What the SDK answers for an unknown element. + */ + public function handle(Request $request, SessionInterface $session): Error + { + if ($request instanceof CompletionCompleteRequest) { + // The SDK's answer to a reference it does not have: a bad parameter. + $message = $request->ref instanceof PromptReference + ? (new PromptNotFoundException($request->ref->name))->getMessage() + : (new ResourceNotFoundException($request->ref->uri))->getMessage(); + + return Error::forInvalidParams($message, $request->getId()); + } + if ($request instanceof GetPromptRequest) { + $message = (new PromptNotFoundException($request->name))->getMessage(); + + return Error::forInvalidParams($message, $request->getId()); + } + $uri = $request instanceof ReadResourceRequest + || $request instanceof ResourceSubscribeRequest + || $request instanceof ResourceUnsubscribeRequest + ? $request->uri + : ''; + $message = (new ResourceNotFoundException($uri))->getMessage(); + + return (new RequestContext($session, $request))->getProtocolVersion()->usesInvalidParamsForResourceNotFound() + ? Error::forInvalidParams($message, $request->getId(), ['uri' => $uri]) + : Error::forResourceNotFound($message, $request->getId()); + } +} diff --git a/src/Authorization/ContentNotificationBus.php b/src/Authorization/ContentNotificationBus.php new file mode 100644 index 0000000..a1cda6c --- /dev/null +++ b/src/Authorization/ContentNotificationBus.php @@ -0,0 +1,68 @@ +bus->publish($notification); + } + + /** + * @inheritDoc + */ + public function cursor(): int + { + $this->pinned ??= $this->gate->pinned(); + + return $this->bus->cursor(); + } + + /** + * @inheritDoc + */ + public function since(int $cursor): array + { + $gate = $this->pinned ??= $this->gate->pinned(); + [$notifications, $next] = $this->bus->since($cursor); + $readable = array_values(array_filter( + $notifications, + fn(Notification $notification): bool => !$notification instanceof ResourceUpdatedNotification + || $gate->allowsRead($notification->uri), + )); + + return [$readable, $next]; + } +} diff --git a/src/Authorization/PromptAuthorizerInterface.php b/src/Authorization/PromptAuthorizerInterface.php new file mode 100644 index 0000000..636607f --- /dev/null +++ b/src/Authorization/PromptAuthorizerInterface.php @@ -0,0 +1,21 @@ + + */ + private array $decides = []; + /** * @param \CakeDC\Auth\Rbac\RbacInterface|array $rbac An Rbac instance, or the config for one. */ @@ -47,6 +59,65 @@ public function permissions(): array * @inheritDoc */ public function canCall(mixed $identity, string $tool): bool + { + return $this->check($identity, self::CONTROLLER, $tool); + } + + /** + * Resource `X` is checked as controller `Resources`, action `X` (the URI read, or a template's URI when + * templates are listed or completed). Only when a rule names plugin `CakeDC/Mcp` and controller `Resources`: + * with no such rule every resource stays readable, as in 2.1. + * + * @inheritDoc + */ + public function canReadResource(mixed $identity, string $uri): bool + { + return !$this->decidesFor(self::RESOURCES) || $this->check($identity, self::RESOURCES, $uri); + } + + /** + * Prompt `X` is checked as controller `Prompts`, action `X`, only when a rule names plugin `CakeDC/Mcp` and + * controller `Prompts`: with no such rule every prompt stays available, as in 2.1. + * + * @inheritDoc + */ + public function canGetPrompt(mixed $identity, string $name): bool + { + return !$this->decidesFor(self::PROMPTS) || $this->check($identity, self::PROMPTS, $name); + } + + /** + * Whether a rule names plugin `CakeDC/Mcp` (exactly, or in a list) and $controller (exactly, or in a list). + * Wildcards do not count, so a 2.1 rule set, or a host rule for a controller of its own with that name, + * changes nothing. + * + * @internal Used by `bin/cake mcp check`; not part of the public API. + * @param string $controller `Resources` or `Prompts`. + * @return bool + */ + public function decidesFor(string $controller): bool + { + if (!isset($this->decides[$controller])) { + $names = fn(mixed $value, string $name): bool => $value === $name + || (is_array($value) && in_array($name, $value, true)); + $this->decides[$controller] = array_filter( + $this->permissions(), + fn(mixed $rule): bool => is_array($rule) + && $names($rule['plugin'] ?? null, self::PLUGIN) + && $names($rule['controller'] ?? null, $controller), + ) !== []; + } + + return $this->decides[$controller]; + } + + /** + * @param mixed $identity The identity. + * @param string $controller The controller. + * @param string $action The action. + * @return bool + */ + private function check(mixed $identity, string $controller, string $action): bool { if (!is_array($identity) && !$identity instanceof ArrayAccess) { return false; @@ -55,8 +126,8 @@ public function canCall(mixed $identity, string $tool): bool $request = (new ServerRequest(['url' => '/mcp']))->withAttribute('params', [ 'plugin' => self::PLUGIN, 'prefix' => null, - 'controller' => self::CONTROLLER, - 'action' => $tool, + 'controller' => $controller, + 'action' => $action, '_ext' => null, 'pass' => [], ]); diff --git a/src/Authorization/ResourceAuthorizerInterface.php b/src/Authorization/ResourceAuthorizerInterface.php new file mode 100644 index 0000000..9907e27 --- /dev/null +++ b/src/Authorization/ResourceAuthorizerInterface.php @@ -0,0 +1,24 @@ + $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/Bake/McpBakeCommand.php b/src/Bake/McpBakeCommand.php new file mode 100644 index 0000000..4987cb7 --- /dev/null +++ b/src/Bake/McpBakeCommand.php @@ -0,0 +1,152 @@ +kind(); + } + + /** + * Refuses a name that is not a class name (`Admin/ListOrders`, `list-orders`, `2fa`), which would write a file + * of invalid PHP. + * + * @inheritDoc + */ + public function execute(Arguments $args, ConsoleIo $io): ?int + { + $raw = $args->getArgumentAt(0); + if (is_string($raw) && $raw !== '') { + [, $name] = pluginSplit($raw); + if (preg_match('/^[A-Za-z][A-Za-z0-9_]*$/', $name) !== 1) { + $io->error(sprintf( + '"%s" is not a class name: use letters, digits and "_", starting with a letter (ListOrders).', + $name, + )); + + return static::CODE_ERROR; + } + } + + return parent::execute($args, $io); + } + + /** + * @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 + { + // `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), + '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/Catalog/CatalogPatterns.php b/src/Catalog/CatalogPatterns.php new file mode 100644 index 0000000..5639527 --- /dev/null +++ b/src/Catalog/CatalogPatterns.php @@ -0,0 +1,64 @@ + $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 + { + // fnmatch() raises a ValueError for a NUL byte, which no tool name has. + if ($tool === ToolCatalog::FIND || $tool === ToolCatalog::CALL || str_contains($tool, "\0")) { + return false; + } + foreach ($patterns as $pattern) { + if (fnmatch($pattern, $tool)) { + return true; + } + } + + return false; + } + + /** + * The one rule for "this tool is behind the catalog", used by `tools/list`, `find_tools`, `call_tools`, + * `bin/cake mcp check` and `McpTestTrait`: it matches a pattern and has no app. An app-only tool is for the + * app's page, and a tool that links to an app must stay in `tools/list`, where the host reads its `_meta.ui`. + * + * @param list $patterns `Mcp.catalog.tools`. + * @param string $tool A tool name. + * @param array|null $meta The tool's `_meta`. + * @return bool + */ + public static function catalogues(array $patterns, string $tool, ?array $meta): bool + { + return self::matches($patterns, $tool) && self::keptOut($meta) === null; + } + + /** + * Why a tool that matches a pattern stays out of the catalog, or null when it does not. + * + * @param array|null $meta The tool's `_meta`. + * @return string|null `app-only` or `links to an app`. + */ + public static function keptOut(?array $meta): ?string + { + $ui = is_array($meta['ui'] ?? null) ? $meta['ui'] : []; + if (($ui['visibility'] ?? null) === ['app']) { + return 'app-only'; + } + if (is_string($ui['resourceUri'] ?? null) && $ui['resourceUri'] !== '') { + return 'links to an app'; + } + + return null; + } +} 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 new file mode 100644 index 0000000..77b0b74 --- /dev/null +++ b/src/Catalog/ToolCatalog.php @@ -0,0 +1,593 @@ + $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. + * @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. + * @param int $maxResultBytes `Mcp.catalog.maxResultBytes`. + */ + public function __construct( + private readonly RegistryInterface $registry, + private readonly ToolGate $gate, + private readonly array $patterns, + private readonly int $maxCalls, + private readonly ReferenceHandlerInterface $references, + private readonly LoggerInterface $logger, + private readonly ?ScopePolicy $policy = null, + private readonly ?EventDispatcherInterface $events = null, + private readonly bool $normalize = false, + private readonly int $maxResultBytes = self::MAX_RESULT_BYTES, + ) { + $this->made = new WeakMap(); + } + + /** + * The requests this catalog made for the tools it ran: the audit marks them `via=call_tools`. Kept out of + * band, so a client cannot claim it through the request's `_meta`. + * + * @var \WeakMap<\Mcp\Schema\JsonRpc\Request, true> + */ + private WeakMap $made; + + /** + * Whether $request is one this catalog made for a tool it ran. + * + * @param \Mcp\Schema\JsonRpc\Request $request A request. + * @return bool + */ + public function made(Request $request): bool + { + return isset($this->made[$request]); + } + + /** + * Whether $tool is in the catalog of this server. + * + * @param string $tool A tool name. + * @return bool + */ + public function has(string $tool): bool + { + return $this->registry->hasTool($tool) + && CatalogPatterns::catalogues($this->patterns, $tool, $this->registry->getTool($tool)->tool->meta); + } + + /** + * Finds catalogued tools the caller may call, best matches first, as many as $limit and maxResultBytes allow. + * + * @param \Mcp\Server\RequestContext $context The call (injected by the SDK). + * @param string $query Words to look for in the tool names, titles, descriptions and the names and descriptions + * of their arguments. Empty: every tool. + * @param int $limit How many tools, 1 to 50. + * @return array{tools: list>, hasMore: bool} + * @throws \Mcp\Exception\ToolCallException With a query longer than MAX_QUERY_LENGTH. + */ + public function find(RequestContext $context, string $query = '', int $limit = 10): array + { + if (mb_strlen($query) > self::MAX_QUERY_LENGTH) { + throw new ToolCallException(sprintf( + 'The query is too long: at most %d characters. Use a few words.', + self::MAX_QUERY_LENGTH, + )); + } + // Words of any script, so a query in another language matches whole words, not their ASCII letters. + $terms = preg_split('/[^\p{L}\p{N}]+/u', mb_strtolower($query), -1, PREG_SPLIT_NO_EMPTY) ?: []; + $ranked = []; + foreach ($this->registry->getTools()->references as $tool) { + $name = $tool->name; + if (!$this->callable($name, $context)) { + 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]); + $limit = max(1, min(50, $limit)); + $tools = []; + $bytes = 2; + foreach ($ranked as [, $tool]) { + if (count($tools) >= $limit) { + break; + } + $entry = [ + 'name' => $tool->name, + 'title' => $tool->title, + 'description' => $tool->description, + // A host asks before calling a tool it does not know to be read-only: tell the model what it is. + 'annotations' => $tool->annotations?->jsonSerialize(), + 'inputSchema' => $this->normalize + ? SchemaNormalizer::normalize($tool->inputSchema) + : $tool->inputSchema, + ]; + $size = strlen((string)json_encode($entry)) + 1; + if ($bytes + $size > $this->maxResultBytes && $tools !== []) { + break; + } + $bytes += $size; + $tools[] = $entry; + } + + return ['tools' => $tools, 'hasMore' => count($tools) < count($ranked)]; + } + + /** + * 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; + $full = null; + $bytes = 2; + foreach (array_values($calls) as $index => $call) { + $name = is_array($call) && is_string($call['name'] ?? null) ? $call['name'] : ''; + if ($full !== null) { + // The answer is full: what comes after is not run, and says so. + $results[] = $this->notRun($name, $full); + continue; + } + $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)); + $size = strlen((string)json_encode($result, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)) + 1; + if ($bytes + $size > $this->maxResultBytes) { + // The tool ran, so its result is never dropped silently: the model must not repeat its effects. + $result = $this->leftOut($name, $size, (bool)$result['isError']); + $full = $name; + $size = strlen((string)json_encode($result)) + 1; + } + $bytes += $size; + $results[] = $result; + if ($result['isError']) { + $failed = true; + break; + } + } + $data = ['results' => $results]; + + // The summary comes first: it is what the audit records for this call, never the output of the tools. + return new CallToolResult([ + new TextContent( + $full !== null && !$failed ? $this->fullSummary($results) : $this->summary($results, $failed), + ), + 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', + 'maxLength' => self::MAX_QUERY_LENGTH, + 'description' => 'Words to look for in tool names, descriptions and arguments. ' + . '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. + * @param \Mcp\Server\RequestContext $context The call, for its access token. + * @return bool + */ + private function callable(string $tool, RequestContext $context): bool + { + 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, $this->policy->expand($token->getScopes())) === []; + } + + /** + * @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 { + // Without the outer progress token: progress must increase, and each tool would start again from zero. + $meta = $context->getRequest()->getMeta() ?? []; + unset($meta['progressToken']); + $request = (new CallToolRequest($name, $arguments))->withId($id)->withMeta($meta === [] ? null : $meta); + $this->made[$request] = true; + $session = $context->getSession(); + $this->events?->dispatch(new RequestEvent($request, $session)); + // What is thrown here ends this call only, so the results of the calls before it are kept: a whole + // call_tools error (-32021 for a missing capability) would make the client send the batch again. + $thrown = null; + try { + if (!$this->callable($name, $context)) { + // Like a direct call: a denied tool answers as an unknown one. + $response = Error::forInvalidParams(sprintf('Tool not found: "%s".', $name), $id); + } else { + $response = $this->handle($handler, $request, $session, $context->getProtocolVersion()->isModern()); + } + } catch (MissingRequiredClientCapabilityException $e) { + $thrown = $e; + $response = Error::forInternalError(sprintf( + '%s needs a capability the client did not declare: call it on its own, not through call_tools.', + $name, + ), $id); + } catch (Throwable $e) { + $thrown = $e; + $this->logger->error('Unhandled error during tool execution', ['name' => $name, 'exception' => $e]); + // The message is left out, as for a direct call: it may hold what the caller must not see. + $response = Error::forInternalError('Error while executing tool', $id); + } + if ($response instanceof Error) { + $this->events?->dispatch(new ErrorEvent($response, $request, $session, $thrown)); + + return $this->error($name, $response->message); + } + if ($response === null || $response->result instanceof InputRequiredResult) { + // The client would answer by sending the whole batch again, and the tools before this one would run + // a second time: this call ends here instead, with what ran before it kept. + $response = new Response($id, new CallToolResult([new TextContent(sprintf( + '%s needs input from the user: call it on its own, not through call_tools.', + $name, + ))], true)); + } + $this->events?->dispatch(new ResponseEvent($response, $request, $session)); + $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; + } + + /** + * Runs one inner call. In the 2026-07-28 revision it runs in a fiber of its own, so a tool that asks the + * client (an elicitation through ClientGateway) is stopped there instead of turning the whole `call_tools` + * into an `input_required` answer. Notifications (progress, logs) go on to the client as before. + * + * @param \Mcp\Server\Handler\Request\CallToolHandler $handler The SDK handler. + * @param \Mcp\Schema\Request\CallToolRequest $request The inner request. + * @param \Mcp\Server\Session\SessionInterface $session The session. + * @param bool $modern Whether the call is in the 2026-07-28 revision. + * @return \Mcp\Schema\JsonRpc\Response<\Mcp\Schema\Result\CallToolResult|\Mcp\Schema\Result\InputRequiredResult>|\Mcp\Schema\JsonRpc\Error|null + * Null when the tool asked the client. + */ + private function handle( + CallToolHandler $handler, + CallToolRequest $request, + SessionInterface $session, + bool $modern, + ): Response|Error|null { + if (!$modern || Fiber::getCurrent() === null) { + return $handler->handle($request, $session); + } + $fiber = new Fiber(fn(): Response|Error => $handler->handle($request, $session)); + $suspended = $fiber->start(); + while (!$fiber->isTerminated()) { + if ($suspended instanceof RequestSuspension) { + // Left suspended: the fiber is dropped, which unwinds the tool. + return null; + } + $suspended = $fiber->resume(Fiber::suspend($suspended)); + } + + return $fiber->getReturn(); + } + + /** + * @param list> $results The results so far. + * @param bool $failed Whether the last one failed. + * @return string `3 calls ok: a, b, c`, or `b failed: ` after the ones that ran. + */ + private function summary(array $results, bool $failed): string + { + if (!$failed) { + return sprintf('%d calls ok: %s', count($results), implode(', ', array_column($results, 'name'))); + } + $last = end($results); + if ($last === false) { + return 'no calls'; + } + $content = is_array($last['content'] ?? null) ? $last['content'] : []; + $text = is_array($content[0] ?? null) ? ($content[0]['text'] ?? '') : ''; + + return sprintf('%s failed: %s', (string)$last['name'], is_string($text) ? $text : ''); + } + + /** + * @param string $name A tool that ran. + * @param int $size The bytes of its result. + * @param bool $isError Whether that result was an error. + * @return array{name: string, isError: bool, outputLeftOut: true, content: list} + */ + private function leftOut(string $name, int $size, bool $isError): array + { + return ['name' => $name, 'isError' => $isError, 'outputLeftOut' => true, 'content' => [[ + 'type' => 'text', + 'text' => sprintf( + '%s ran, but its output (%d bytes) was left out: one call_tools answer holds at most %d bytes. ' + . 'Do not run it again for its effects; call %s on its own to get its output.', + $name, + $size, + $this->maxResultBytes, + $name, + ), + ]]]; + } + + /** + * @param string $name A tool after the one that filled the answer. + * @param string $full The tool whose output filled it. + * @return array{name: string, isError: false, notRun: true, content: list} + */ + private function notRun(string $name, string $full): array + { + return ['name' => $name, 'isError' => false, 'notRun' => true, 'content' => [[ + 'type' => 'text', + 'text' => sprintf('%s was not run: the answer was full after %s. Call it again.', $name, $full), + ]]]; + } + + /** + * @param list> $results The results of an answer that filled up. + * @return string `3 calls: a, b ran (output left out for its size); c not run`. + */ + private function fullSummary(array $results): string + { + $parts = []; + $skipped = []; + foreach ($results as $result) { + $name = (string)$result['name']; + if (isset($result['notRun'])) { + $skipped[] = $name; + } elseif (isset($result['outputLeftOut'])) { + $parts[] = $name . ' ran (output left out for its size)'; + } else { + $parts[] = $name; + } + } + + return sprintf('%d calls: %s', count($results), implode(', ', $parts)) + . ($skipped === [] ? '' : '; ' . implode(', ', $skipped) . ' not run'); + } + + /** + * @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 6, title 4, description 2, the name or description of an argument 2, and + * the rest of the input schema (allowed values, nested arguments) 1. + */ + private function score(Tool $tool, array $terms): int + { + $arguments = []; + $properties = $tool->inputSchema['properties'] ?? []; + foreach (is_array($properties) ? $properties : [] as $property => $schema) { + $arguments[] = (string)$property; + if (is_array($schema) && is_string($schema['description'] ?? null)) { + $arguments[] = $schema['description']; + } + } + $rest = []; + foreach (is_array($properties) ? $properties : [] as $schema) { + if (is_array($schema)) { + self::schemaWords($schema, $rest); + } + } + // Each searched field with the points a query word found in it is worth. + $fields = [ + [$tool->name, 6], + [(string)$tool->title, 4], + [(string)$tool->description, 2], + [implode(' ', $arguments), 2], + [implode(' ', $rest), 1], + ]; + + return array_sum(array_map( + fn(array $field): int => (int)$field[1] * count(array_filter( + $terms, + fn(string $term): bool => str_contains(mb_strtolower($field[0]), $term), + )), + $fields, + )); + } + + /** + * Collects the words of an argument's schema below its own name and description: its allowed values (`enum`, + * `const`), and the names and descriptions of nested properties and list items, at every depth. + * + * @param array $schema An argument's schema. + * @param list $words Where the words go. + * @param int $depth How deep this is; deep or cyclic schemas stop at 10. + * @return void + */ + private static function schemaWords(array $schema, array &$words, int $depth = 0): void + { + if ($depth > 10) { + return; + } + foreach (['enum', 'examples'] as $key) { + foreach (is_array($schema[$key] ?? null) ? $schema[$key] : [] as $value) { + if (is_scalar($value)) { + $words[] = (string)$value; + } + } + } + if (is_scalar($schema['const'] ?? null)) { + $words[] = (string)$schema['const']; + } + $nested = is_array($schema['properties'] ?? null) ? $schema['properties'] : []; + foreach ($nested as $property => $child) { + $words[] = (string)$property; + if (is_array($child)) { + if (is_string($child['description'] ?? null)) { + $words[] = $child['description']; + } + self::schemaWords($child, $words, $depth + 1); + } + } + foreach (['items', 'additionalProperties'] as $key) { + if (is_array($schema[$key] ?? null)) { + self::schemaWords($schema[$key], $words, $depth + 1); + } + } + foreach (['anyOf', 'oneOf', 'allOf'] as $key) { + foreach (is_array($schema[$key] ?? null) ? $schema[$key] : [] as $child) { + if (is_array($child)) { + self::schemaWords($child, $words, $depth + 1); + } + } + } + } +} diff --git a/src/Client/CakeHttpClientFactory.php b/src/Client/CakeHttpClientFactory.php new file mode 100644 index 0000000..454c20a --- /dev/null +++ b/src/Client/CakeHttpClientFactory.php @@ -0,0 +1,55 @@ + $config->timeout, 'redirect' => 0]; + $proxy = ClientConfig::proxy(); + if ($proxy !== null) { + // The credentials stay in the URL, so curl sends them to the proxy only (Cake's `username` option + // would add a Proxy-Authorization header that reaches the server through the tunnel). + $options['proxy'] = ['proxy' => $proxy]; + // This machine directly: through the proxy a token for http://localhost would cross the network in + // clear and reach the proxy's own localhost. Nothing else bypasses it, whatever NO_PROXY says. + $options['curl'] = [CURLOPT_NOPROXY => implode(',', self::thisMachine($config))]; + } + + return new Client($options); + } + + /** + * The hosts the proxy is not used for: this machine's usual names, and each configured address the URL policy + * takes as this machine (all of 127.0.0.0/8 and `*.localhost`), named one by one so that no curl version + * needs to know address ranges. + * + * @param \CakeDC\Mcp\Client\ClientConfig $config The client. + * @return list + */ + private static function thisMachine(ClientConfig $config): array + { + $hosts = ['localhost', '127.0.0.1', '::1']; + $urls = [$config->url, $config->authorizationUrl, $config->tokenUrl, $config->revocationUrl, $config->issuer]; + foreach ($urls as $url) { + $host = is_string($url) ? strtolower(trim((string)parse_url($url, PHP_URL_HOST), '[]')) : ''; + if ($host !== '' && ServerUrlPolicy::isLocal($host)) { + $hosts[] = $host; + } + } + + return array_values(array_unique($hosts)); + } +} diff --git a/src/Client/CallsServerTrait.php b/src/Client/CallsServerTrait.php new file mode 100644 index 0000000..133fdc1 --- /dev/null +++ b/src/Client/CallsServerTrait.php @@ -0,0 +1,275 @@ +|null The raw `result` of the last answer to it. + */ + abstract protected function lastResult(string $method): ?array; + + /** + * Checks that the server answers: `ping`, or `server/discover` in the 2026-07-28 revision, which has no ping. + * + * @return void + */ + public function ping(): void + { + $this->run(fn(Client $client) => $client->ping()); + } + + /** + * @return \Mcp\Schema\Implementation|null The server's name, version and other details, from the handshake or + * `server/discover`. + */ + public function serverInfo(): ?Implementation + { + return $this->run(fn(Client $client): ?Implementation => $client->getServerInfo()); + } + + /** + * @return \Mcp\Schema\ServerCapabilities|null What the server declared it supports. + */ + public function capabilities(): ?ServerCapabilities + { + return $this->run(fn(Client $client): ?ServerCapabilities => $client->getServerCapabilities()); + } + + /** + * @return string|null The protocol revision the client and the server speak (`2026-07-28`, `2025-11-25`...): + * the one the handshake agreed, which may be another than `protocolVersion` asked for. + */ + public function protocolVersion(): ?string + { + return $this->run(fn(Client $client): ?string => $client->getProtocolVersion()?->value); + } + + /** + * @return string|null The server's instructions for the model, if it gives any. + */ + public function instructions(): ?string + { + return $this->run(fn(Client $client): ?string => $client->getInstructions()); + } + + /** + * @param int|null $limit At most this many; pages past it are not fetched. Null for every tool. + * @return list<\Mcp\Schema\Tool> The tools the server offers that the client's filters allow. + */ + public function listTools(?int $limit = null): array + { + $filter = $this->config()->toolFilter(); + $tools = []; + $list = fn(Client $client, ?string $cursor) => $client->listTools($cursor); + foreach ($this->pages('tools/list', ListToolsResult::class, $list, $limit) as $page) { + foreach ($page->tools as $tool) { + if ($filter->allows($tool->name)) { + $tools[] = $tool; + } + } + if ($limit !== null && count($tools) >= $limit) { + break; + } + } + + return self::limited($tools, $limit); + } + + /** + * @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)); + } + + /** + * @param int|null $limit At most this many; pages past it are not fetched. Null for every resource. + * @return list<\Mcp\Schema\ResourceDefinition> The server's resources. + */ + public function listResources(?int $limit = null): array + { + $resources = []; + $list = fn(Client $client, ?string $cursor) => $client->listResources($cursor); + foreach ($this->pages('resources/list', ListResourcesResult::class, $list, $limit) as $page) { + array_push($resources, ...array_values($page->resources)); + if ($limit !== null && count($resources) >= $limit) { + break; + } + } + + return self::limited($resources, $limit); + } + + /** + * @param int|null $limit At most this many; pages past it are not fetched. Null for every template. + * @return list<\Mcp\Schema\ResourceTemplate> The server's resource templates. + */ + public function listResourceTemplates(?int $limit = null): array + { + $templates = []; + $list = fn(Client $client, ?string $cursor) => $client->listResourceTemplates($cursor); + foreach ($this->pages('resources/templates/list', ListResourceTemplatesResult::class, $list, $limit) as $page) { + array_push($templates, ...array_values($page->resourceTemplates)); + if ($limit !== null && count($templates) >= $limit) { + break; + } + } + + return self::limited($templates, $limit); + } + + /** + * @param string $uri The resource. + * @return \Mcp\Schema\Result\ReadResourceResult From the list cache when it holds a fresh read for this caller. + */ + public function readResource(string $uri): ReadResourceResult + { + $cache = $this->listCache(); + $cached = $cache?->get('resources/read', $uri); + if ($cached instanceof ReadResourceResult) { + return $cached; + } + $read = $this->run(fn(Client $client): ReadResourceResult => $client->readResource($uri)); + $result = $cache === null ? null : $this->lastResult('resources/read'); + if ($cache !== null && $result !== null) { + $cache->put('resources/read', $uri, $result, $read); + } + + return $read; + } + + /** + * @param int|null $limit At most this many; pages past it are not fetched. Null for every prompt. + * @return list<\Mcp\Schema\Prompt> The server's prompts. + */ + public function listPrompts(?int $limit = null): array + { + $prompts = []; + $list = fn(Client $client, ?string $cursor) => $client->listPrompts($cursor); + foreach ($this->pages('prompts/list', ListPromptsResult::class, $list, $limit) as $page) { + array_push($prompts, ...array_values($page->prompts)); + if ($limit !== null && count($prompts) >= $limit) { + break; + } + } + + return self::limited($prompts, $limit); + } + + /** + * @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)); + } + + /** + * The pages of a list, fetched as they are read, each from the list cache when it holds a fresh one for this + * caller. + * + * @template P of \Mcp\Schema\Result\ListToolsResult|\Mcp\Schema\Result\ListResourcesResult|\Mcp\Schema\Result\ListResourceTemplatesResult|\Mcp\Schema\Result\ListPromptsResult + * @param string $method The list method. + * @param class-string

    $class The result class. + * @param callable(\Mcp\Client, ?string): P $list Lists one page. + * @param int|null $limit The caller's limit, checked before any page is fetched. + * @return \Generator + * @throws \InvalidArgumentException When $limit is below 1. + */ + private function pages(string $method, string $class, callable $list, ?int $limit = null): Generator + { + if ($limit !== null && $limit < 1) { + throw new InvalidArgumentException('A list limit must be 1 or more.'); + } + $cache = $this->listCache(); + $cursor = null; + $left = self::$maxPages; + do { + $cached = $cache?->get($method, $cursor); + if ($cached instanceof $class) { + $page = $cached; + } else { + $page = $this->run(fn(Client $client) => $list($client, $cursor)); + $result = $cache === null ? null : $this->lastResult($method); + if ($cache !== null && $result !== null) { + $cache->put($method, $cursor, $result, $page); + } + } + yield $page; + $cursor = $page->nextCursor; + $left--; + } while ($cursor !== null && $cursor !== '' && $left > 0); + } + + /** + * @template I + * @param list $items The items. + * @param int|null $limit At most this many. + * @return list + */ + private static function limited(array $items, ?int $limit): array + { + return $limit === null ? $items : array_slice($items, 0, $limit); + } +} diff --git a/src/Client/ClientConfig.php b/src/Client/ClientConfig.php new file mode 100644 index 0000000..be48b6f --- /dev/null +++ b/src/Client/ClientConfig.php @@ -0,0 +1,773 @@ + + */ + public const SETTINGS = [ + 'route' => '/mcp-client', + 'store' => TableConnectionStore::class, + 'encryptionKey' => null, + 'name' => 'CakePHP MCP Client', + 'version' => '1.0.0', + 'refreshLeeway' => 60, + 'maxResponseBytes' => 1024 * 1024, + 'identityAttribute' => 'identity', + 'proxy' => null, + ]; + + /** + * Keys a client config may have. + * + * @var list + */ + public const KEYS = [ + 'url', 'token', 'headers', 'command', 'args', 'env', 'cwd', 'auth', 'timeout', 'tools', 'protocolVersion', + 'allowInsecure', 'clientId', 'clientSecret', 'scopes', 'authorizationUrl', 'tokenUrl', 'revocationUrl', + 'issuer', 'allowPrivateNetwork', 'registration', 'cache', + ]; + + /** + * Values of `registration`: how a user mode client without a configured `clientId` gets one. + * + * @var list + */ + public const REGISTRATIONS = ['auto', 'metadata', 'dynamic']; + + /** + * @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`, `user` or `client_credentials`. + * @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. + * @param string|null $issuer With configured endpoints, the issuer the authorization server names itself by, + * compared with the `iss` of its sign-in responses; null to skip that comparison. + * @param \Closure|null $tokenProvider A `token` given as a callable, called for each request. + * @param bool $allowPrivateNetwork Whether the OAuth endpoints learned for this client may resolve to private, + * loopback or link-local addresses (plain http also needs `allowInsecure`). + * @param string $registration `auto`, `metadata` or `dynamic`: see `REGISTRATIONS`. + * @param string|null $cache The Cake cache config list results with cache hints are kept in; null for none. + */ + 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, + public readonly ?string $issuer = null, + public readonly ?Closure $tokenProvider = null, + public readonly bool $allowPrivateNetwork = false, + public readonly string $registration = 'auto', + public readonly ?string $cache = null, + ) { + } + + /** + * Whether $token can go in an `Authorization` header: visible ASCII only (RFC 6750 tokens are). + * + * @param string $token The token, trimmed. + * @return bool + */ + private static function headerSafe(string $token): bool + { + return preg_match('/^[\x21-\x7E]+$/', $token) === 1; + } + + /** + * The token of a `token` callable, for one request. + * + * @return string|null Null when `token` is not a callable. + * @throws \CakeDC\Mcp\Client\Exception\ClientException When the callable returns no token. + */ + public function callableToken(): ?string + { + if ($this->tokenProvider === null) { + return null; + } + $token = ($this->tokenProvider)(); + if (!is_string($token) || trim($token) === '') { + throw new ClientException(sprintf( + 'The callable of "Mcp.clients.%s.token" returned %s, not a token string.', + $this->name, + get_debug_type($token), + )); + } + $token = trim($token); + if (!self::headerSafe($token)) { + throw new ClientException(sprintf( + 'The token the callable of "Mcp.clients.%s.token" returned has characters an HTTP header cannot carry.', + $this->name, + )); + } + + return $token; + } + + /** + * @return bool Whether each user signs in (`auth` `user`). + */ + public function isUser(): bool + { + return $this->auth === self::USER; + } + + /** + * @return bool Whether the application gets its own token (`auth` `client_credentials`). + */ + public function isClientCredentials(): bool + { + return $this->auth === self::CLIENT_CREDENTIALS; + } + + /** + * @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; + } + + /** + * What is wrong with `Mcp.client.route`, the base path of the sign-in routes, or null when it is a path. + * + * @return string|null + */ + public static function routeError(): ?string + { + $route = self::setting('route'); + if (is_string($route) && trim($route, '/') !== '') { + return null; + } + + return '"Mcp.client.route" must be the path the sign-in routes of user mode clients go under, such as ' + . '"/mcp-client"; they are not connected.'; + } + + /** + * `Mcp.client.proxy`: the proxy every client HTTP request goes through, or null to connect directly. + * + * @return string|null An `http`, `https` or `socks5h` URL with a host, maybe a user and password and a port, + * and no path. Not `socks5`, with which curl resolves the name in the application instead of the proxy. + * @throws \InvalidArgumentException When it is set to anything else. + */ + public static function proxy(): ?string + { + $proxy = Configure::read('Mcp.client.proxy'); + if ($proxy === null) { + return null; + } + $parts = is_string($proxy) ? parse_url($proxy) : false; + if ( + !is_array($parts) + || !in_array(strtolower((string)($parts['scheme'] ?? '')), ['http', 'https', 'socks5h'], true) + || (string)($parts['host'] ?? '') === '' + || !in_array($parts['path'] ?? '/', ['', '/'], true) + || isset($parts['query']) + || isset($parts['fragment']) + ) { + throw new InvalidArgumentException( + '"Mcp.client.proxy" must be null or a proxy URL such as "http://proxy.example.com:3128" (http, ' + . 'https or socks5h, with no path; socks5h rather than socks5, so the proxy resolves host names).', + ); + } + + return (string)$proxy; + } + + /** + * `Mcp.client.proxy` without its user name and password, for messages. + * + * @return string|null + */ + public static function proxyForDisplay(): ?string + { + $proxy = self::proxy(); + if ($proxy === null) { + return null; + } + $parts = parse_url($proxy); + $port = is_array($parts) && isset($parts['port']) ? ':' . $parts['port'] : ''; + + return is_array($parts) ? ($parts['scheme'] ?? '') . '://' . ($parts['host'] ?? '') . $port : null; + } + + /** + * @return list The configured client names whose entry has a valid shape, in order (see `errors()`). + */ + 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. + */ + 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 + { + [$valid, $errors] = self::scan(); + if (isset($errors[$name])) { + throw new InvalidArgumentException($errors[$name]); + } + $config = $valid[$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 (!in_array($auth, [self::APP, self::USER, self::CLIENT_CREDENTIALS], true)) { + throw new InvalidArgumentException(sprintf( + '"%s" must be "app" or "user", or "client_credentials" for an OAuth token of the application.', + $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'))); + } + } + $cache = self::optionalString($config, 'cache', $key); + if ($cache !== null && $command !== null) { + throw new InvalidArgumentException(sprintf( + '"%s" is only for a client over HTTP: list results are not cached for a stdio server.', + $key('cache'), + )); + } + if ($cache !== null && Cache::getConfig($cache) === null) { + throw new InvalidArgumentException(sprintf( + '"%s" names the cache config "%s", which does not exist.', + $key('cache'), + $cache, + )); + } + $registration = $config['registration'] ?? 'auto'; + if (!in_array($registration, self::REGISTRATIONS, true)) { + throw new InvalidArgumentException(sprintf( + '"%s" must be "auto", "metadata" or "dynamic".', + $key('registration'), + )); + } + $tokenProvider = null; + if (array_key_exists('token', $config) && !is_string($config['token']) && is_callable($config['token'])) { + // Called for each request, for tokens that rotate; `bin/cake mcp check` never calls it. + $tokenProvider = Closure::fromCallable($config['token']); + } elseif (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'), + )); + } + // A secret file read whole ends with a line break; the token is never quoted, a header error would. + $token = trim($token); + if (!self::headerSafe($token)) { + throw new InvalidArgumentException(sprintf( + '"%s" has characters an HTTP header cannot carry.', + $key('token'), + )); + } + $headers['Authorization'] = 'Bearer ' . $token; + } + $hasAuthorization = $tokenProvider !== null; + 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, + )); + } + } + + if ($auth === self::CLIENT_CREDENTIALS) { + if ($url === null) { + throw new InvalidArgumentException(sprintf( + '"Mcp.clients.%s": client_credentials needs a "url".', + $name, + )); + } + if ($hasAuthorization) { + throw new InvalidArgumentException(sprintf( + '"Mcp.clients.%s": client_credentials gets its own token, so it takes no "token" or ' + . 'Authorization header.', + $name, + )); + } + foreach (['authorizationUrl', 'revocationUrl', 'registration'] as $userOnly) { + if (array_key_exists($userOnly, $config)) { + throw new InvalidArgumentException(sprintf('"%s" is only for user mode.', $key($userOnly))); + } + } + foreach (['clientId', 'clientSecret'] as $required) { + if (self::optionalString($config, $required, $key) === null) { + throw new InvalidArgumentException(sprintf( + '"%s" is required with "auth" => "client_credentials".', + $key($required), + )); + } + } + if ( + self::optionalString($config, 'issuer', $key) === null + && self::optionalString($config, 'tokenUrl', $key) === null + ) { + // The secret goes to one authorization server only, the one the config names. + throw new InvalidArgumentException(sprintf( + '"Mcp.clients.%s": client_credentials needs "issuer" (its token endpoint is read from the ' + . 'issuer\'s metadata) or "tokenUrl".', + $name, + )); + } + } + + if ($auth === self::APP) { + $oauthKeys = [ + 'clientId', 'clientSecret', 'scopes', 'authorizationUrl', 'tokenUrl', 'revocationUrl', 'issuer', + 'registration', + ]; + foreach ($oauthKeys as $oauth) { + if (array_key_exists($oauth, $config)) { + throw new InvalidArgumentException(sprintf( + '"%s" is only for user mode; add "auth" => "user" if each user should sign in.', + $key($oauth), + )); + } + } + } + + $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); + if ($clientId === null && self::optionalString($config, 'clientSecret', $key) !== null) { + throw new InvalidArgumentException(sprintf('"%s" needs "clientId".', $key('clientSecret'))); + } + $issuer = self::optionalString($config, 'issuer', $key); + if ($issuer !== null) { + // Its metadata names the token endpoint a secret goes to: the same rule as the configured addresses. + ServerUrlPolicy::check($issuer, $allowInsecure, $key('issuer')); + } + $configured = array_filter($endpoints, fn(?string $value): bool => $value !== null) !== []; + $secret = self::optionalString($config, 'clientSecret', $key); + if ($auth === self::USER && $secret !== null && !$configured && $issuer === null) { + // The MCP server names its authorization server on every sign-in: a secret must be bound to one. + throw new InvalidArgumentException(sprintf( + '"%s" is required with "clientSecret" and discovery: without it, the secret would go to whatever ' + . 'authorization server the MCP server names. Set it to the issuer that gave you the client.', + $key('issuer'), + )); + } + if ( + $auth === self::USER + && $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')), + ); + } + foreach (array_keys($tools) as $toolKey) { + if ($toolKey !== 'only' && $toolKey !== 'except') { + // A misspelled deny list would otherwise allow every tool. + throw new InvalidArgumentException(sprintf( + '"%s" is not a setting; "tools" takes "only" and "except".', + $key('tools.' . $toolKey), + )); + } + } + + $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'], + $issuer, + $tokenProvider, + self::bool($config, 'allowPrivateNetwork', $key), + $registration, + $cache, + ); + } + + /** + * The entries of `Mcp.clients` that cannot be used (their shape or a setting), as entry name => what is wrong. + * The name is `Mcp.clients` when the whole setting is not an array of client name => config. The other + * clients keep working; `bin/cake mcp check` fails on these. + * + * @return array + */ + public static function errors(): array + { + [$valid, $errors] = self::scan(); + $errors += self::settingErrors(); + foreach (array_keys($valid) as $name) { + try { + self::fromConfig($name); + } catch (InvalidArgumentException $e) { + $errors[$name] = $e->getMessage(); + } + } + + return $errors; + } + + /** + * What is wrong with the settings shared by every client, `Mcp.client.*`, as `Mcp.client.` => message. + * `store` and `encryptionKey` as a store are checked by `bin/cake mcp check`, which builds the store. + * + * @return array + */ + private static function settingErrors(): array + { + $settings = Configure::read('Mcp.client') ?? []; + if (!is_array($settings)) { + return ['Mcp.client' => '"Mcp.client" must be an array of the settings shared by every client.']; + } + $errors = []; + foreach (array_diff(array_map('strval', array_keys($settings)), array_keys(self::SETTINGS)) as $key) { + $errors['Mcp.client.' . $key] = sprintf( + '"Mcp.client.%s" is not a setting: the shared client settings are %s.', + $key, + implode(', ', array_keys(self::SETTINGS)), + ); + } + $route = self::routeError(); + if ($route !== null) { + $errors['Mcp.client.route'] = $route; + } + $seconds = 'a number of seconds, 0 or more'; + $rules = [ + 'name' => [fn(mixed $v): bool => is_string($v) && trim($v) !== '', 'a non-empty string'], + 'version' => [fn(mixed $v): bool => is_string($v) && trim($v) !== '', 'a non-empty string'], + 'identityAttribute' => [fn(mixed $v): bool => is_string($v) && $v !== '', 'a request attribute name'], + // A string of digits too: what env() gives, read with an (int) cast. + 'refreshLeeway' => [fn(mixed $v): bool => self::digits($v) && (int)$v >= 0, $seconds], + 'maxResponseBytes' => [fn(mixed $v): bool => self::digits($v) && (int)$v > 0, 'a positive number of bytes'], + 'encryptionKey' => [fn(mixed $v): bool => is_string($v), 'null or a string of at least 32 bytes'], + ]; + foreach ($rules as $key => [$valid, $what]) { + $value = $settings[$key] ?? null; + if ($value !== null && !$valid($value)) { + $errors['Mcp.client.' . $key] = sprintf('"Mcp.client.%s" must be %s.', $key, $what); + } + } + try { + self::proxy(); + } catch (InvalidArgumentException $e) { + $errors['Mcp.client.proxy'] = $e->getMessage(); + } + + return $errors; + } + + /** + * @param mixed $value A setting. + * @return bool Whether it is an int, or a string of digits. + */ + private static function digits(mixed $value): bool + { + return is_int($value) || (is_string($value) && ctype_digit($value)); + } + + /** + * @return array> The entries of `Mcp.clients` whose shape is valid. + */ + private static function all(): array + { + return self::scan()[0]; + } + + /** + * @return array{0: array>, 1: array} The entries of `Mcp.clients` + * with a valid shape, and the others with what is wrong with them. + */ + private static function scan(): array + { + $clients = Configure::read('Mcp.clients') ?? []; + if (!is_array($clients)) { + return [[], ['Mcp.clients' => '"Mcp.clients" must be an array of client name => config.']]; + } + if ($clients !== [] && array_is_list($clients)) { + return [[], ['Mcp.clients' => '"Mcp.clients" must be an array of client name => config, not a list.']]; + } + $valid = []; + $errors = []; + foreach ($clients as $name => $config) { + if (is_int($name)) { + // PHP keeps a numeric key an int: a name like "42". + $errors['Mcp.clients.' . $name] = sprintf( + '"Mcp.clients.%d": a client name must be a word, not a number.', + $name, + ); + continue; + } + if (!is_array($config)) { + $errors[$name] = sprintf( + '"Mcp.clients.%s" must be the config array of the client; "Mcp.clients" is an array of client ' + . 'name => config.', + $name, + ); + } elseif (preg_match('/^[A-Za-z0-9_-]+$/', $name) !== 1) { + $errors[$name] = sprintf( + 'The client name "%s" in "Mcp.clients" may only have letters, digits, "-" and "_".', + $name, + ); + } else { + $valid[$name] = $config; + } + } + + /** @var array> $valid */ + return [$valid, $errors]; + } + + /** + * @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..e7c622c --- /dev/null +++ b/src/Client/ClientRegistry.php @@ -0,0 +1,191 @@ + + */ + private array $clients = []; + + /** + * @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. + * @param \Closure|null $sleep `fn(int $microseconds): void` while another request refreshes a grant; `usleep()` + * by default. + * @param \CakeDC\Mcp\Client\Http\HostResolverInterface|null $resolver Looks host names up; DNS by default. + */ + public function __construct( + private ?HttpClientFactoryInterface $http = null, + private ?ConnectionStoreInterface $store = null, + private ?GuardedHttp $guarded = null, + private ?Closure $sleep = null, + private ?HostResolverInterface $resolver = null, + ) { + } + + /** + * Waits while another request refreshes a grant. + * + * @param int $microseconds How long. + * @return void + */ + public function sleep(int $microseconds): void + { + $this->sleep === null ? usleep($microseconds) : ($this->sleep)($microseconds); + } + + /** + * @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(); + } + + /** + * @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\HostResolverInterface How host names are looked up. + */ + public function resolver(): HostResolverInterface + { + return $this->resolver ??= new DnsHostResolver(); + } + + /** + * @return \CakeDC\Mcp\Client\Http\GuardedHttp + */ + public function guarded(): GuardedHttp + { + $proxy = ClientConfig::proxy(); + + return $this->guarded ??= new GuardedHttp( + new EndpointGuard($this->resolver(), $proxy !== null), + new CakeGuardedTransport(null, $proxy), + (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()->forClient($config), $this->http()->create($config)); + } + + /** + * The application's own token of a client with `'auth' => 'client_credentials'`. + * + * @param \CakeDC\Mcp\Client\ClientConfig $config The client. + * @return \CakeDC\Mcp\Client\OAuth\ClientCredentials + */ + public function clientCredentials(ClientConfig $config): ClientCredentials + { + $outbound = $this->outbound($config); + + return new ClientCredentials($config, $outbound, $this->store(), new TokenClient($outbound, $config->timeout)); + } + + /** + * @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)); + } + // One flow serves one web request (a connect or a callback): all its requests share the client's timeout. + $outbound = $this->outbound($config)->withDeadline(new Deadline((float)$config->timeout)); + + return new OAuthFlow( + $config, + new Discovery($outbound, $config), + new Registrar($outbound, $this->store(), $config, $this->resolver()), + new TokenClient($outbound, $config->timeout), + $this->store(), + ); + } + + /** + * 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..f030722 --- /dev/null +++ b/src/Client/ClientSession.php @@ -0,0 +1,268 @@ + + */ + 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). + * @param \CakeDC\Mcp\Client\ListCache|null $lists The client's list cache, dropped on `list_changed`. + */ + public function __construct( + private ClientConfig $config, + private HttpClientFactoryInterface $factory, + private array $headers = [], + private ?ListCache $lists = null, + ) { + } + + /** + * @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(McpLogger::forUrl($this->config->url)) + ->addRequestHandler(new PingHandler()); + if ($this->lists !== null) { + $builder->addNotificationHandler(new ListChangedHandler($this->lists)); + } + if ($this->config->protocolVersion !== null) { + $builder->setProtocolVersion($this->config->protocolVersion); + } + $client = $builder->build(); + $client->connect($this->transport()); + $this->client = $client; + + return $client; + } + + /** + * Runs $call on the connected client. When the server refused the request before running it, it is sent once + * more: after a header mismatch (-32020), with the tool list fetched again so the SDK knows the headers of + * each tool, as the specification advises; after an expired session (HTTP 404 in the handshake revisions), + * on a new session. Nothing else is retried, so a call that may have run never runs twice. + * + * @template T + * @param callable(\Mcp\Client): T $call The call. + * @return T + */ + public function call(callable $call): mixed + { + try { + return $this->attempt($call); + } catch (ExceptionInterface $e) { + // The SDK reports a redirect as an empty answer: say what it was. + $redirect = $this->http?->lastRedirect(); + if ($redirect === null) { + throw $e; + } + $parts = (array)parse_url($redirect[1]); + $target = ($parts['scheme'] ?? 'https') . '://' . ($parts['host'] ?? '') + . (isset($parts['port']) ? ':' . $parts['port'] : '') . ($parts['path'] ?? '/'); + throw new ClientException(sprintf( + 'The server of "%s" answered with a redirect (%d) to %s. The MCP client does not follow redirects, ' + . 'since the token would go wherever they point: set "Mcp.clients.%s.url" to the final address.', + $this->config->name, + $redirect[0], + $target, + $this->config->name, + ), 0, $e); + } + } + + /** + * @template T + * @param callable(\Mcp\Client): T $call The call. + * @return T + */ + private function attempt(callable $call): mixed + { + $this->http?->startCall(); + $client = $this->client(); + try { + return $call($client); + } catch (RequestException $e) { + if ($e->getCode() !== Error::HEADER_MISMATCH) { + throw $e; + } + // Every page: the tool the call is for may be on any of them. + $cursor = null; + $pages = 0; + do { + $cursor = $client->listTools($cursor)->nextCursor; + } while ($cursor !== null && ++$pages < self::MAX_TOOL_PAGES); + + return $call($client); + } catch (ConnectionException $e) { + if ($e->getCode() !== 404) { + throw $e; + } + $this->close(); + + return $call($this->client()); + } + } + + /** + * @param string $method A list method. + * @return array|null The raw `result` of the last answer to it, with its cache hints. + */ + public function lastResult(string $method): ?array + { + return $this->http?->lastResult($method); + } + + /** + * @return string|null The challenge of the server's last 403 since the previous call, which this forgets. + */ + public function takeForbidden(): ?string + { + return $this->http?->takeForbidden(); + } + + /** + * @return string|null The `WWW-Authenticate` header of the server's last answer, null when it had none. + */ + public function lastChallenge(): ?string + { + return $this->http?->lastChallenge(); + } + + /** + * @return bool Whether the last call failed with a 401 before the server accepted any of its requests: only + * then can it be sent again with a new token without running twice. + */ + public function unauthorizedBeforeAccepted(): bool + { + return $this->http?->unauthorizedBeforeAccepted() ?? false; + } + + /** + * @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; + } + + /** + * The SDK quotes the arguments but not the command (escapeshellcmd() leaves spaces alone), so a program whose + * path has a space ("/Users/me/My Tools/server") would not start. Such a path is passed to /usr/bin/env as an + * argument instead, quoted like the others. A command with arguments written into it ("npx -y x") is not a + * file and is left as it is; so is everything on Windows. + * + * @param string $command The configured command. + * @param list $args Its arguments. + * @param string|null $cwd The directory it runs in. + * @return array{0: string, 1: list} + */ + private static function spawnable(string $command, array $args, ?string $cwd): array + { + $file = $command; + if (!str_starts_with($command, '/') && $cwd !== null) { + $file = rtrim($cwd, '/') . '/' . $command; + } + $spaced = preg_match('/\s/', $command) === 1 && is_file($file); + // env reads a leading "-" as an option and a "NAME=value" word as a variable. + $env = DIRECTORY_SEPARATOR === '/' && is_executable('/usr/bin/env'); + if (!$spaced || !$env || str_starts_with($command, '-') || str_contains($command, '=')) { + return [$command, $args]; + } + + // A bare name is the file found in cwd (env would look for it in PATH); a path is run from cwd as written. + return ['/usr/bin/env', [str_contains($command, '/') ? $command : './' . $command, ...$args]]; + } + + /** + * @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; + } + } + + [$command, $args] = self::spawnable($this->config->command, $this->config->args, $this->config->cwd); + + return new StdioTransport($command, $args, $this->config->cwd, $this->config->env + $env, new McpLogger()); + } + + $this->http = new WatchedHttpClient($this->factory->create($this->config), $this->config, $this->lists); + + return new HttpTransport( + (string)$this->config->url, + $this->headers + $this->config->headers, + $this->http, + new RequestFactory(), + new StreamFactory(), + McpLogger::forUrl($this->config->url), + ); + } +} 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 @@ +url); + $host = is_array($parts) ? strtolower(trim((string)($parts['host'] ?? ''), '[]')) : ''; + // Compared as written: "host." would not match the pin in curl and be resolved again. + // Plain http only when the guard let it through (a client with allowPrivateNetwork and allowInsecure). + $expected = str_starts_with($pin->origin, 'http://') ? 'http' : 'https'; + $scheme = is_array($parts) ? strtolower((string)($parts['scheme'] ?? '')) : ''; + $port = is_array($parts) ? (int)($parts['port'] ?? ($scheme === 'http' ? 80 : 443)) : 0; + if ($scheme !== $expected || $host !== $pin->host || $port !== $pin->port) { + throw new BlockedUrlException('The request left the address that was checked.'); + } + + $tooLarge = false; + $compressed = false; + $ip = str_contains($pin->ip, ':') ? '[' . $pin->ip . ']' : $pin->ip; + // Without `Mcp.client.proxy`: pinned to the address that was checked, and no proxy from the environment. + // With it: through it, unpinned, since the proxy resolves the name, and never direct (an empty NOPROXY + // overrides NO_PROXY in the environment, which would send the request unpinned). Its credentials stay in + // its URL, so curl sends them to the proxy only. + $route = $this->proxy === null + ? [ + CURLOPT_RESOLVE => [sprintf('%s:%d:%s', $pin->host, $pin->port, $ip)], + CURLOPT_PROXY => '', + CURLOPT_NOPROXY => '*', + ] + : [CURLOPT_PROXY => $this->proxy, CURLOPT_NOPROXY => '']; + $curl = $route + [ + 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; + }, + // A compressed body is inflated whole after it is read, past the cap: stop the transfer at its headers. + CURLOPT_HEADERFUNCTION => function ($handle, string $header) use (&$compressed): int { + if (self::isCompressed($header)) { + $compressed = true; + + return 0; + } + + return strlen($header); + }, + ]; + if (defined('CURLOPT_PROTOCOLS_STR')) { + $curl[CURLOPT_PROTOCOLS_STR] = $expected; + } else { + $curl[CURLOPT_PROTOCOLS] = $expected === 'http' ? CURLPROTO_HTTP : CURLPROTO_HTTPS; + } + $headers = array_filter( + $request->headers, + fn(string $name): bool => strcasecmp($name, 'host') !== 0, + ARRAY_FILTER_USE_KEY, + ); + $headers = array_filter( + $headers, + fn(string $name): bool => strcasecmp($name, 'accept-encoding') !== 0, + ARRAY_FILTER_USE_KEY, + ) + ['Accept-Encoding' => 'identity']; + + try { + $client = new Client(['adapter' => $this->adapter ?? Curl::class]); + $response = $client->send( + new Request($request->url, $request->method, $headers, $request->body), + [ + // Whole seconds for curl, which reads 0 as no limit: a fraction left of a step is rounded up. + 'timeout' => max(1, (int)ceil($request->timeout)), + 'ssl_verify_peer' => true, + 'ssl_verify_host' => true, + 'curl' => $curl, + ], + ); + } catch (Throwable $e) { + // Anything the HTTP layer throws (a gzip body that is not one, say) is this transport's error. The + // message is left out: it quotes the URL, whose query may carry a secret. + if ($compressed) { + throw self::compressed($pin->host); + } + 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)); + } + if (self::isCompressed('Content-Encoding: ' . $response->getHeaderLine('Content-Encoding'))) { + throw self::compressed($pin->host); + } + $body = (string)$response->getBody(); + if (strlen($body) > $maxBytes) { + throw self::tooLarge(); + } + + return new HttpResponse($response->getStatusCode(), $response->getHeaders(), $body); + } + + /** + * @param string $header One header line. + * @return bool Whether it announces a compressed body (a `Content-Encoding` other than `identity`). + */ + private static function isCompressed(string $header): bool + { + // Read the line as Cake does: the name is what comes before the first colon, trimmed, so + // "Content-Encoding : gzip" is Content-Encoding to it as well. + $parts = explode(':', $header, 2); + if (count($parts) !== 2 || strtolower(trim($parts[0])) !== 'content-encoding') { + return false; + } + $encoding = strtolower(trim($parts[1])); + + return $encoding !== '' && $encoding !== 'identity'; + } + + /** + * @param string $host The server. + * @return \CakeDC\Mcp\Client\Exception\ClientException + */ + private static function compressed(string $host): ClientException + { + return new ClientException(sprintf( + 'The server at %s sent a compressed answer, which the MCP client does not accept.', + $host, + )); + } + + /** + * @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 @@ +clock = $clock ?? fn(): float => microtime(true); + $this->at = ($this->clock)() + $seconds; + } + + /** + * @param float $timeout The request's own timeout. + * @param string $url The URL about to be requested. + * @return float Seconds for that request: its timeout, or what is left when that is less. + * @throws \CakeDC\Mcp\Client\Exception\ClientException When no time is left. + */ + public function timeout(float $timeout, string $url): float + { + $left = $this->at - ($this->clock)(); + if ($left <= 0) { + throw new ClientException(sprintf( + 'The server at %s took too long: the requests of this step may take %s %s in all.', + (string)parse_url($url, PHP_URL_HOST), + (string)round($this->seconds, 3), + round($this->seconds, 3) === 1.0 ? 'second' : 'seconds', + )); + } + + return min($timeout, $left); + } +} diff --git a/src/Client/Http/DnsHostResolver.php b/src/Client/Http/DnsHostResolver.php new file mode 100644 index 0000000..eccc20e --- /dev/null +++ b/src/Client/Http/DnsHostResolver.php @@ -0,0 +1,67 @@ + + */ + private Closure $dns; + + /** + * @var \Closure(string): list + */ + private Closure $system; + + /** + * @param (\Closure(string): list)|null $dns The DNS lookup; `dns_get_record()` by default. + * @param (\Closure(string): list)|null $system The system lookup; `gethostbynamel()` by default. + */ + public function __construct(?Closure $dns = null, ?Closure $system = null) + { + $this->dns = $dns ?? self::dnsRecords(...); + $this->system = $system ?? fn(string $host): array => gethostbynamel($host) ?: []; + } + + /** + * @inheritDoc + */ + public function resolve(string $host): array + { + if (filter_var($host, FILTER_VALIDATE_IP) !== false) { + return [$host]; + } + $addresses = ($this->dns)($host); + if ($addresses === []) { + $addresses = ($this->system)($host); + } + + return array_values(array_unique($addresses)); + } + + /** + * @param string $host A host name. + * @return list Its A and AAAA records. + */ + private static function dnsRecords(string $host): array + { + $addresses = []; + // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- a failed lookup is just no address + foreach (@dns_get_record($host, DNS_A | DNS_AAAA) ?: [] as $record) { + $address = $record['ip'] ?? $record['ipv6'] ?? null; + if (is_string($address)) { + $addresses[] = $address; + } + } + + return $addresses; + } +} diff --git a/src/Client/Http/EndpointGuard.php b/src/Client/Http/EndpointGuard.php new file mode 100644 index 0000000..20107a4 --- /dev/null +++ b/src/Client/Http/EndpointGuard.php @@ -0,0 +1,192 @@ + + */ + private const LOCAL_SUFFIXES = ['localhost', 'local', 'localdomain', 'internal', 'home.arpa', 'arpa']; + + /** + * @param \CakeDC\Mcp\Client\Http\HostResolverInterface $resolver Resolves host names. + * @param bool $proxied Whether requests go through `Mcp.client.proxy`, which resolves the name itself: a name + * the application cannot resolve is then allowed, and the checked endpoint has no address to pin. + */ + public function __construct( + private HostResolverInterface $resolver, + private bool $proxied = false, + private bool $privateNetwork = false, + private bool $plainHttp = false, + ) { + } + + /** + * This guard for a client with `allowPrivateNetwork`: names under the local special-use names and names that + * resolve to private, loopback or link-local addresses pass; IP addresses and single labels stay refused. + * + * @param bool $plainHttp Whether plain http passes too (the client's `allowInsecure`). + * @return self + */ + public function allowingPrivateNetwork(bool $plainHttp): self + { + return new self($this->resolver, $this->proxied, true, $plainHttp); + } + + /** + * Checks the origin of $url; the path and query are the caller's. + * + * @param string $url An absolute URL. + * @return \CakeDC\Mcp\Client\Http\CheckedEndpoint + * @throws \CakeDC\Mcp\Client\Http\BlockedUrlException + */ + public function check(string $url): CheckedEndpoint + { + $parts = parse_url($url); + $host = is_array($parts) ? strtolower(trim((string)($parts['host'] ?? ''), '[]')) : ''; + $scheme = is_array($parts) ? strtolower((string)($parts['scheme'] ?? '')) : ''; + if ( + !is_array($parts) + || !($scheme === 'https' || ($scheme === 'http' && $this->plainHttp)) + || $host === '' + || isset($parts['user']) + || isset($parts['pass']) + || isset($parts['fragment']) + || (isset($parts['port']) && $parts['port'] < 1) + || str_contains($url, '#') + || preg_match('/\s/', $url) === 1 + ) { + throw new BlockedUrlException( + 'A remote server named an address the MCP client does not call: only https, without a user name, ' + . 'password or fragment.', + ); + } + $notPublic = sprintf('%s is not a public address the MCP client may call.', $host); + if (filter_var($host, FILTER_VALIDATE_IP) !== false || self::looksNumeric($host)) { + // curl reads 2130706433, 127.1 or 0x7f000001 as an IP address; learned URLs are reached by name only. + throw new BlockedUrlException($notPublic); + } + // A trailing dot is refused by isHostName(): curl would not match the pin to "host." and resolve again. + // `localhost` is a single label that never goes through DNS search domains: allowed with the private network. + $singleLabel = !str_contains($host, '.') && !($host === 'localhost' && $this->privateNetwork); + if ( + !self::isHostName($host) + || $singleLabel + || (self::isLocalName($host) && !$this->privateNetwork) + ) { + // A single label could go through the server's DNS search domains. + throw new BlockedUrlException($notPublic); + } + $addresses = $this->resolver->resolve($host); + if ($addresses === [] && !$this->proxied) { + throw new BlockedUrlException($notPublic); + } + foreach ($addresses as $address) { + if (!$this->privateNetwork && !self::isPublic($address)) { + throw new BlockedUrlException($notPublic); + } + } + $default = $scheme === 'http' ? 80 : 443; + $port = (int)($parts['port'] ?? $default); + + return new CheckedEndpoint( + $scheme . '://' . $host . ($port === $default ? '' : ':' . $port), + $host, + $port, + // Behind a proxy nothing is pinned: the proxy resolves the name. + $this->proxied ? '' : $addresses[0], + ); + } + + /** + * @param string $host A host name. + * @return bool Whether it is, or is under, a special-use name of this machine or the local network. + */ + private static function isLocalName(string $host): bool + { + foreach (self::LOCAL_SUFFIXES as $suffix) { + if ($host === $suffix || str_ends_with($host, '.' . $suffix)) { + return true; + } + } + + return false; + } + + /** + * @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}(?allowPrivateNetwork) { + return $this; + } + + return new self( + $this->guard->allowingPrivateNetwork($config->allowInsecure), + $this->transport, + $this->maxBytes, + ); + } + + /** + * An unauthenticated GET for metadata, following at most MAX_REDIRECTS redirects. + * + * @param string $url The exact URL. + * @param float $timeout Seconds for each request. + * @param \CakeDC\Mcp\Client\Http\Deadline|null $deadline A limit the redirects share, if any. + * @return \CakeDC\Mcp\Client\Http\HttpResponse The last answer, any status but a redirect with a Location. + * @throws \CakeDC\Mcp\Client\Http\BlockedUrlException + * @throws \CakeDC\Mcp\Client\Exception\ClientException + */ + public function get(string $url, float $timeout, ?Deadline $deadline = null): HttpResponse + { + for ($hop = 0;; $hop++) { + $seconds = $deadline?->timeout($timeout, $url) ?? $timeout; + $response = $this->transport->send( + new HttpRequest('GET', $url, ['Accept' => 'application/json'], null, $seconds), + $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); + } + } + + /** + * 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. + * + * @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..485566b --- /dev/null +++ b/src/Client/Http/OutboundHttp.php @@ -0,0 +1,135 @@ +guarded, $this->trusted, $deadline); + } + + /** + * An unauthenticated GET for metadata. + * + * @param string $url The exact URL. + * @param bool $trusted Whether the URL comes from the config. + * @param float $timeout Seconds for each request. + * @return \CakeDC\Mcp\Client\Http\HttpResponse + * @throws \CakeDC\Mcp\Client\Exception\ClientException + */ + public function get(string $url, bool $trusted, float $timeout): HttpResponse + { + if (!$trusted) { + return $this->guarded->get($url, $timeout, $this->deadline); + } + $response = $this->trusted(new HttpRequest( + 'GET', + $url, + ['Accept' => 'application/json'], + null, + $this->deadline?->timeout($timeout, $url) ?? $timeout, + )); + $location = $response->header('Location'); + if ($response->isRedirect() && $location !== null && trim($location) !== '') { + return $this->guarded->get(GuardedHttp::resolve($url, $location), $timeout, $this->deadline); + } + + 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. + * + * @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 ($this->deadline !== null) { + $request = new HttpRequest( + $request->method, + $request->url, + $request->headers, + $request->body, + $this->deadline->timeout($request->timeout, $request->url), + ); + } + 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 { + $psr = new Request($request->url, $request->method, $request->headers, $request->body); + // Cake's client takes a timeout for one request; another PSR-18 client keeps its own. + $client = $this->trusted; + $response = $this->deadline !== null && $client instanceof Client + ? $client->send($psr, ['timeout' => max(1, (int)ceil($request->timeout))] + $client->getConfig()) + : $client->sendRequest($psr); + } catch (Throwable) { + // Anything the HTTP layer throws (a PSR-18 error, a gzip body that is not one) is this client's error. + // 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/src/Client/HttpClientFactoryInterface.php b/src/Client/HttpClientFactoryInterface.php new file mode 100644 index 0000000..9c5f07c --- /dev/null +++ b/src/Client/HttpClientFactoryInterface.php @@ -0,0 +1,20 @@ +timeout`. + */ + public function create(ClientConfig $config): ClientInterface; +} diff --git a/src/Client/ListCache.php b/src/Client/ListCache.php new file mode 100644 index 0000000..3a11332 --- /dev/null +++ b/src/Client/ListCache.php @@ -0,0 +1,185 @@ +.cache`: results (`tools/list`, `resources/list`, `resources/templates/list`, + * `prompts/list`, `resources/read` and `server/discover`) that carry the cache hints of the 2026-07-28 revision + * (`ttlMs`, `cacheScope`) are kept in that Cake cache config for their ttl. A `private` result is keyed by user in user mode and by client in app mode, and + * always by the credential it was asked with (the user's access token, the configured token or headers, what a + * `token` callable returns): it is never served for another token, nor after a reconnection with another account. + * A `public` one is keyed by client. No hints, no caching. A `notifications/*\/list_changed` drops the entries of + * its lists, and a `notifications/resources/updated` the reads of its URI. + */ +final class ListCache +{ + /** + * @var list + */ + public const METHODS = [ + 'tools/list', + 'resources/list', + 'resources/templates/list', + 'prompts/list', + 'resources/read', + 'server/discover', + ]; + + /** + * The largest result kept, in bytes of JSON: a resource can be a large blob. + */ + public const MAX_ENTRY_BYTES = 512 * 1024; + + /** + * @param \CakeDC\Mcp\Client\ClientConfig $config The client, with `cache` set. + * @param string|null $userId The user in user mode; null in app mode. + * @param string $credential What the requests are authorized with; only its hash is kept, in the key. + */ + public function __construct(private ClientConfig $config, private ?string $userId, private string $credential = '') + { + } + + /** + * @param \CakeDC\Mcp\Client\ClientConfig $config The client. + * @param string|null $userId The user in user mode; null in app mode. + * @param string $credential What the requests are authorized with. + * @return self|null Null when the client has no `cache`. + */ + public static function for(ClientConfig $config, ?string $userId, string $credential = ''): ?self + { + return $config->cache === null ? null : new self($config, $userId, $credential); + } + + /** + * @param string $credential What the requests are authorized with. + * @return self This cache for that credential. + */ + public function withCredential(string $credential): self + { + return new self($this->config, $this->userId, $credential); + } + + /** + * @param string $method A method of METHODS. + * @param string|null $cursor The page cursor of a list, the URI of `resources/read`, null for `server/discover`. + * @return object|array|null What was kept (the SDK's result, or the raw result of + * `server/discover`), when one is fresh for this caller. + */ + public function get(string $method, ?string $cursor): object|array|null + { + foreach ([CacheScope::Private, CacheScope::Public] as $scope) { + $entry = Cache::read($this->key($method, $cursor, $scope), (string)$this->config->cache); + if ( + is_array($entry) + && is_int($entry['expires'] ?? null) + && $entry['expires'] > self::nowMs() + && (is_object($entry['page'] ?? null) || is_array($entry['page'] ?? null)) + ) { + return $entry['page']; + } + } + + return null; + } + + /** + * Keeps $page for the `ttlMs` of $result, under its `cacheScope`; does nothing without both hints. + * + * @param string $method A method of METHODS. + * @param string|null $cursor The page cursor, or the URI of `resources/read`. + * @param array $result The raw `result` of the server's answer, for its hints. + * @param object|array $page What to keep: the SDK's result made from it, or the raw result. + * @return void + */ + public function put(string $method, ?string $cursor, array $result, object|array $page): void + { + $ttl = $result['ttlMs'] ?? null; + $scope = is_string($result['cacheScope'] ?? null) ? CacheScope::tryFrom($result['cacheScope']) : null; + if (!in_array($method, self::METHODS, true) || !is_int($ttl) || $ttl <= 0 || $scope === null) { + return; + } + if (strlen((string)json_encode($result)) > self::MAX_ENTRY_BYTES) { + return; + } + // The SDK learns the Mcp-Param headers of a tool from the listing it fetched itself: a tool list whose + // tools have x-mcp-header annotations is always fetched. + if ($method === 'tools/list' && str_contains((string)json_encode($result['tools'] ?? []), 'x-mcp-header')) { + return; + } + Cache::write( + $this->key($method, $cursor, $scope), + ['expires' => self::nowMs() + $ttl, 'page' => $page], + (string)$this->config->cache, + ); + } + + /** + * Drops every entry of $method for this client, all users and pages included, or only those of $part (the URI + * of a `resources/read`). + * + * @param string $method A method of METHODS. + * @param string|null $part Only the entries for this cursor or URI; null for all. + * @return void + */ + public function forget(string $method, ?string $part = null): void + { + $key = $this->generationKey($part === null ? $method : $method . "\0" . $part); + Cache::write($key, bin2hex(random_bytes(8)), (string)$this->config->cache); + } + + /** + * @param string $method A list method. + * @param string|null $cursor The page cursor. + * @param \Mcp\Schema\Enum\CacheScope $scope The scope. + * @return string + */ + private function key(string $method, ?string $cursor, CacheScope $scope): string + { + $owner = match (true) { + $scope === CacheScope::Public => 'public', + $this->userId !== null => 'user:' . TableConnectionStore::connectionKey($this->config->name, $this->userId), + default => 'app', + }; + if ($scope === CacheScope::Private) { + $owner .= ':' . hash('sha256', $this->credential); + } + $generation = Cache::read($this->generationKey($method), (string)$this->config->cache); + $own = $cursor === null + ? null + : Cache::read($this->generationKey($method . "\0" . $cursor), (string)$this->config->cache); + + return 'mcp_client_list_' . hash('sha256', (string)json_encode([ + $this->config->name, + // A client that now points to another server never gets what the previous one answered. + $this->config->url, + $method, + $cursor, + $owner, + is_string($generation) ? $generation : '', + is_string($own) ? $own : '', + ])); + } + + /** + * @param string $method A method of METHODS, maybe with a cursor or URI after a NUL. + * @return string + */ + private function generationKey(string $method): string + { + return 'mcp_client_list_gen_' . hash('sha256', $this->config->name . "\0" . $method); + } + + /** + * @return int Milliseconds since the epoch, on Cake's (testable) clock. + */ + private static function nowMs(): int + { + return (int)DateTime::now()->format('Uv'); + } +} diff --git a/src/Client/ListChangedHandler.php b/src/Client/ListChangedHandler.php new file mode 100644 index 0000000..c7225df --- /dev/null +++ b/src/Client/ListChangedHandler.php @@ -0,0 +1,57 @@ +> + */ + private const LISTS = [ + 'notifications/tools/list_changed' => ['tools/list'], + // A resource the list no longer has is not read from the cache either. + 'notifications/resources/list_changed' => ['resources/list', 'resources/templates/list', 'resources/read'], + 'notifications/prompts/list_changed' => ['prompts/list'], + ]; + + /** + * @param \CakeDC\Mcp\Client\ListCache $cache The client's list cache. + */ + public function __construct(private ListCache $cache) + { + } + + /** + * @inheritDoc + */ + public function supports(Notification $notification): bool + { + return isset(self::LISTS[$notification::getMethod()]) || $notification instanceof ResourceUpdatedNotification; + } + + /** + * @inheritDoc + */ + public function handle(Notification $notification): void + { + if ($notification instanceof ResourceUpdatedNotification) { + // The reads of that resource only. + $this->cache->forget('resources/read', $notification->uri); + + return; + } + foreach (self::LISTS[$notification::getMethod()] ?? [] as $method) { + $this->cache->forget($method); + } + } +} diff --git a/src/Client/McpClient.php b/src/Client/McpClient.php new file mode 100644 index 0000000..3a1d67c --- /dev/null +++ b/src/Client/McpClient.php @@ -0,0 +1,197 @@ +callTool('search_issues', ['query' => 'bug']); + * McpClients::get('linear')->for($this->Authentication->getIdentity())->listTools(); + * ``` + */ +final class McpClient +{ + use CallsServerTrait; + + private ?ClientSession $session = null; + + /** + * The token the session of a `client_credentials` client sends. + */ + private ?string $sessionToken = null; + + /** + * @var array + */ + private array $users = []; + + /** + * @param \CakeDC\Mcp\Client\ClientConfig $config The client. + * @param \CakeDC\Mcp\Client\ClientRegistry $registry Where its HTTP client, store and OAuth pieces come from. + */ + public function __construct(private ClientConfig $config, private ClientRegistry $registry) + { + } + + /** + * @return string The client's name in `Mcp.clients`. + */ + public function name(): string + { + return $this->config->name; + } + + /** + * @inheritDoc + */ + public function config(): ClientConfig + { + return $this->config; + } + + /** + * The connection of one user, for a user mode client. + * + * @param mixed $user A user id, an identity, or a user entity or array with an `id`. + * @return \CakeDC\Mcp\Client\UserConnection The same instance for the same user. + * @throws \LogicException When the client is in app mode. + * @throws \InvalidArgumentException When no user id can be read from $user. + */ + public function for(mixed $user): UserConnection + { + if (!$this->config->isUser()) { + throw new LogicException(sprintf( + '"Mcp.clients.%s" is an app mode client: call it directly with McpClients::get(\'%s\'), or set ' + . '"auth" => "user" to call it on behalf of each user.', + $this->config->name, + $this->config->name, + )); + } + $userId = UserId::of($user); + + return $this->users[$userId] ??= new UserConnection($this->config, $this->registry, $userId); + } + + /** + * Ends the connection to the server, and every user's; the next call opens a new one. + * + * @return void + */ + public function close(): void + { + $this->session?->close(); + $this->session = null; + foreach ($this->users as $user) { + $user->close(); + } + $this->users = []; + } + + /** + * @inheritDoc + */ + protected function listCache(): ?ListCache + { + if ($this->config->isUser() || $this->config->cache === null) { + return null; + } + // Keyed by the credential the requests carry: a `token` callable may return another user's token. + $credential = $this->config->isClientCredentials() + ? $this->registry->clientCredentials($this->config)->token() + : (string)json_encode([$this->config->headers, $this->config->callableToken()]); + + return ListCache::for($this->config, null, $credential); + } + + /** + * @inheritDoc + */ + protected function lastResult(string $method): ?array + { + return $this->session?->lastResult($method); + } + + /** + * @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, + )); + } + if ($this->config->isClientCredentials()) { + return $this->runWithOwnToken($call); + } + $this->session ??= new ClientSession( + $this->config, + $this->registry->http(), + [], + ListCache::for($this->config, null), + ); + + try { + return $this->session->call($call); + } catch (ConnectionException $e) { + // A `token` callable that failed: its own message, not the transport's. + $previous = $e->getPrevious(); + throw $previous instanceof ClientException ? $previous : $e; + } + } + + /** + * A call of a `client_credentials` client, with the application's own token; when the server refuses it + * (401), once more with a new one. + * + * @template T + * @param callable(\Mcp\Client): T $call The call. + * @return T + */ + private function runWithOwnToken(callable $call): mixed + { + $tokens = $this->registry->clientCredentials($this->config); + $session = $this->sessionFor($tokens->token()); + try { + return $session->call($call); + } catch (ExceptionInterface $e) { + // Only a call the server refused before running any of it: never one whose stream a 401 cut short. + if (!$session->unauthorizedBeforeAccepted()) { + throw $e; + } + } + + return $this->sessionFor($tokens->token(true))->call($call); + } + + /** + * @param string $token The access token. + * @return \CakeDC\Mcp\Client\ClientSession A session that sends it. + */ + private function sessionFor(string $token): ClientSession + { + if ($this->session === null || $this->sessionToken !== $token) { + $this->session?->close(); + $this->session = new ClientSession( + $this->config, + $this->registry->http(), + ['Authorization' => 'Bearer ' . $token], + ListCache::for($this->config, null), + ); + $this->sessionToken = $token; + } + + return $this->session; + } +} diff --git a/src/Client/McpClients.php b/src/Client/McpClients.php new file mode 100644 index 0000000..e6cfacf --- /dev/null +++ b/src/Client/McpClients.php @@ -0,0 +1,82 @@ +callTool('search_issues', ['query' => 'bug']); + * McpClients::get('linear')->for($user)->listTools(); + * ``` + */ +final class McpClients +{ + private static ?ClientRegistry $registry = null; + + private static bool $shutdown = false; + + /** + * @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 + { + if (!self::$shutdown) { + // The sessions end with the process: a server of the handshake revisions gets its DELETE. + register_shutdown_function([self::class, 'closeAtShutdown']); + self::$shutdown = true; + } + + return self::$registry ??= new ClientRegistry(); + } + + /** + * Closes every session; registered as a shutdown function by the first `registry()` call. A server that + * cannot be reached then is left alone. + * + * @return void + */ + public static function closeAtShutdown(): void + { + try { + self::$registry?->close(); + } catch (Throwable) { + // The process is ending: nothing is left to tell. + } + } + + /** + * 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/OAuth/AuthServer.php b/src/Client/OAuth/AuthServer.php new file mode 100644 index 0000000..e1fa37c --- /dev/null +++ b/src/Client/OAuth/AuthServer.php @@ -0,0 +1,39 @@ + $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). + * @param bool $metadataDocuments Whether it accepts a Client ID Metadata Document URL as `client_id` + * (`client_id_metadata_document_supported`). + */ + 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, + public readonly bool $metadataDocuments = false, + ) { + } +} diff --git a/src/Client/OAuth/ClientCredentials.php b/src/Client/OAuth/ClientCredentials.php new file mode 100644 index 0000000..24e489c --- /dev/null +++ b/src/Client/OAuth/ClientCredentials.php @@ -0,0 +1,153 @@ + 'client_credentials'`: asked for with its client id and secret at + * the token endpoint of the configured `issuer` (read from its metadata, RFC 8414) or at the configured + * `tokenUrl`, so the secret never goes to an authorization server the MCP server names. Kept in the connection + * store (encrypted, like user grants) until it expires within `Mcp.client.refreshLeeway` seconds. + */ +final class ClientCredentials +{ + /** + * The start of the user id the application's own token is stored under, followed by `:` and a fingerprint of + * what the token was asked for with (see storeUser()). Plain text, for every database; it cannot meet a real + * user, since a client_credentials client has no users (for() refuses it) and rows are keyed by client. + */ + public const STORE_USER = 'client_credentials'; + + /** + * @param \CakeDC\Mcp\Client\ClientConfig $config The client. + * @param \CakeDC\Mcp\Client\Http\OutboundHttp $http Its HTTP layers. + * @param \CakeDC\Mcp\Client\Store\ConnectionStoreInterface $store Where the token is kept. + * @param \CakeDC\Mcp\Client\OAuth\TokenClient $tokens The token endpoint client. + */ + public function __construct( + private ClientConfig $config, + private OutboundHttp $http, + private ConnectionStoreInterface $store, + private TokenClient $tokens, + ) { + } + + /** + * @param bool $renew Ask for a new token even when the stored one has not expired (the server refused it). + * @return string The access token to send. + * @throws \CakeDC\Mcp\Client\OAuth\OAuthException + */ + public function token(bool $renew = false): string + { + $now = DateTime::now()->getTimestamp(); + $user = $this->storeUser(); + $stored = $this->store->get($this->config->name, $user); + if ( + !$renew + && $stored !== null + && $stored->resource === $this->config->url + && !$stored->expiresWithin((int)ClientConfig::setting('refreshLeeway'), $now) + ) { + return $stored->accessToken; + } + [$issuer, $tokenUrl, $trusted, $methods] = $this->endpoint(); + $set = $this->tokens->clientCredentials( + $tokenUrl, + $trusted, + (string)$this->config->clientId, + (string)$this->config->clientSecret, + Registrar::automaticMethod(true, $methods), + (string)$this->config->url, + $this->config->scopes, + ); + $this->store->save(new StoredConnection( + $this->config->name, + $user, + $set->accessToken, + null, + $set->expiresIn === null ? null : $now + $set->expiresIn, + $set->scope, + $issuer, + $tokenUrl, + null, + (string)$this->config->clientId, + null, + 'none', + (string)$this->config->url, + )); + + return $set->accessToken; + } + + /** + * The user id of the token for the client as configured now: a token asked for at another issuer or token + * URL, by another client id or for other scopes is never found, so it is not sent, and a new one is asked for. + * + * @return string + */ + private function storeUser(): string + { + $scopes = $this->config->scopes; + sort($scopes); + $fingerprint = hash('sha256', (string)json_encode([ + $this->config->issuer, + $this->config->tokenUrl, + $this->config->clientId, + $scopes, + ])); + + return self::STORE_USER . ':' . substr($fingerprint, 0, 32); + } + + /** + * @return array{0: string, 1: string, 2: bool, 3: list} The issuer, the token endpoint, whether it is + * from the config, and the client authentication methods it lists. + * @throws \CakeDC\Mcp\Client\OAuth\OAuthException When the issuer's metadata is not usable. + */ + private function endpoint(): array + { + $config = $this->config; + if ($config->tokenUrl !== null) { + return [$config->issuer ?? (string)$config->tokenUrl, $config->tokenUrl, true, []]; + } + $issuer = (string)$config->issuer; + $document = null; + foreach (Discovery::metadataUrls($issuer) as $url) { + // The issuer is configured: its metadata is read like the configured url. + $response = $this->http->get($url, true, (float)$config->timeout); + $document = $response->status === 200 ? $response->json() : null; + if ($document !== null) { + break; + } + } + if ($document === null) { + throw new OAuthException(sprintf( + 'The authorization server of "%s" does not publish its details.', + $config->name, + )); + } + // Simple string comparison, as RFC 8414 3.3 says. + if (($document['issuer'] ?? null) !== $issuer) { + throw new OAuthException(sprintf( + 'The metadata of "Mcp.clients.%s.issuer" names another issuer: the secret is not sent.', + $config->name, + )); + } + $tokenUrl = $document['token_endpoint'] ?? null; + if (!is_string($tokenUrl) || !str_starts_with($tokenUrl, 'https://')) { + throw new OAuthException(sprintf( + 'The authorization server of "%s" names no usable token endpoint.', + $config->name, + )); + } + $methods = $document['token_endpoint_auth_methods_supported'] ?? []; + + return [$issuer, $tokenUrl, false, is_array($methods) ? array_values(array_filter($methods, 'is_string')) : []]; + } +} diff --git a/src/Client/OAuth/ClientMetadataDocument.php b/src/Client/OAuth/ClientMetadataDocument.php new file mode 100644 index 0000000..160f676 --- /dev/null +++ b/src/Client/OAuth/ClientMetadataDocument.php @@ -0,0 +1,137 @@ +//client.json`, whose absolute + * URL is the `client_id` the client sends to an authorization server that supports such documents. It holds no + * secret: the client authenticates with `none` and PKCE. + */ +final class ClientMetadataDocument +{ + /** + * The local and reserved names (RFC 6761 and RFC 6762) that make a base URL unreachable from an authorization + * server on the internet. + * + * @var list + */ + private const LOCAL_SUFFIXES = [ + 'localhost', + 'local', + 'localdomain', + 'internal', + 'home.arpa', + 'arpa', + 'test', + 'example', + 'invalid', + ]; + + /** + * @param \CakeDC\Mcp\Client\ClientConfig $config A user mode client. + * @return string The document's absolute URL, which is also its `client_id`. + */ + public static function url(ClientConfig $config): string + { + return Router::url( + [ + 'plugin' => 'CakeDC/Mcp', + 'controller' => 'McpClient', + 'action' => 'metadata', + 'prefix' => false, + $config->name, + ], + true, + ); + } + + /** + * @param \CakeDC\Mcp\Client\ClientConfig $config A user mode client. + * @return string The absolute URL of its sign-in callback, its only redirect URI. + */ + public static function callbackUrl(ClientConfig $config): string + { + return Router::url( + [ + 'plugin' => 'CakeDC/Mcp', + 'controller' => 'McpClient', + 'action' => 'callback', + 'prefix' => false, + $config->name, + ], + true, + ); + } + + /** + * @param \CakeDC\Mcp\Client\ClientConfig $config A user mode client. + * @return array The document. + */ + public static function document(ClientConfig $config): array + { + return [ + 'client_id' => self::url($config), + 'client_name' => (string)ClientConfig::setting('name'), + 'redirect_uris' => [self::callbackUrl($config)], + 'grant_types' => ['authorization_code', 'refresh_token'], + 'response_types' => ['code'], + // The draft recommends the list; the MCP specification's example has the single value. Both say none. + 'token_endpoint_auth_method' => 'none', + 'token_endpoint_auth_methods_supported' => ['none'], + 'application_type' => 'web', + ]; + } + + /** + * Whether an authorization server on the internet can fetch the document: its URL (from `App.fullBaseUrl`) is + * https, on a public IP address or a host name with a dot that is not a local or reserved name. With a + * resolver, the name must also resolve, to public addresses only: `*.ddev.site` resolves to this machine. + * A site behind a VPN with public addresses still passes, and needs `'registration' => 'dynamic'`. + * + * @param \CakeDC\Mcp\Client\ClientConfig $config A user mode client. + * @param \CakeDC\Mcp\Client\Http\HostResolverInterface|null $resolver Resolves the host name; null to decide on + * the name alone. + * @return bool + */ + public static function servable(ClientConfig $config, ?HostResolverInterface $resolver = null): bool + { + try { + $parts = parse_url(self::url($config)); + } catch (MissingRouteException) { + // The plugin routes are not loaded: nothing serves the document. + return false; + } + if (!is_array($parts) || strtolower((string)($parts['scheme'] ?? '')) !== 'https') { + return false; + } + $host = strtolower(trim((string)($parts['host'] ?? ''), '[]')); + if (filter_var($host, FILTER_VALIDATE_IP) !== false) { + return filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_GLOBAL_RANGE) !== false; + } + if (!str_contains($host, '.')) { + return false; + } + foreach (self::LOCAL_SUFFIXES as $suffix) { + if ($host === $suffix || str_ends_with($host, '.' . $suffix)) { + return false; + } + } + if ($resolver === null) { + return true; + } + $addresses = $resolver->resolve($host); + + return $addresses !== [] && array_filter( + $addresses, + fn(string $address): bool => !EndpointGuard::isPublic($address), + ) === []; + } +} diff --git a/src/Client/OAuth/Discovery.php b/src/Client/OAuth/Discovery.php new file mode 100644 index 0000000..d175ece --- /dev/null +++ b/src/Client/OAuth/Discovery.php @@ -0,0 +1,532 @@ +config; + $server = (string)$config->url; + if ($config->hasConfiguredEndpoints()) { + $parts = (array)parse_url((string)$config->tokenUrl); + + return new AuthServer( + $config->issuer ?? (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 && self::sameOrigin($metadataUrl, $server)) { + // On the origin of the configured url: trusted like it (an internal or localhost server), but named by + // the server, so its resource must be this server exactly. + $resourceMetadata = $this->firstDocument([$metadataUrl], true); + $prefixAllowed = false; + } elseif ($metadataUrl !== null) { + // Named by the server: learned, so through the guard, and its resource must be this server exactly. + $resourceMetadata = $this->firstDocument([$this->learnedUrl($metadataUrl)], false); + $prefixAllowed = false; + } else { + $resourceMetadata = $this->firstDocument(self::protectedResourceUrls($server), true); + $prefixAllowed = true; + } + $trustedIssuer = false; + if ($resourceMetadata === null) { + // A server of the 2025-03-26 revision, without protected resource metadata: its origin is the + // authorization server, and its metadata is on that origin, trusted like the configured url. + $origin = self::origin((array)parse_url($server)); + $originDocument = $this->firstDocument(self::metadataUrls($origin), true); + if ($originDocument === null || ($originDocument['issuer'] ?? null) !== $origin) { + throw new OAuthException($this->answeredWithoutSignIn + ? sprintf( + 'The server of "%s" does not ask for a sign-in; use it in app mode (without "auth" => ' + . '"user").', + $config->name, + ) + : sprintf('The server of "%s" does not publish how to sign in to it.', $config->name)); + } + $resourceMetadata = ['resource' => $server, 'authorization_servers' => [$origin]]; + $trustedIssuer = true; + } + $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; + $servers = is_array($servers) && array_is_list($servers) ? $servers : []; + $issuer = $servers[0] ?? null; + if (!is_string($issuer) || $issuer === '') { + throw new OAuthException(sprintf('The server of "%s" names no authorization server.', $config->name)); + } + if ($config->issuer !== null) { + // The configured issuer pins the authorization server: a client id and secret are bound to it. + if (!in_array($config->issuer, $servers, true)) { + throw new OAuthException(sprintf( + 'The server of "%s" names the authorization server %s, but "Mcp.clients.%s.issuer" is %s: ' + . 'the client is not signed in anywhere else.', + $config->name, + $issuer, + $config->name, + $config->issuer, + )); + } + $issuer = $config->issuer; + } + + $document = $this->firstDocument($this->authorizationServerUrls($issuer), $trustedIssuer); + 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'] ?? []); + // Servers in the OpenID Connect style only issue a refresh token for offline_access: ask for it with + // the other scopes when either side lists it. Configured scopes are sent as written. + $offline = [ + ...(is_array($document['scopes_supported'] ?? null) ? $document['scopes_supported'] : []), + ...(is_array($resourceMetadata['scopes_supported'] ?? null) + ? $resourceMetadata['scopes_supported'] + : []), + ]; + if ($scopes !== [] && in_array('offline_access', $offline, true)) { + $scopes[] = 'offline_access'; + } + } + + return new AuthServer( + $issuer, + $this->learnedUrl($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, + ($document['client_id_metadata_document_supported'] ?? null) === true, + ); + } + + /** + * 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) { + // It may ask for a sign-in only for some calls: the well-known URLs still say how. + $this->answeredWithoutSignIn = true; + + return []; + } + 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 = $this->learnedUrl($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. + */ + public static function metadataUrls(string $issuer): array + { + $parts = (array)parse_url($issuer); + $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]; + } + + /** + * @param string $issuer The expected issuer. + * @return list Its metadata URLs in the order RFC 8414 and OpenID Connect Discovery give. + */ + private function authorizationServerUrls(string $issuer): array + { + $parts = (array)parse_url($this->learnedUrl($issuer)); + if (isset($parts['query'])) { + throw self::unusable(''); + } + + return self::metadataUrls($issuer); + } + + /** + * Whether a grant made for $resource may be sent to $server: the same resource, or a path prefix of it, as + * discovery accepts. + * + * @param string $resource The `resource` the grant was made for. + * @param string $server The configured server URL. + * @return bool + */ + public static function covers(string $resource, string $server): bool + { + return self::resourceMatches($resource, $server, true); + } + + /** + * 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; plain http too for a + * client with both `allowPrivateNetwork` and `allowInsecure`. + * @throws \CakeDC\Mcp\Client\OAuth\OAuthException Otherwise. + */ + private function learnedUrl(mixed $value): string + { + $parts = is_string($value) ? parse_url($value) : false; + $schemes = $this->config->allowPrivateNetwork && $this->config->allowInsecure ? ['https', 'http'] : ['https']; + if ( + !is_string($value) + || !is_array($parts) + || !in_array(strtolower((string)($parts['scheme'] ?? '')), $schemes, true) + || ($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. + */ + public 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; + } + + /** + * Whether $url has the scheme, host and port of $server, the configured url (default ports included), and no + * credentials. + * + * @param string $url A URL the server named. + * @param string $server The configured url. + * @return bool + */ + private static function sameOrigin(string $url, string $server): bool + { + $origin = function (string $value): ?string { + $parts = parse_url($value); + if (!is_array($parts) || !isset($parts['scheme'], $parts['host']) || isset($parts['user'])) { + return null; + } + $scheme = strtolower($parts['scheme']); + $port = $parts['port'] ?? ($scheme === 'https' ? 443 : ($scheme === 'http' ? 80 : null)); + + return $scheme . '://' . strtolower($parts['host']) . ':' . $port; + }; + $mine = $origin($server); + + return $mine !== null && $origin($url) === $mine; + } +} 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); + // Scope step-up: what the user already had, and what the server asked for with insufficient_scope. + $scopes = array_values(array_unique([ + ...$server->scopes, + ...($this->store->get($this->config->name, $userId)?->stepUpScopes() ?? []), + ])); + $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, + $scopes === [] ? null : implode(' ', $scopes), + ); + $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 ($scopes !== []) { + $query['scope'] = implode(' ', $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.'); + } + $iss = $query['iss'] ?? null; + // With configured endpoints and no configured issuer, the issuer is not known: nothing to compare `iss` with. + $issuerKnown = !$pending->trusted || $this->config->issuer !== null; + if (($issuerKnown && $iss !== null && $iss !== $pending->issuer) || ($iss === null && $pending->issParameter)) { + // RFC 9207: the response must come from the server the flow started with (mix-up), an error response + // too: its error is not acted on (section 2.4). + throw new OAuthException('The sign-in response came from another authorization server.'); + } + if (isset($query['error'])) { + $error = OAuthException::code($query['error']) ?? 'error'; + + throw new OAuthException(sprintf('The authorization server answered %s.', $error), $error); + } + $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, + // RFC 6749 5.1: without `scope` in the answer, the scope granted is the one asked for. + $tokens->scope ?? $pending->scope, + $pending->issuer, + $pending->tokenUrl, + $pending->revocationUrl, + $pending->clientId, + $secret, + $pending->authMethod, + $pending->resource, + null, + $pending->scope, + ); + $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..6de02b8 --- /dev/null +++ b/src/Client/OAuth/PendingAuthorization.php @@ -0,0 +1,110 @@ + 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) + || !(is_string($data['scope'] ?? null) || ($data['scope'] ?? 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'], + $data['scope'] ?? null, + ); + } +} diff --git a/src/Client/OAuth/Registrar.php b/src/Client/OAuth/Registrar.php new file mode 100644 index 0000000..7f451a0 --- /dev/null +++ b/src/Client/OAuth/Registrar.php @@ -0,0 +1,222 @@ +config; + if ($config->clientId !== null) { + return new Registration( + $config->name, + $server->issuer, + $redirectUri, + $config->clientId, + $config->clientSecret, + self::automaticMethod($config->clientSecret !== null, $server->authMethods), + ); + } + if ($this->usesMetadataDocument($server)) { + // Portable across authorization servers: nothing to register or store. + return new Registration( + $config->name, + $server->issuer, + $redirectUri, + ClientMetadataDocument::url($config), + null, + 'none', + ); + } + $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(self::registrationRequest($redirectUri, $server->scopes), 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; + } + + /** + * The dynamic registration request (RFC 7591). `application_type` is `native` for a callback on this machine + * and `web` otherwise, as the MCP specification asks of OpenID Connect servers; `scope` is the scopes the + * client will ask for, when there are any. + * + * @param string $redirectUri The callback URL. + * @param list $scopes The scopes to ask for. + * @return array + */ + private static function registrationRequest(string $redirectUri, array $scopes): array + { + $host = strtolower(trim((string)parse_url($redirectUri, PHP_URL_HOST), '[]')); + $local = $host === 'localhost' || str_ends_with($host, '.localhost') + || filter_var($host, FILTER_VALIDATE_IP) !== false + && filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE) === false; + $request = [ + 'client_name' => (string)ClientConfig::setting('name'), + 'redirect_uris' => [$redirectUri], + 'grant_types' => ['authorization_code', 'refresh_token'], + 'response_types' => ['code'], + 'token_endpoint_auth_method' => 'none', + 'application_type' => $local ? 'native' : 'web', + ]; + if ($scopes !== []) { + $request['scope'] = implode(' ', $scopes); + } + + return $request; + } + + /** + * Whether the client id is the URL of the Client ID Metadata Document: `registration` `metadata`, or `auto` + * when the authorization server supports such documents and the application's base URL is public https. + * + * @param \CakeDC\Mcp\Client\OAuth\AuthServer $server The authorization server. + * @return bool + * @throws \CakeDC\Mcp\Client\OAuth\OAuthException When `metadata` is forced but cannot work. + */ + private function usesMetadataDocument(AuthServer $server): bool + { + $config = $this->config; + if ($config->registration === 'dynamic') { + return false; + } + if ($config->registration === 'auto') { + // Only where an authorization server can fetch the document: a site on this machine or a private + // network registers dynamically, as it can. + return $server->metadataDocuments + && ClientMetadataDocument::servable($config, $this->resolver ?? new DnsHostResolver()); + } + $servable = ClientMetadataDocument::servable($config); + if (!$servable) { + throw new OAuthException(sprintf( + '"Mcp.clients.%s.registration" is "metadata", but App.fullBaseUrl is not a public https address, so ' + . 'the authorization server cannot fetch %s.', + $config->name, + ClientMetadataDocument::url($config), + )); + } + if (!$server->metadataDocuments) { + throw new OAuthException(sprintf( + '"Mcp.clients.%s.registration" is "metadata", but the authorization server %s does not say ' + . 'client_id_metadata_document_supported. Use "auto" or "dynamic".', + $config->name, + $server->issuer, + )); + } + + return true; + } + + /** + * 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..521b66b --- /dev/null +++ b/src/Client/OAuth/TokenClient.php @@ -0,0 +1,254 @@ + $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, + )); + } + + /** + * Asks for an access token of the application itself (OAuth 2.1 client credentials grant). + * + * @param string $tokenUrl The token endpoint. + * @param bool $trusted Whether it comes from the config. + * @param string $clientId The client id. + * @param string $clientSecret The client secret. + * @param string $authMethod How the client authenticates. + * @param string $resource The MCP server (RFC 8707). + * @param list $scopes The scopes to ask for; none for the server's default. + * @return \CakeDC\Mcp\Client\OAuth\TokenSet + * @throws \CakeDC\Mcp\Client\OAuth\OAuthException + */ + public function clientCredentials( + string $tokenUrl, + bool $trusted, + string $clientId, + string $clientSecret, + string $authMethod, + string $resource, + array $scopes, + ): TokenSet { + $form = ['grant_type' => 'client_credentials', 'resource' => $resource]; + if ($scopes !== []) { + $form['scope'] = implode(' ', $scopes); + } + + 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 @@ + + */ +final class PingHandler implements RequestHandlerInterface +{ + /** + * @inheritDoc + */ + public function supports(Request $request): bool + { + return $request instanceof PingRequest; + } + + /** + * @inheritDoc + */ + public function handle(Request $request): Response + { + return new Response($request->getId(), new EmptyResult()); + } +} diff --git a/src/Client/ServerUrlPolicy.php b/src/Client/ServerUrlPolicy.php new file mode 100644 index 0000000..809f3b6 --- /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. + */ + public 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/Store/ConnectionStoreInterface.php b/src/Client/Store/ConnectionStoreInterface.php new file mode 100644 index 0000000..5f904e9 --- /dev/null +++ b/src/Client/Store/ConnectionStoreInterface.php @@ -0,0 +1,102 @@ + The scopes the sign-in that made this grant asked for. + */ + public function requestedScopes(): array + { + return $this->requestedScope === null + ? [] + : array_values(array_filter(explode(' ', $this->requestedScope), fn(string $s): bool => $s !== '')); + } + + /** + * @return list The scopes to ask for at the next connect, empty when the server asked for none more. + */ + public function stepUpScopes(): array + { + return $this->stepUpScope === null + ? [] + : array_values(array_filter(explode(' ', $this->stepUpScope), fn(string $s): bool => $s !== '')); + } + + /** + * This grant, marked as needing $scopes too: the granted scopes, those marked before and $scopes. + * + * @param list $scopes The scopes the server asked for. + * @return self + */ + public function withStepUp(array $scopes): self + { + $granted = $this->scope === null ? [] : explode(' ', $this->scope); + $all = array_values(array_unique(array_filter( + [...$granted, ...$this->stepUpScopes(), ...$scopes], + fn(string $s): bool => $s !== '', + ))); + // Bounded, in the order above: the scopes come from the MCP server, and the next authorization URL and + // the database column carry them. + $union = []; + $length = 0; + foreach ($all as $scope) { + $length += strlen($scope) + ($union === [] ? 0 : 1); + if (count($union) >= self::MAX_STEP_UP_SCOPES || $length > self::MAX_STEP_UP_LENGTH) { + break; + } + $union[] = $scope; + } + + return new self( + $this->client, + $this->userId, + $this->accessToken, + $this->refreshToken, + $this->expiresAt, + $this->scope, + $this->issuer, + $this->tokenUrl, + $this->revocationUrl, + $this->clientId, + $this->clientSecret, + $this->authMethod, + $this->resource, + implode(' ', $union), + $this->requestedScope, + ); + } + + /** + * @param string $accessToken The new access token. + * @param string|null $refreshToken The refresh token to keep. + * @param int|null $expiresAt When the access token expires. + * @param string|null $scope The scopes granted. + * @return self The same grant with new tokens. + */ + public function withTokens(string $accessToken, ?string $refreshToken, ?int $expiresAt, ?string $scope): self + { + return new self( + $this->client, + $this->userId, + $accessToken, + $refreshToken, + $expiresAt, + $scope, + $this->issuer, + $this->tokenUrl, + $this->revocationUrl, + $this->clientId, + $this->clientSecret, + $this->authMethod, + $this->resource, + $this->stepUpScope, + $this->requestedScope, + ); + } + + /** + * @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..f616197 --- /dev/null +++ b/src/Client/Store/TableConnectionStore.php @@ -0,0 +1,349 @@ +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(['connection_key' => self::connectionKey($client, $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'), + self::nullableString($row->get('step_up_scope')), + self::nullableString($row->get('requested_scope')), + ); + } + + /** + * @inheritDoc + */ + public function save(StoredConnection $connection): void + { + $data = [ + 'connection_key' => self::connectionKey($connection->client, $connection->userId), + '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, + 'step_up_scope' => $connection->stepUpScope, + 'requested_scope' => $connection->requestedScope, + // A refresh of the grant replaced here must not write the old grant's tokens over this one. + 'refresh_claim_id' => null, + 'refresh_claimed_at' => null, + ]; + $this->upsert($this->connections(), 'connection_key', $data); + } + + /** + * @inheritDoc + */ + public function markStepUp(string $client, string $userId, string $scope): void + { + $this->connections()->updateAll( + ['step_up_scope' => $scope], + ['connection_key' => self::connectionKey($client, $userId)], + ); + } + + /** + * @inheritDoc + */ + public function saveRefreshed(StoredConnection $connection, string $claimId): bool + { + // One conditional UPDATE: a deleted row, or a claim that is no longer this one, matches nothing. + return $this->connections()->updateAll( + [ + 'access_token' => $this->encrypt($connection->accessToken), + 'refresh_token' => $this->encrypt($connection->refreshToken), + 'expires' => $connection->expiresAt === null + ? null + : DateTime::createFromTimestamp($connection->expiresAt), + 'scope' => $connection->scope, + ], + [ + 'connection_key' => self::connectionKey($connection->client, $connection->userId), + 'refresh_claim_id' => $claimId, + ], + ) === 1; + } + + /** + * @inheritDoc + */ + public function claimRefresh(string $client, string $userId, string $claimId, int $leaseSeconds): bool + { + $now = DateTime::now(); + + // One conditional UPDATE: only one request can turn a free (or expired) claim into its own. + return $this->connections()->updateAll( + ['refresh_claim_id' => $claimId, 'refresh_claimed_at' => $now], + [ + 'connection_key' => self::connectionKey($client, $userId), + 'OR' => [ + 'refresh_claim_id IS' => null, + 'refresh_claimed_at <' => $now->subSeconds($leaseSeconds), + ], + ], + ) === 1; + } + + /** + * @inheritDoc + */ + public function releaseRefresh(string $client, string $userId, string $claimId): void + { + $this->connections()->updateAll( + ['refresh_claim_id' => null, 'refresh_claimed_at' => null], + ['connection_key' => self::connectionKey($client, $userId), 'refresh_claim_id' => $claimId], + ); + } + + /** + * @inheritDoc + */ + public function delete(string $client, string $userId): void + { + $this->connections()->deleteAll(['connection_key' => self::connectionKey($client, $userId)]); + } + + /** + * @inheritDoc + */ + public function registration(string $client, string $issuer): ?Registration + { + $row = $this->registrations()->find() + ->where(['registration_key' => self::registrationKey($client, $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 + { + $data = [ + 'registration_key' => self::registrationKey($registration->client, $registration->issuer), + '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, + ]; + $this->upsert($this->registrations(), 'registration_key', $data); + } + + /** + * Updates the row with $data's key, or inserts it. When another request inserts the same key between the read + * and the insert (two first requests of a user at once), the unique index refuses the insert: the row is read + * again and updated, so both succeed and the last one wins. + * + * @param \Cake\ORM\Table $table The table. + * @param string $key The unique key column. + * @param array $data The row. + * @return void + */ + private function upsert(Table $table, string $key, array $data): void + { + for ($attempt = 0;; $attempt++) { + $row = $table->find()->where([$key => $data[$key]])->first(); + $entity = $row instanceof EntityInterface + ? $table->patchEntity($row, $data, ['validate' => false]) + : $table->newEntity($data, ['validate' => false]); + try { + $table->saveOrFail($entity); + + return; + } catch (Throwable $e) { + // The ORM declares no exception here; the driver's QueryException is what the index raises. + if (!$e instanceof QueryException || $row instanceof EntityInterface || $attempt > 0) { + throw $e; + } + } + } + } + + /** + * @inheritDoc + */ + public function deleteRegistration(string $client, string $issuer): void + { + $this->registrations()->deleteAll(['registration_key' => self::registrationKey($client, $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'); + } + + /** + * The HMAC salt, derived from the key: by default Security mixes in the application's salt, and changing that + * would make every stored grant unreadable even with `Mcp.client.encryptionKey` set. + * + * @return string + */ + private function hmacSalt(): string + { + return hash('sha256', 'cakedc-mcp-client:' . $this->key); + } + + /** + * @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, $this->hmacSalt())); + } + + /** + * @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, $this->hmacSalt()); + } + + /** + * @param mixed $value A column value. + * @return string|null + */ + private static function nullableString(mixed $value): ?string + { + return is_string($value) && $value !== '' ? $value : null; + } + + /** + * The key a grant is found by: a hash, so that no collation of the database can match another user's grant. + * + * @param string $client The client's name. + * @param string $userId The user. + * @return string 64 hex characters. + */ + public static function connectionKey(string $client, string $userId): string + { + return hash('sha256', $client . "\0" . $userId); + } + + /** + * The key a registration is found by, as connectionKey(). + * + * @param string $client The client's name. + * @param string $issuer The authorization server. + * @return string 64 hex characters. + */ + public static function registrationKey(string $client, string $issuer): string + { + return hash('sha256', $client . "\0" . $issuer); + } +} 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/UserConnection.php b/src/Client/UserConnection.php new file mode 100644 index 0000000..9060e3e --- /dev/null +++ b/src/Client/UserConnection.php @@ -0,0 +1,428 @@ +for($user)`. + * + * Calls send the user's stored access token. It is refreshed when it expires within `Mcp.client.refreshLeeway` + * seconds, and once more when the server answers 401; when there is no usable grant left, the call throws + * NotConnectedException and the grant is deleted, so `isConnected()` is false and the user can connect again. + */ +final class UserConnection +{ + use CallsServerTrait; + + /** + * How many times, and how long each, a request waits for another one's refresh: 10 seconds in all. + */ + private const REFRESH_WAITS = 40; + + private const REFRESH_WAIT_MICROSECONDS = 250_000; + + private ?ClientSession $session = null; + + private ?string $sessionToken = null; + + /** + * @param \CakeDC\Mcp\Client\ClientConfig $config The user mode client. + * @param \CakeDC\Mcp\Client\ClientRegistry $registry Its HTTP client, store and token client. + * @param string $userId The user. + */ + public function __construct( + private ClientConfig $config, + private ClientRegistry $registry, + private string $userId, + ) { + } + + /** + * @inheritDoc + */ + public function config(): ClientConfig + { + return $this->config; + } + + /** + * @return string The user's id, as stored. + */ + public function userId(): string + { + return $this->userId; + } + + /** + * @return bool Whether the user has a grant the client can use (a refresh token, or an access token that has not + * expired). + */ + public function isConnected(): bool + { + $stored = $this->stored(); + + return $stored !== null + && ($stored->refreshToken !== null || !$stored->expiresWithin(0, DateTime::now()->getTimestamp())); + } + + /** + * The address of the plugin's connect route for this client; send the logged-in user there to sign in. + * + * @param string|null $redirect A local path to come back to afterwards. + * @return string A full URL. + */ + public function connectUrl(?string $redirect = null): string + { + $url = ['plugin' => 'CakeDC/Mcp', 'controller' => 'McpClient', 'action' => 'connect', $this->config->name]; + if ($redirect !== null) { + $url['?'] = ['redirect' => $redirect]; + } + + return Router::url($url, true); + } + + /** + * Revokes the user's grant at the authorization server (best effort) and deletes it. + * + * @return void + */ + public function disconnect(): void + { + $this->close(); + $store = $this->registry->store(); + $stored = $store->get($this->config->name, $this->userId); + try { + if ($stored !== null) { + $trusted = $this->config->revocationUrl !== null + && $stored->revocationUrl === $this->config->revocationUrl; + $this->registry->tokens($this->config)->revoke($stored, $trusted); + } + } finally { + // Whatever revocation does, the local grant goes. + $store->delete($this->config->name, $this->userId); + } + } + + /** + * 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; + $this->sessionToken = null; + } + + /** + * @inheritDoc + */ + protected function listCache(): ?ListCache + { + // Only for a user who is still connected: a cached list is no way around a lost grant. Keyed by the access + // token too, so a list is not served after a reconnection with another account. + $stored = $this->config->cache !== null && $this->isConnected() ? $this->stored() : null; + + return $stored === null ? null : ListCache::for($this->config, $this->userId, $stored->accessToken); + } + + /** + * @inheritDoc + */ + protected function lastResult(string $method): ?array + { + return $this->session?->lastResult($method); + } + + /** + * @inheritDoc + */ + protected function run(callable $call): mixed + { + $session = $this->session($this->accessToken(false)); + $session->takeForbidden(); + try { + return $session->call($call); + } catch (ExceptionInterface $e) { + $this->markStepUp($session->takeForbidden()); + // Only a call the server refused before running any of it: never one whose stream a 401 cut short. + if (!$session->unauthorizedBeforeAccepted()) { + throw $e; + } + } + // The server no longer accepts the token: refresh once and try again. + $session = $this->session($this->accessToken(true)); + try { + return $session->call($call); + } catch (ExceptionInterface $e) { + if ($session->lastStatus() !== 401) { + throw $e; + } + $this->forget(); + + throw $this->notConnected(); + } + } + + /** + * Whether the server answered a call of this user with `403 insufficient_scope`: send the user to + * `connectUrl()` to sign in again with the scopes of `stepUpScopes()`. + * + * @return bool + */ + public function needsMoreScope(): bool + { + return $this->stepUpScopes() !== []; + } + + /** + * @return list The scopes the next connect asks for: those granted plus those the server asked for; + * empty when it asked for none. + */ + public function stepUpScopes(): array + { + return $this->stored()?->stepUpScopes() ?? []; + } + + /** + * Marks the grant with the scopes of an `insufficient_scope` challenge, kept until the user connects again. + * + * @param string|null $challenge The `WWW-Authenticate` header of the 403. + * @return void + */ + private function markStepUp(?string $challenge): void + { + $parameters = $challenge === null ? [] : Discovery::bearerParameters($challenge); + if (($parameters['error'] ?? null) !== 'insufficient_scope') { + return; + } + // offline_access is the authorization server's to offer, as on the first sign-in (Discovery): one that + // does not know it would refuse every connect while the mark asked for it. + $scopes = array_values(array_filter( + explode(' ', $parameters['scope'] ?? ''), + fn(string $scope): bool => $scope !== 'offline_access' + && preg_match('/\A[\x21\x23-\x5B\x5D-\x7E]+\z/', $scope) === 1, + )); + $stored = $this->stored(); + // A retry limit (MCP authorization, step-up): scopes the last sign-in already asked for were not granted, + // and connecting again would ask for the same. The call fails; the user is not sent round again. + if ($stored !== null && array_diff($scopes, $stored->requestedScopes()) === []) { + return; + } + if ($stored !== null && $scopes !== []) { + // Only the mark: the tokens may have been refreshed by another request since they were read. + $this->registry->store()->markStepUp( + $this->config->name, + $this->userId, + (string)$stored->withStepUp($scopes)->stepUpScope, + ); + } + } + + /** + * The user's grant, unless it was made for another server than the one configured now (the `url` changed): + * its token is never sent elsewhere. + * + * @return \CakeDC\Mcp\Client\Store\StoredConnection|null + */ + private function stored(): ?StoredConnection + { + $stored = $this->registry->store()->get($this->config->name, $this->userId); + + return $stored !== null && Discovery::covers($stored->resource, (string)$this->config->url) ? $stored : null; + } + + /** + * @param bool $rejected Whether the server just refused the stored access token. + * @return string An access token to send. + * @throws \CakeDC\Mcp\Client\Exception\NotConnectedException + */ + private function accessToken(bool $rejected): string + { + $stored = $this->stored(); + if ($stored === null) { + throw $this->notConnected(); + } + $now = DateTime::now()->getTimestamp(); + if (!$rejected && !$stored->expiresWithin((int)ClientConfig::setting('refreshLeeway'), $now)) { + return $stored->accessToken; + } + if ($stored->refreshToken === null) { + if ($rejected || $stored->expiresWithin(0, $now)) { + $this->forget(); + + throw $this->notConnected(); + } + + // About to expire and nothing to refresh it with: it is still good for now. + return $stored->accessToken; + } + + return $this->refresh($stored, $now); + } + + /** + * @param \CakeDC\Mcp\Client\Store\StoredConnection $stored The grant. + * @param int $now The time now. + * @return string The new access token. + * @throws \CakeDC\Mcp\Client\Exception\NotConnectedException When the grant is no longer accepted. + */ + private function refresh(StoredConnection $stored, int $now): string + { + $store = $this->registry->store(); + $claimId = Text::uuid(); + // Longer than the token request may take, so a claim never ends while its request is still running. + if (!$store->claimRefresh($this->config->name, $this->userId, $claimId, $this->config->timeout + 30)) { + return $this->waitForRefresh($stored); + } + try { + // Read again: another request may have refreshed, stored and released between our read and our claim, + // and the refresh token we read is then already spent. + $fresh = $this->stored(); + if ($fresh === null) { + throw $this->notConnected(); + } + if ($fresh->accessToken !== $stored->accessToken) { + return $fresh->accessToken; + } + + return $this->refreshClaimed($fresh, $now, $claimId); + } finally { + $store->releaseRefresh($this->config->name, $this->userId, $claimId); + } + } + + /** + * Another request is refreshing the grant: waits a bounded time for the token it stores, and never refreshes + * again with the refresh token that request just sent. + * + * @param \CakeDC\Mcp\Client\Store\StoredConnection $stored The grant as read before. + * @return string The new access token. + * @throws \CakeDC\Mcp\Client\Exception\NotConnectedException When the grant went meanwhile. + * @throws \CakeDC\Mcp\Client\Exception\ClientException When the other request did not finish in time. + */ + private function waitForRefresh(StoredConnection $stored): string + { + for ($attempt = 0; $attempt < self::REFRESH_WAITS; $attempt++) { + $this->registry->sleep(self::REFRESH_WAIT_MICROSECONDS); + $fresh = $this->stored(); + if ($fresh === null) { + throw $this->notConnected(); + } + if ($fresh->accessToken !== $stored->accessToken) { + return $fresh->accessToken; + } + } + + throw new ClientException(sprintf( + 'The connection to "%s" is being renewed by another request; try again in a moment.', + $this->config->name, + )); + } + + /** + * @param \CakeDC\Mcp\Client\Store\StoredConnection $stored The grant. + * @param int $now The time now. + * @param string $claimId This request's refresh claim. + * @return string The new access token. + * @throws \CakeDC\Mcp\Client\Exception\NotConnectedException When the grant is no longer accepted. + */ + private function refreshClaimed(StoredConnection $stored, int $now, string $claimId): string + { + $store = $this->registry->store(); + $trusted = $this->config->tokenUrl !== null && $stored->tokenUrl === $this->config->tokenUrl; + try { + $tokens = $this->registry->tokens($this->config)->refresh($stored, $trusted); + } catch (OAuthException $e) { + if (!in_array($e->error, ['invalid_grant', 'invalid_client', 'unauthorized_client'], true)) { + throw $e; + } + // Another request may have refreshed (and rotated) the grant meanwhile. + $again = $this->stored(); + if ($again !== null && $again->accessToken !== $stored->accessToken) { + return $again->accessToken; + } + $this->forget(); + + throw $this->notConnected(); + } + $updated = $stored->withTokens( + $tokens->accessToken, + $tokens->refreshToken ?? $stored->refreshToken, + $tokens->expiresIn === null ? null : $now + $tokens->expiresIn, + $tokens->scope ?? $stored->scope, + ); + if (!$store->saveRefreshed($updated, $claimId)) { + $current = $this->stored(); + if ($current === null) { + // The user disconnected while the token request ran: the new tokens are not kept, and not left live. + $this->registry->tokens($this->config)->revoke( + $updated, + $this->config->revocationUrl !== null && $updated->revocationUrl === $this->config->revocationUrl, + ); + + throw $this->notConnected(); + } + if ($current->accessToken !== $stored->accessToken) { + // The user signed in again meanwhile, which ended this refresh: that grant is the one to use. + return $current->accessToken; + } + } + + return $updated->accessToken; + } + + /** + * @param string $token The access token to send. + * @return \CakeDC\Mcp\Client\ClientSession A connection that sends it. + */ + private function session(string $token): ClientSession + { + if ($this->session === null || $this->sessionToken !== $token) { + $this->close(); + $this->session = new ClientSession( + $this->config, + $this->registry->http(), + ['Authorization' => 'Bearer ' . $token], + ListCache::for($this->config, $this->userId), + ); + $this->sessionToken = $token; + } + + return $this->session; + } + + /** + * Deletes the grant without revoking it (the server already refused it). + * + * @return void + */ + private function forget(): void + { + $this->close(); + $this->registry->store()->delete($this->config->name, $this->userId); + } + + /** + * @return \CakeDC\Mcp\Client\Exception\NotConnectedException + */ + private function notConnected(): NotConnectedException + { + return new NotConnectedException(sprintf( + 'The user is not connected to "%s": send them to McpClients::get(\'%s\')->for($user)->connectUrl().', + $this->config->name, + $this->config->name, + )); + } +} diff --git a/src/Client/UserId.php b/src/Client/UserId.php new file mode 100644 index 0000000..1c2631a --- /dev/null +++ b/src/Client/UserId.php @@ -0,0 +1,38 @@ + $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/Client/WatchedHttpClient.php b/src/Client/WatchedHttpClient.php new file mode 100644 index 0000000..0221198 --- /dev/null +++ b/src/Client/WatchedHttpClient.php @@ -0,0 +1,263 @@ +> + */ + private array $results = []; + + /** + * Whether the server accepted (2xx) a `tools/call` of the current call: then that call may have run. The other + * requests (`initialize`, `server/discover`, lists, reads, gets, completions) run nothing. + */ + private bool $accepted = false; + + /** + * Whether this connection sent its `server/discover` probe: only that one may be answered from the cache, a + * later one is a `ping()` that must reach the server. + */ + private bool $probed = false; + + /** + * The status and absolute `Location` of the last answer when it was a redirect, which is never followed. + * + * @var array{0: int, 1: string}|null + */ + private ?array $redirect = null; + + /** + * @param \Psr\Http\Client\ClientInterface $client The client it wraps. + * @param \CakeDC\Mcp\Client\ClientConfig|null $config The client, whose `token` callable is called for each request. + * @param \CakeDC\Mcp\Client\ListCache|null $cache The client's cache, for the `server/discover` probe. + */ + public function __construct( + private ClientInterface $client, + private ?ClientConfig $config = null, + private ?ListCache $cache = null, + ) { + } + + /** + * @inheritDoc + */ + public function sendRequest(RequestInterface $request): ResponseInterface + { + $this->lastStatus = null; + $this->lastChallenge = null; + $this->redirect = null; + $token = $this->config?->callableToken(); + if ($token !== null) { + $request = $request->withHeader('Authorization', 'Bearer ' . $token); + } + $method = self::method($request); + unset($this->results[$method]); + $discover = null; + if ($method === 'server/discover' && !$this->probed && $this->cache !== null) { + // Keyed by the credential this very request carries, as a private list is. + $discover = $this->cache->withCredential( + $request->getHeaderLine('Authorization') . "\0" . json_encode($this->config->headers ?? []), + ); + $kept = $discover->get('server/discover', null); + if (is_array($kept)) { + $this->probed = true; + $this->lastStatus = 200; + + return self::answer($request, $kept); + } + } + if ($method === 'server/discover') { + $this->probed = true; + } + $response = $this->client->sendRequest($request); + $this->lastStatus = $response->getStatusCode(); + $location = $response->getHeaderLine('Location'); + if (in_array($this->lastStatus, [301, 302, 303, 307, 308], true) && $location !== '') { + $this->redirect = [$this->lastStatus, GuardedHttp::resolve((string)$request->getUri(), $location)]; + } + if ( + $request->getMethod() === 'POST' + && $response->getStatusCode() >= 200 + && $response->getStatusCode() < 300 + && $method === 'tools/call' + ) { + $this->accepted = true; + } + $challenge = $response->getHeaderLine('WWW-Authenticate'); + $this->lastChallenge = $challenge === '' ? null : $challenge; + if ($response->getStatusCode() === 403 && $challenge !== '') { + $this->forbidden = $challenge; + } + if (in_array($method, ListCache::METHODS, true) && $response->getStatusCode() === 200) { + // Read here for its cache hints, which the SDK's list results do not keep, then handed on unread. + $body = (string)$response->getBody(); + $response = $response->withBody((new StreamFactory())->createStream($body)); + $result = self::result($body); + if ($result !== null) { + $this->results[$method] = $result; + $discover?->put('server/discover', null, $result, $result); + } + } + + return $response; + } + + /** + * @param \Psr\Http\Message\RequestInterface $request A `server/discover` request. + * @param array $result A fresh result kept for it. + * @return \Psr\Http\Message\ResponseInterface The answer the server gave then, to this request's id. + */ + private static function answer(RequestInterface $request, array $result): ResponseInterface + { + $body = $request->getBody(); + $decoded = json_decode((string)$body, true); + $body->rewind(); + + return new Response(['HTTP/1.1 200 OK', 'Content-Type: application/json'], (string)json_encode([ + 'jsonrpc' => '2.0', + 'id' => is_array($decoded) ? ($decoded['id'] ?? null) : null, + 'result' => $result, + ], JSON_UNESCAPED_SLASHES)); + } + + /** + * Starts a call: what `unauthorizedBeforeAccepted()` tells is about the requests from here on. + * + * @return void + */ + public function startCall(): void + { + $this->accepted = false; + } + + /** + * @return bool Whether the last answer was a 401 and the server accepted no `tools/call` of the call before it, + * so the call did not run and may be sent again with a new token. + */ + public function unauthorizedBeforeAccepted(): bool + { + return $this->lastStatus === 401 && !$this->accepted; + } + + /** + * @param string $method A list method. + * @return array|null The raw `result` of the last answer to it, if it was one. + */ + public function lastResult(string $method): ?array + { + return $this->results[$method] ?? null; + } + + /** + * @param \Psr\Http\Message\RequestInterface $request A request to the MCP server. + * @return string Its JSON-RPC method, or an empty string. + */ + private static function method(RequestInterface $request): string + { + $header = $request->getHeaderLine('Mcp-Method'); + if ($header !== '') { + return $header; + } + $body = $request->getBody(); + $decoded = json_decode((string)$body, true); + $body->rewind(); + + return is_array($decoded) && is_string($decoded['method'] ?? null) ? $decoded['method'] : ''; + } + + /** + * @param string $body A JSON or event-stream answer. + * @return array|null The `result` of the JSON-RPC response it holds. + */ + private static function result(string $body): ?array + { + $messages = [json_decode($body, true)]; + if ($messages[0] === null) { + // text/event-stream: the data lines of each event. + $messages = []; + foreach (preg_split('/\r?\n\r?\n/', $body) ?: [] as $event) { + $data = []; + foreach (preg_split('/\r?\n/', $event) ?: [] as $line) { + if (str_starts_with($line, 'data:')) { + $data[] = ltrim(substr($line, 5), ' '); + } + } + $messages[] = json_decode(implode("\n", $data), true); + } + } + foreach ($messages as $message) { + if (is_array($message) && is_array($message['result'] ?? null)) { + return $message['result']; + } + } + + return null; + } + + /** + * @return string|null The challenge of the last 403 since the previous call, which this forgets. + */ + public function takeForbidden(): ?string + { + $challenge = $this->forbidden; + $this->forbidden = null; + + return $challenge; + } + + /** + * @return string|null The `WWW-Authenticate` header of the last answer, null when it had none. + */ + public function lastChallenge(): ?string + { + return $this->lastChallenge; + } + + /** + * @return array{0: int, 1: string}|null The status and target of the last answer, when it was a redirect. + */ + public function lastRedirect(): ?array + { + return $this->redirect; + } + + /** + * @return int|null The status of the last answer, null when none came. + */ + public function lastStatus(): ?int + { + return $this->lastStatus; + } +} 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/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/src/Command/McpCheckCommand.php b/src/Command/McpCheckCommand.php index a83a17b..cf4a8bc 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; @@ -26,16 +27,35 @@ use CakeDC\Mcp\Audit\AuditSettings; use CakeDC\Mcp\Audit\AuditWriter; use CakeDC\Mcp\Authorization\AllowAllToolAuthorizer; +use CakeDC\Mcp\Authorization\ContentGate; +use CakeDC\Mcp\Authorization\PromptAuthorizerInterface; use CakeDC\Mcp\Authorization\RbacToolAuthorizer; +use CakeDC\Mcp\Authorization\ResourceAuthorizerInterface; +use CakeDC\Mcp\Authorization\ToolAuthorizerInterface; +use CakeDC\Mcp\Catalog\CatalogPatterns; +use CakeDC\Mcp\Catalog\ToolCatalog; +use CakeDC\Mcp\Client\ClientConfig; +use CakeDC\Mcp\Client\McpClients; +use CakeDC\Mcp\Client\OAuth\ClientMetadataDocument; +use CakeDC\Mcp\Client\Store\ConnectionStoreInterface; +use CakeDC\Mcp\Client\Store\TableConnectionStore; use CakeDC\Mcp\Identity\CurrentIdentity; use CakeDC\Mcp\Log\McpLogger; 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\Mcp\TestSuite\RecordingTransport; use CakeDC\OAuthServer\Authenticator\TokenAuthenticator; use CakeDC\OAuthServer\OAuthServer; +use InvalidArgumentException; +use Mcp\Schema\Enum\CacheScope; +use Mcp\Schema\Enum\ProtocolVersion; +use Mcp\Schema\Extension\Apps\McpApps; +use ReflectionClass; use ReflectionProperty; +use Symfony\Component\Finder\Finder; use Throwable; /** @@ -55,10 +75,15 @@ class McpCheckCommand extends Command private const LISTED_TOOLS = 10; /** - * @var list|null + * @var list>|null */ 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. */ @@ -87,9 +112,71 @@ public static function getDescription(): string * @inheritDoc */ public function execute(Arguments $args, ConsoleIo $io): int + { + $all = McpConfig::servers(); + $broken = McpConfig::serverErrors(); + $only = $args->getOption('server'); + $failed = false; + if (is_string($only) && isset($broken[$only])) { + $failed = $this->runChecks(['Server ' . $only => fn(): array => ['fail', $broken[$only]]], $io); + // An entry named `default` is ignored, and the default server is still checked. + if (!in_array($only, $all, true)) { + return static::CODE_ERROR; + } + } + if (is_string($only) && !in_array($only, $all, true)) { + $io->err(sprintf('"Mcp.servers.%s" is not configured.', $only)); + + return static::CODE_ERROR; + } + + // Entries of Mcp.servers that are not served: the plugin left their routes out. + if (!is_string($only)) { + foreach ($broken as $name => $error) { + $failed = $this->runChecks(['Server ' . $name => fn(): array => ['fail', $error]], $io) || $failed; + } + } + 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; + } + // Across all servers, also with --server: a shared route or resource concerns the server checked. + if (count($all) > 1) { + $failed = $this->runChecks(['Servers' => fn(): array => $this->serversCheck($all)], $io) || $failed; + } + if (!is_string($only)) { + $failed = $this->runChecks(['Clients' => fn(): array => $this->clients()], $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 ($this->checks() as $name => $probe) { + foreach ($checks as $name => $probe) { try { [$status, $message] = $probe(); } catch (Throwable $e) { @@ -100,7 +187,334 @@ public function execute(Arguments $args, ConsoleIo $io): int $failed = $failed || $status === 'fail'; } - return $failed ? static::CODE_ERROR : static::CODE_SUCCESS; + return $failed; + } + + /** + * The MCP clients of `Mcp.clients`: each config valid, and for user mode the connect and callback routes and the + * token store's tables. + * + * @return array{0: 'pass'|'warn'|'fail', 1: string} + */ + private function clients(): array + { + $names = ClientConfig::names(); + $problems = array_values(ClientConfig::errors()); + if ($names === [] && $problems === []) { + return ['pass', 'none']; + } + $described = []; + $warnings = []; + $userMode = false; + foreach ($names as $name) { + try { + $config = ClientConfig::fromConfig($name); + } catch (InvalidArgumentException $e) { + $problems[] = $e->getMessage(); + continue; + } + if ($config->allowPrivateNetwork) { + $warnings[] = sprintf( + '%s has allowPrivateNetwork: the authorization server its server names may be on your private ' + . 'network, so a compromised server can make the application call internal addresses', + $name, + ); + } + if ($config->isClientCredentials()) { + // Its token is kept in the connection store, like user grants. + $userMode = true; + $described[] = sprintf( + '%s (client credentials from %s)', + $name, + $config->tokenUrl ?? (string)$config->issuer, + ); + continue; + } + if (!$config->isUser()) { + // A token callable is never called here: it may read a vault. + $kind = $config->tokenProvider !== null ? 'app, token from a callable' : 'app'; + $described[] = sprintf('%s (%s)', $name, $config->isStdio() ? 'stdio' : $kind); + continue; + } + $userMode = true; + try { + $connect = Router::url([ + 'plugin' => 'CakeDC/Mcp', + 'controller' => 'McpClient', + 'action' => 'connect', + 'prefix' => false, + $name, + ]); + [$registration, $problem] = self::registration($config); + if ($problem !== null) { + $problems[] = $problem; + } + $described[] = sprintf('%s (user, connect at %s, %s)', $name, $connect, $registration); + } catch (MissingRouteException) { + $problems[] = 'the connect and callback routes of user mode clients are not connected: load the ' + . 'plugin routes'; + $described[] = sprintf('%s (user)', $name); + } + } + if ($userMode) { + $problems = array_merge($problems, $this->clientStore()); + } + $proxy = null; + try { + $proxy = ClientConfig::proxyForDisplay(); + } catch (InvalidArgumentException $e) { + $problems[] = $e->getMessage(); + } + if ($problems !== []) { + return ['fail', implode('; ', array_unique($problems)) . ', see ' . self::DOCS . 'mcp-client.md']; + } + + $line = implode(', ', $described) . ($proxy === null ? '' : '; through the proxy ' . $proxy); + if ($warnings !== []) { + return ['warn', $line . '; ' . implode('; ', $warnings)]; + } + + return ['pass', $line]; + } + + /** + * How a user mode client gets its client id, as far as the config tells without asking the authorization server. + * + * @param \CakeDC\Mcp\Client\ClientConfig $config A user mode client. + * @return array{0: string, 1: string|null} The description, and a problem when `metadata` cannot work. + */ + private static function registration(ClientConfig $config): array + { + if ($config->clientId !== null) { + return ['configured client id', null]; + } + if ($config->registration === 'dynamic') { + return ['dynamic registration', null]; + } + if ($config->registration === 'metadata') { + $servable = ClientMetadataDocument::servable($config); + + return $servable + ? ['metadata document ' . ClientMetadataDocument::url($config), null] + : ['metadata document', sprintf( + '"Mcp.clients.%s.registration" is "metadata", but App.fullBaseUrl is not a public https ' + . 'address, so no authorization server can fetch the document', + $config->name, + )]; + } + + // As the sign-in decides it: the name must also resolve, to public addresses only. + return [ClientMetadataDocument::servable($config, McpClients::registry()->resolver()) + ? sprintf( + 'metadata document %s when the authorization server supports it, else dynamic registration (a ' + . 'site no authorization server can reach, behind a VPN say, needs "registration" => "dynamic")', + ClientMetadataDocument::url($config), + ) + : 'dynamic registration, App.fullBaseUrl is not a public https address', null]; + } + + /** + * @return list What keeps user mode from storing tokens. + */ + private function clientStore(): array + { + $store = ClientConfig::setting('store'); + if (!is_string($store) || !is_subclass_of($store, ConnectionStoreInterface::class)) { + return [sprintf('"Mcp.client.store" must be a class implementing %s', ConnectionStoreInterface::class)]; + } + if ($store !== TableConnectionStore::class) { + return []; + } + try { + new TableConnectionStore(); + } catch (InvalidArgumentException $e) { + return [$e->getMessage()]; + } + $schema = $this->fetchTable('CakeDC/Mcp.McpClientConnections') + ->getConnection() + ->getSchemaCollection(); + $tables = $schema->listTables(); + $problems = []; + foreach (['mcp_client_connections', 'mcp_client_registrations'] as $table) { + if (!in_array($table, $tables, true)) { + $problems[] = sprintf( + 'the table %s is missing: run bin/cake migrations migrate -p CakeDC/Mcp', + $table, + ); + } + } + // Only a table that a pre-release of 2.2 created lacks it: migrating again adds nothing, as the migration + // is the same. + if ( + in_array('mcp_client_connections', $tables, true) + && !$schema->describe('mcp_client_connections')->hasColumn('requested_scope') + ) { + $problems[] = 'the table mcp_client_connections has no requested_scope column, so a pre-release of 2.2 ' + . 'created it: run bin/cake migrations rollback -p CakeDC/Mcp, then bin/cake migrations migrate -p ' + . 'CakeDC/Mcp (users connect again)'; + } + + return $problems; + } + + /** + * 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 = []; + $paths = []; + $resources = []; + $audiences = []; + foreach ($servers as $server) { + $route = McpConfig::get('route', $server); + if (is_string($route) && trim($route, '/') !== '') { + $paths[$server] = '/' . trim($route, '/'); + // By shape: `/mcp/{tenant}` and `/mcp/{partner}` are the same route, and only one server answers. + $routes[(string)preg_replace('/\{[^}\/]+\}/', '{}', $paths[$server])][] = $server; + } + $settings = AuthSettings::fromConfig($server); + 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 $names) { + if (count($names) > 1) { + $problems[] = sprintf('%s share the route %s', implode(' and ', $names), $paths[$names[0]]); + } + } + $problems = [...$problems, ...self::shadowedValues($paths)]; + 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, + ); + } + } + 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)]; + } + $nested = $this->nestedScanDirs($servers); + if ($nested !== []) { + return ['warn', implode('; ', $nested)]; + } + + return ['pass', sprintf('%d servers: %s', count($servers), implode(', ', $servers))]; + } + + /** + * A fixed route that fits another server's pattern (`/mcp/admin` next to `/mcp/{tenant}`): Cake's router matches + * fixed routes first, so that value of the pattern never reaches its server, and in oauth mode both would claim + * the same resource. + * + * @param array $paths The route of each server. + * @return list + */ + private static function shadowedValues(array $paths): array + { + $problems = []; + foreach ($paths as $fixedServer => $fixed) { + if (McpConfig::routeParams($fixed) !== []) { + continue; + } + foreach ($paths as $server => $pattern) { + $values = $server === $fixedServer || McpConfig::routeParams($pattern) === [] + ? null + : McpConfig::routeValues($pattern, $fixed); + if ($values !== null) { + $problems[] = sprintf( + 'the route %s of %s fits %s of %s: the router sends it to %s, so %s never serves the value %s', + $fixed, + $fixedServer, + $pattern, + $server, + $fixedServer, + $server, + implode('/', $values), + ); + } + } + } + + return $problems; + } + + /** + * Scan directories of one server that hold another server's, not excluded: discovery is recursive, so the + * outer server also registers the inner server's tools, resources and prompts. + * + * @param list $servers The servers. + * @return list + */ + private function nestedScanDirs(array $servers): array + { + $dirs = []; + foreach ($servers as $server) { + foreach ((array)McpConfig::get('discovery.scanDirs', $server) as $dir) { + if (!is_string($dir)) { + continue; + } + $real = realpath(rtrim(ROOT, DS) . DS . $dir); + if ($real !== false && is_dir($real)) { + $dirs[] = [$server, $dir, $real]; + } + } + } + $warnings = []; + foreach ($dirs as [$outer, $outerDir, $outerPath]) { + $excluded = array_filter((array)McpConfig::get('discovery.excludeDirs', $outer), 'is_string'); + foreach ($dirs as [$inner, $innerDir, $innerPath]) { + if ($outer === $inner || !str_starts_with($innerPath, $outerPath . DIRECTORY_SEPARATOR)) { + continue; + } + $relative = str_replace(DIRECTORY_SEPARATOR, '/', substr($innerPath, strlen($outerPath) + 1)); + foreach ($excluded as $pattern) { + // As the SDK's Finder reads it: relative to the scanned directory, any segment of the path. + $pattern = '#(?:^|/)' . preg_quote(trim($pattern, '/'), '#') . '(?:/|$)#'; + if (preg_match($pattern, $relative) === 1) { + continue 2; + } + } + $warnings[] = sprintf( + 'the scan directory %s of %s holds %s of %s, so %s also registers %s\'s tools, resources and ' + . 'prompts: use sibling directories, or add \'excludeDirs\' => [\'%s\'] to the discovery of %s ' + . '(excludeDirs is relative to each scan directory)', + $outerDir, + $outer, + $innerDir, + $inner, + $outer, + $inner, + $relative, + $outer, + ); + } + } + + return $warnings; } /** @@ -118,9 +532,15 @@ 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(), + '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(), 'Logging' => fn(): array => $this->logging(), 'Audit' => fn(): array => $this->audit(), ]; @@ -131,17 +551,219 @@ 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); } /** - * The tools the server offers, listed once per run. + * Every tool registered on the server, catalogued and app-only ones included, without the catalog's own + * `find_tools` and `call_tools`. * - * @return list + * @return list> + */ + private function registeredTools(): array + { + return $this->tools ??= array_values(array_filter( + $this->factory()->registeredToolDefinitions(), + fn(array $tool): bool => !in_array($tool['name'], [ToolCatalog::FIND, ToolCatalog::CALL], true), + )); + } + + /** + * @return list The names of `registeredTools()`. */ private function toolNames(): array { - return $this->tools ??= $this->factory()->toolNames(); + return array_map(fn(array $tool): string => (string)$tool['name'], $this->registeredTools()); + } + + /** + * @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); + // On in the config, or announced by the host hook (as a 2.1 application could). + $enabled = $this->factory()->appsAnnounced(); + 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', + )]; + } + + if ($apps === []) { + return ['pass', 'on, no app resources']; + } + $line = sprintf('%d app resources: %s', count($apps), implode(', ', $apps)); + $broken = $this->unrenderedApps($apps); + + return $broken === [] + ? ['pass', $line] + : ['warn', $line . '; ' . implode('; ', $broken) . ', see ' . self::DOCS . 'apps.md']; + } + + /** + * Reads each app page through the server, as a host does (trusted, without a caller): a page that needs one + * may fail here and render for a user, so a failure only warns. + * + * @param list $apps The app resource URIs. + * @return list ` does not render: ` for each page whose read fails. + */ + private function unrenderedApps(array $apps): array + { + $messages = [ + ['jsonrpc' => '2.0', 'id' => 'init', 'method' => 'initialize', 'params' => [ + 'protocolVersion' => ProtocolVersion::latestHandshake()->value, + 'capabilities' => ['extensions' => [McpApps::EXTENSION_ID => ['mimeTypes' => [McpApps::MIME_TYPE]]]], + 'clientInfo' => ['name' => 'mcp check', 'version' => '1.0'], + ]], + ['jsonrpc' => '2.0', 'method' => 'notifications/initialized'], + ]; + foreach ($apps as $index => $uri) { + $messages[] = [ + 'jsonrpc' => '2.0', + 'id' => $index, + 'method' => 'resources/read', + 'params' => ['uri' => $uri], + ]; + } + $transport = new RecordingTransport(array_map( + fn(array $message): string => (string)json_encode($message), + $messages, + )); + try { + $this->factory()->create(true)->run($transport); + } catch (Throwable $e) { + return [sprintf('the pages could not be read: %s', $e->getMessage())]; + } + $broken = []; + foreach ($apps as $index => $uri) { + $answer = $transport->responseFor($index); + if (!isset($answer['result'])) { + $error = $answer['error']['message'] ?? 'no answer'; + $broken[] = sprintf('%s does not render: %s', $uri, is_string($error) ? $error : 'no answer'); + } + } + + return $broken; + } + + /** + * @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')); + $catalogued = []; + $kept = []; + $tools = []; + foreach ($this->registeredTools() as $tool) { + $name = (string)$tool['name']; + $tools[] = $name; + $meta = is_array($tool['_meta'] ?? null) ? $tool['_meta'] : null; + if (CatalogPatterns::catalogues($patterns, $name, $meta)) { + $catalogued[] = $name; + } elseif (CatalogPatterns::matches($patterns, $name) && CatalogPatterns::keptOut($meta) !== 'app-only') { + // App-only tools are never for the model: only a tool the model sees is worth naming here. + $kept[] = $name; + } + } + sort($catalogued); + sort($kept); + $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', + )]; + } + + $line = sprintf('%d tools behind find_tools and call_tools', count($catalogued)) + . ($catalogued === [] ? '' : ': ' . self::names($catalogued)); + if ($kept !== []) { + $line .= sprintf( + '; kept in tools/list because they link to an app, which the host reads from tools/list: %s', + implode(', ', $kept), + ); + } + + return ['pass', $line]; + } + + /** + * @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} + */ + private function toolSchemas(): array + { + // 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']; + } + $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', + )]; } /** @@ -153,7 +775,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 ' @@ -169,11 +791,22 @@ 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', + )]; + } + $coverage = self::contentCoverage($authorizer); if ($authorizer instanceof AllowAllToolAuthorizer) { - return ['pass', 'AllowAllToolAuthorizer: every identified caller may call every tool']; + return ['pass', 'AllowAllToolAuthorizer: every identified caller may call every tool; ' . $coverage]; } if (!$authorizer instanceof RbacToolAuthorizer) { - return ['pass', $authorizer::class]; + return ['pass', $authorizer::class . '; ' . $coverage]; } $docs = self::DOCS . 'authorization.md#rbactoolauthorizer-cakedcauth'; $rules = $authorizer->permissions(); @@ -184,7 +817,20 @@ private function authorizerCheck(): array RbacToolAuthorizer::PLUGIN, RbacToolAuthorizer::CONTROLLER, $docs, - )]; + ) . '; ' . $coverage]; + } + $misnamed = self::misnamedControllers($rules); + if ($misnamed !== []) { + return ['warn', sprintf( + "rules for plugin '%s' name controllers it does not have, so they decide nothing: %s. The " + . "controllers are '%s' (tools), '%s' and '%s', see %s", + RbacToolAuthorizer::PLUGIN, + implode(', ', $misnamed), + RbacToolAuthorizer::CONTROLLER, + RbacToolAuthorizer::RESOURCES, + RbacToolAuthorizer::PROMPTS, + $docs, + ) . '; ' . $coverage]; } $forTools = count(array_filter($rules, fn(mixed $rule): bool => is_array($rule) && self::allowsTools($rule))); if ($forTools === 0) { @@ -195,10 +841,83 @@ private function authorizerCheck(): array RbacToolAuthorizer::PLUGIN, RbacToolAuthorizer::CONTROLLER, $docs, - )]; + ) . '; ' . $coverage]; + } + + return ['pass', sprintf( + 'RbacToolAuthorizer, %d of %d rules for the tools; %s', + $forTools, + count($rules), + $coverage, + )]; + } + + /** + * The controllers that rules for plugin `CakeDC/Mcp` name and the plugin does not have (`Resource`, `prompts`): + * such a rule matches nothing, and a content rule never switches its check on. + * + * @param array $rules The Rbac rules. + * @return list + */ + private static function misnamedControllers(array $rules): array + { + $known = [ + RbacToolAuthorizer::CONTROLLER, + RbacToolAuthorizer::RESOURCES, + RbacToolAuthorizer::PROMPTS, + // The plugin's routes (McpConfig::rbacPermissions()). + 'Mcp', + 'ProtectedResource', + 'McpClient', + ]; + $misnamed = []; + foreach ($rules as $rule) { + if (!is_array($rule)) { + continue; + } + $plugin = $rule['plugin'] ?? null; + $ours = $plugin === RbacToolAuthorizer::PLUGIN + || (is_array($plugin) && in_array(RbacToolAuthorizer::PLUGIN, $plugin, true)); + if (!$ours) { + continue; + } + foreach ((array)($rule['controller'] ?? []) as $controller) { + if (is_string($controller) && !str_contains($controller, '*') && !in_array($controller, $known, true)) { + $misnamed[$controller] = $controller; + } + } + } + + return array_values($misnamed); + } + + /** + * Whether the authorizer decides who reads resources and gets prompts. + * + * @param \CakeDC\Mcp\Authorization\ToolAuthorizerInterface $authorizer The authorizer. + * @return string + */ + private static function contentCoverage(ToolAuthorizerInterface $authorizer): string + { + $rbac = $authorizer instanceof RbacToolAuthorizer; + $resources = $authorizer instanceof ResourceAuthorizerInterface + && (!$rbac || $authorizer->decidesFor(RbacToolAuthorizer::RESOURCES)); + $prompts = $authorizer instanceof PromptAuthorizerInterface + && (!$rbac || $authorizer->decidesFor(RbacToolAuthorizer::PROMPTS)); + if ($resources && $prompts) { + return 'resources and prompts are covered'; + } + if (!$resources && !$prompts) { + return 'resources and prompts are not covered' . ($rbac + ? ' (no rule for controller Resources or Prompts)' + : ': every caller may list, read and get them'); } + [$covered, $not, $controller] = $resources + ? ['resources', 'prompts', RbacToolAuthorizer::PROMPTS] + : ['prompts', 'resources', RbacToolAuthorizer::RESOURCES]; - return ['pass', sprintf('RbacToolAuthorizer, %d of %d rules for the tools', $forTools, count($rules))]; + return sprintf('%s are covered, %s are not', $covered, $not) + . ($rbac ? sprintf(' (no rule for controller %s)', $controller) : ''); } /** @@ -251,8 +970,15 @@ 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) { + $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(); @@ -264,7 +990,11 @@ private function toolScopes(): array $problems[] = 'tools that need no scope, so any valid token may call them: ' . self::names($free); } } - $unknown = array_values(array_diff(array_keys($settings->toolScopes), $tools)); + // The catalog's own tools take a scope too: the SDK checks it before the inner calls are checked. + $known = McpConfig::get('catalog.enabled', $this->server) === true + ? [...$tools, ToolCatalog::FIND, ToolCatalog::CALL] + : $tools; + $unknown = array_values(array_diff(array_keys($settings->toolScopes), $known)); if ($unknown !== []) { $problems[] = 'Mcp.auth.scopes.tools names tools that do not exist: ' . implode(', ', $unknown); } @@ -311,7 +1041,7 @@ private function logging(): array */ private function audit(): array { - $settings = AuditSettings::fromConfig(); + $settings = AuditSettings::fromConfig($this->server); if (!$settings->enabled) { return ['pass', 'off']; } @@ -367,12 +1097,47 @@ private static function enginesFor(string $level, array $scopes): array */ private function endpoint(): array { - $route = McpConfig::get('route'); + $route = McpConfig::get('route', $this->server); + if ($this->server !== McpConfig::DEFAULT_SERVER && $route === false) { + return ['pass', sprintf( + 'no HTTP route (route is false): served over stdio only, with bin/cake mcp server --server %s', + $this->server, + )]; + } if (!is_string($route) || $route === '') { return ['warn', 'Mcp.route is disabled: only stdio (bin/cake mcp server) is served']; } - return ['pass', rtrim((string)Configure::read('App.fullBaseUrl'), '/') . $route]; + $url = rtrim((string)Configure::read('App.fullBaseUrl'), '/') . $route; + $params = McpConfig::routeParams($route); + if ($params !== [] && $this->server === McpConfig::DEFAULT_SERVER) { + return ['fail', sprintf( + 'Mcp.route %s has parameters, which only a named server may have (Mcp.servers): the default ' + . 'server answers every request with an error, see %s', + $route, + self::DOCS . 'configuration.md#routes-with-parameters', + )]; + } + + $values = $params === [] ? '' : sprintf(' (one server per value of %s)', implode(', ', $params)); + if ($params === []) { + return ['pass', $url]; + } + $names = implode(', ', $params); + $auth = (array)McpConfig::get('auth', $this->server); + if (($auth['mode'] ?? AuthSettings::HOST) === AuthSettings::HOST) { + return ['warn', sprintf( + '%s%s: host mode binds nothing to the value of %s, which the caller chooses in the URL: check in the ' + . 'tools or the authorizer that the identity belongs to it, see %s', + $url, + $values, + $names, + self::DOCS . 'configuration.md#routes-with-parameters', + )]; + } + // A configured resource or audience without every parameter stops the server (McpConfig), so a server + // that gets here binds each token to one value. + return ['pass', $url . $values]; } /** @@ -380,14 +1145,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), ), }]; } @@ -397,10 +1162,25 @@ 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']; } + // A default server with Mcp.route false is stdio only: its auth is the base the named servers inherit. + $route = McpConfig::get('route', $this->server); + if (!is_string($route) || trim($route, '/') === '') { + return ['pass', 'no HTTP endpoint']; + } + $declared = $this->declaredRouteValues(); + if ($declared !== null && $declared['values'] === []) { + return ['fail', sprintf( + 'no resource in OAuthServer.resources fits %s: declare the resource of each value of the route, ' + . 'see %s', + $declared['pattern'], + self::DOCS . 'configuration.md#routes-with-parameters', + )]; + } + $settings = AuthSettings::fromConfig($this->server, $this->routeSample()); $server = new ResourceServer($settings); $metadata = $server->metadata(); $server->validator(new CurrentIdentity()); @@ -411,6 +1191,15 @@ private function resource(): array $metadata->getMetadataUrl(), $scopes === [] ? 'none declared' : implode(' ', $scopes), ); + if ($declared !== null) { + $count = count($declared['values']); + $message .= sprintf( + '; %d declared %s %s', + $count, + $count === 1 ? 'resource fits' : 'resources fit', + $declared['pattern'], + ); + } $audiences = $settings->external?->audiences; if ($audiences === null) { return ['pass', $message]; @@ -432,26 +1221,31 @@ 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']; } + $declared = $this->declaredRouteValues(); + if ($declared !== null && $declared['values'] === []) { + return ['fail', 'no declared resource fits the route, see the Resource line']; + } + $values = $this->routeSample(); try { $url = Router::url([ 'plugin' => 'CakeDC/Mcp', 'controller' => 'ProtectedResource', 'action' => 'metadata', 'prefix' => false, - ]); + ] + ($this->server === McpConfig::DEFAULT_SERVER ? [] : ['server' => $this->server]) + $values); } catch (MissingRouteException) { return ['fail', 'the metadata route of the plugin is not connected: load the plugin routes']; } $advertised = (string)parse_url( - (new ResourceServer($settings))->metadata()->getMetadataUrl(), + (new ResourceServer(AuthSettings::fromConfig($this->server, $values)))->metadata()->getMetadataUrl(), PHP_URL_PATH, ); if ($url !== $advertised) { @@ -466,13 +1260,65 @@ private function metadataRoute(): array return ['pass', $url]; } + /** + * The values to probe this server's route with: none on a fixed route; in oauth mode those of the first + * resource declared in OAuthServer.resources that fits the route's resource; otherwise `sample` for each + * parameter. A probe of the pattern itself (`/mcp/t/{tenant}`) is no request the server ever answers. + * + * @return array + */ + private function routeSample(): array + { + $params = McpConfig::routeParams(McpConfig::get('route', $this->server)); + if ($params === []) { + return []; + } + + return $this->declaredRouteValues()['values'][0] ?? array_fill_keys($params, 'sample'); + } + + /** + * In oauth mode on a route with parameters, the values of each resource declared in OAuthServer.resources that + * fits the server's resource pattern (`http://localhost/mcp/t/{tenant}`); null otherwise. + * + * @return array{pattern: string, values: list>}|null + */ + private function declaredRouteValues(): ?array + { + if (McpConfig::routeParams(McpConfig::get('route', $this->server)) === []) { + return null; + } + try { + $settings = AuthSettings::fromConfig($this->server); + } catch (InvalidArgumentException) { + return null; + } + if ($settings->mode !== AuthSettings::OAUTH || !$this->oauthServerInstalled()) { + return null; + } + $pattern = $settings->resource; + $regex = '#^' . preg_replace( + '/\\\{([A-Za-z_][A-Za-z0-9_]*)\\\}/', + '(?P<$1>' . McpConfig::ROUTE_VALUE . ')', + preg_quote($pattern, '#'), + ) . '$#'; + $values = []; + foreach (OAuthServer::server()->config()->resources->all() as $resource) { + if (preg_match($regex, $resource->identifier, $match) === 1) { + $values[] = array_filter($match, 'is_string', ARRAY_FILTER_USE_KEY); + } + } + + return ['pattern' => $pattern, 'values' => $values]; + } + /** * @return array{0: 'pass'|'warn'|'fail', 1: string} */ private function hosts(): array { - $allowed = McpConfig::allowedHosts(); - $settings = AuthSettings::fromConfig(); + $allowed = McpConfig::allowedHosts($this->server); + $settings = AuthSettings::fromConfig($this->server, $this->routeSample()); if ($settings->mode === AuthSettings::HOST) { return ['pass', implode(', ', $allowed)]; } @@ -494,7 +1340,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']; } @@ -508,7 +1354,10 @@ private function csrf(): array } $callback = (new ReflectionProperty(CsrfProtectionMiddleware::class, 'skipCheckCallback')) ->getValue($middleware); - $request = new ServerRequest(['url' => $route, 'environment' => ['REQUEST_METHOD' => 'POST']]); + $request = new ServerRequest([ + 'url' => McpConfig::withRouteValues($route, $this->routeSample()), + 'environment' => ['REQUEST_METHOD' => 'POST'], + ]); return is_callable($callback) && $callback($request) === true ? ['pass', 'the MCP route is skipped'] @@ -526,8 +1375,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']; } @@ -539,6 +1388,7 @@ private function authenticators(): array return ['warn', $app . '; its authenticators were not inspected']; } $prefix = OAuthServer::server()->config()->tokenPrefix; + $route = McpConfig::withRouteValues($route, $this->routeSample()); $probe = (new ServerRequest(['url' => $route, 'environment' => ['REQUEST_METHOD' => 'POST']])) ->withHeader('Authorization', 'Bearer ' . $prefix . '_at_' . str_repeat('A', 43)); if (!$app instanceof AuthenticationServiceProviderInterface) { @@ -679,6 +1529,44 @@ private static function within(string $path, array $prefixes): bool return false; } + /** + * @return array{0: 'pass'|'warn'|'fail', 1: string} + */ + private function cacheHints(): array + { + // Read from the factory, so a policy the hook set is seen as the server sends it. + $policy = $this->factory()->cachePolicy(); + if ($policy === null) { + return ['pass', 'off (private, not cached)']; + } + $perUser = !$this->factory()->authorizer() instanceof AllowAllToolAuthorizer; + $perClient = McpConfig::get('apps.enabled', $this->server) === true; + $note = null; + if ($policy->scopeFor('tools/list') === CacheScope::Public && ($perUser || $perClient)) { + $note = $perUser + ? 'tools/list is sent private, because the authorizer can give each user different tools' + : 'tools/list is sent private, because clients with and without MCP Apps get different tools'; + } + // Over HTTP, an authorizer that decides who reads which resource makes the plugin send resources/read + // private (the check builds the server trusted, where nothing is filtered). + $readsPerUser = (new ContentGate($this->factory()->authorizer(), new CurrentIdentity()))->decidesResources(); + if ($policy->scopeFor('resources/read') === CacheScope::Public && !$readsPerUser) { + return ['warn', implode('; ', array_filter([ + $note, + 'resources/read is public: only right when every resource reads the same for every user. Set it ' + . 'to private in Mcp.server.cache.methods, see ' . self::DOCS . 'configuration.md#keys', + ]))]; + } + if ($policy->scopeFor('resources/read') === CacheScope::Public) { + $note = implode('; ', array_filter([ + $note, + 'resources/read is sent private, because the authorizer decides who reads which resource', + ])); + } + + return ['pass', sprintf('ttl %d ms', $policy->ttlFor('tools/list')) . ($note === null ? '' : '; ' . $note)]; + } + /** * Whether cakedc/cakephp-oauth-server is installed. * @@ -689,6 +1577,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', $this->server), '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/src/Command/McpInspectorCommand.php b/src/Command/McpInspectorCommand.php index 398c0e3..dbb7634 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.'); @@ -310,6 +327,17 @@ private function httpServer(?string $url, array $headers, ConsoleIo $io): ?array return null; } + $params = McpConfig::routeParams($route); + if ($params !== []) { + $io->error(sprintf( + 'The route %s has parameters ({%s}): pass the URL of one value with --url, such as %s.', + $route, + implode('}, {', $params), + rtrim($base, '/') . McpConfig::withRouteValues($route, array_fill_keys($params, 'acme')), + )); + + return null; + } $url = rtrim($base, '/') . $route; } @@ -333,7 +361,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/Controller/McpClientController.php b/src/Controller/McpClientController.php new file mode 100644 index 0000000..4018abd --- /dev/null +++ b/src/Controller/McpClientController.php @@ -0,0 +1,214 @@ +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 = ClientMetadataDocument::callbackUrl($config); + + 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); + } + + /** + * The client's OAuth Client ID Metadata Document: public, no login, no secret. + * + * @param string $client The client name. + * @return \Cake\Http\Response + */ + public function metadata(string $client): Response + { + $this->skipHostAuthorization(); + $config = $this->userModeClient($client); + if ($config === null) { + return $this->plain(404, 'Not Found'); + } + + return $this->response + ->withType('application/json') + ->withHeader('Cache-Control', 'public, max-age=3600') + ->withStringBody((string)json_encode(ClientMetadataDocument::document($config), JSON_UNESCAPED_SLASHES)); + } + + /** + * @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/Controller/McpController.php b/src/Controller/McpController.php index 8f8268a..acf7b45 100644 --- a/src/Controller/McpController.php +++ b/src/Controller/McpController.php @@ -16,9 +16,12 @@ use CakeDC\Mcp\McpConfig; use CakeDC\Mcp\Middleware\AuditRefusalMiddleware; use CakeDC\Mcp\Middleware\BodyLimitMiddleware; +use CakeDC\Mcp\Middleware\CatalogScopeMiddleware; +use CakeDC\Mcp\Middleware\HeaderEncodingMiddleware; use CakeDC\Mcp\Middleware\IdentityMiddleware; use CakeDC\Mcp\OAuth\AuthSettings; use CakeDC\Mcp\OAuth\ResourceServer; +use CakeDC\Mcp\OAuth\UndeclaredResourceException; use CakeDC\Mcp\Server\ServerFactory; use Closure; use Mcp\Server\Transport\Http\Middleware\CorsMiddleware; @@ -36,6 +39,7 @@ */ class McpController extends Controller { + use ResolvesServerTrait; use SkipsHostAuthorizationTrait; /** @@ -48,16 +52,27 @@ 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(); + $route = []; try { - $maxBodyBytes = McpConfig::maxBodyBytes(); - $origins = array_values(array_filter((array)McpConfig::get('http.allowedOrigins'), 'is_string')); + // The values of a route such as /mcp/{tenant}, for tools (McpRoute), the OAuth resource and the audit. + $route = $this->mcpRouteValues($server); + $factory->route()->set($route); + $maxBodyBytes = McpConfig::maxBodyBytes($server); + $origins = array_values(array_filter((array)McpConfig::get('http.allowedOrigins', $server), 'is_string')); $middleware = [ new CorsMiddleware($origins), + // Before the checks that read these headers. + new HeaderEncodingMiddleware($responseFactory, $streamFactory), new DnsRebindingProtectionMiddleware( - McpConfig::allowedHosts(), + McpConfig::allowedHosts($server), $origins, $responseFactory, $streamFactory, @@ -66,12 +81,28 @@ public function handle(ServerFactory $factory, CurrentIdentity $identity): Respo // Bearer challenge. new BodyLimitMiddleware($maxBodyBytes, $responseFactory, $streamFactory), ]; - $audit = AuditSettings::fromConfig(); + $audit = AuditSettings::fromConfig($server, $route); if ($audit->enabled) { // Right before authentication, to record the calls it refuses. - $middleware[] = new AuditRefusalMiddleware($audit, new AuditWriter($audit), $identity); + $middleware[] = new AuditRefusalMiddleware( + $audit, + new AuditWriter($audit), + $identity, + fn(string $tool): bool => $factory->isAppOnlyTool($tool), + ); + } + $middleware[] = $this->authentication( + $server, + $route, + $identity, + $responseFactory, + $streamFactory, + $maxBodyBytes, + ); + $catalog = $this->catalogScopes($server, $route, $responseFactory, $streamFactory, $maxBodyBytes); + if ($catalog !== null) { + $middleware[] = $catalog; } - $middleware[] = $this->authentication($identity, $responseFactory, $streamFactory, $maxBodyBytes); $transport = new StreamableHttpTransport( $this->request, $responseFactory, @@ -82,6 +113,10 @@ public function handle(ServerFactory $factory, CurrentIdentity $identity): Respo ); $response = $factory->create()->run($transport); } catch (Throwable $exception) { + if ($exception instanceof UndeclaredResourceException && $route !== []) { + // A value of /mcp/{tenant} whose resource nobody declared: anyone can ask for one, so no log. + return $this->response->withStatus(404); + } Log::error(sprintf("MCP request failed.\n%s", $exception), ['scope' => [McpLogger::SCOPE]]); return $this->internalError(); @@ -90,10 +125,46 @@ 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 array $route The values of its route's parameters. + * @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, + array $route, + ResponseFactory $responseFactory, + StreamFactory $streamFactory, + int $maxBodyBytes, + ): ?CatalogScopeMiddleware { + $settings = AuthSettings::fromConfig($server, $route); + $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. * + * @param string $server The MCP server. + * @param array $route The values of its route's parameters. * @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 +172,14 @@ public function handle(ServerFactory $factory, CurrentIdentity $identity): Respo * @return \Psr\Http\Server\MiddlewareInterface */ private function authentication( + string $server, + array $route, CurrentIdentity $identity, ResponseFactory $responseFactory, StreamFactory $streamFactory, int $maxBodyBytes, ): MiddlewareInterface { - $settings = AuthSettings::fromConfig(); + $settings = AuthSettings::fromConfig($server, $route); if ($settings->mode !== AuthSettings::HOST) { return (new ResourceServer($settings))->middleware( $identity, @@ -115,14 +188,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..359c8cb 100644 --- a/src/Controller/ProtectedResourceController.php +++ b/src/Controller/ProtectedResourceController.php @@ -9,6 +9,7 @@ use CakeDC\Mcp\Log\McpLogger; use CakeDC\Mcp\OAuth\AuthSettings; use CakeDC\Mcp\OAuth\ResourceServer; +use CakeDC\Mcp\OAuth\UndeclaredResourceException; use Throwable; /** @@ -18,6 +19,7 @@ */ class ProtectedResourceController extends Controller { + use ResolvesServerTrait; use SkipsHostAuthorizationTrait; private const CORS = [ @@ -41,9 +43,12 @@ public function metadata(): Response return $response->withStatus(204); } + $values = []; try { - $settings = AuthSettings::fromConfig(); - if ($settings->mode === AuthSettings::HOST) { + $server = $this->mcpServer(); + $values = $server === null ? [] : $this->mcpRouteValues($server); + $settings = $server === null ? null : AuthSettings::fromConfig($server, $values); + if ($settings === null || $settings->mode === AuthSettings::HOST) { return $response->withStatus(404) ->withType('application/json') ->withStringBody((string)json_encode(['error' => 'not_found'])); @@ -53,6 +58,12 @@ public function metadata(): Response JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES, ); } catch (Throwable $exception) { + if ($exception instanceof UndeclaredResourceException && $values !== []) { + // A value of /mcp/{tenant} whose resource nobody declared: anyone can ask for one, so no log. + return $response->withStatus(404) + ->withType('application/json') + ->withStringBody((string)json_encode(['error' => 'not_found'])); + } Log::error( sprintf("MCP protected resource metadata failed.\n%s", $exception), ['scope' => [McpLogger::SCOPE]], diff --git a/src/Controller/ResolvesServerTrait.php b/src/Controller/ResolvesServerTrait.php new file mode 100644 index 0000000..62ec765 --- /dev/null +++ b/src/Controller/ResolvesServerTrait.php @@ -0,0 +1,89 @@ +request), "\n")) { + return null; + } + $server = $this->request->getParam('server'); + $named = is_string($server) && $server !== ''; + $server = $named ? $server : McpConfig::DEFAULT_SERVER; + try { + $route = McpConfig::get('route', $server); + } catch (InvalidArgumentException) { + return null; + } + // Without a server param this is the default server, at whatever path the route that reached the controller + // has: the plugin's own, the plugin's routes loaded inside a scope, or a route the application connected + // itself (2.1 served all of them). + if (!$named) { + return $server; + } + // A named server only at its own route (or its metadata route): never a stdio only server, nor another + // server named by a route param. + if (!is_string($route) || trim($route, '/') === '') { + return null; + } + $path = McpConfig::requestPath($this->request); + $metadata = McpConfig::METADATA_PREFIX . '/' . trim($route, '/'); + if (McpConfig::routeValues($route, $path) === null && McpConfig::routeValues($metadata, $path) === null) { + return null; + } + foreach (McpConfig::hostRouteParams($server) as $name) { + $value = $this->request->getParam($name); + if (is_string($value) && $value !== strtolower($value)) { + return null; + } + } + + return $server; + } + + /** + * The values of the parameters of $server's route in this request (`/mcp/{tenant}`). + * + * @param string $server The server. + * @return array + * @throws \InvalidArgumentException When the default server's route has parameters, which only a named server + * may have: the request fails closed. + */ + protected function mcpRouteValues(string $server): array + { + $route = McpConfig::get('route', $server); + $params = McpConfig::routeParams($route); + if ($params !== [] && $server === McpConfig::DEFAULT_SERVER) { + throw new InvalidArgumentException(sprintf( + '"Mcp.route" is "%s": only a named server (Mcp.servers) may have route parameters, so the default ' + . 'server is not served. Give "Mcp.route" a fixed path and serve "%s" from a named server.', + (string)$route, + (string)$route, + )); + } + $values = []; + foreach ($params as $name) { + $value = $this->request->getParam($name); + if (is_string($value) && $value !== '') { + $values[$name] = $value; + } + } + + return $values; + } +} 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 df9d384..e068fc5 100644 --- a/src/Event/AuditListener.php +++ b/src/Event/AuditListener.php @@ -57,6 +57,10 @@ 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). + * @param \Closure|null $via `fn(Request $request): ?string`, the plugin tool that made a call (`call_tools`). + * @param \Closure|null $contentDenied `fn(Request $request): bool`, whether the authorizer denied a + * `resources/read` or `prompts/get` of something that exists: answered like an unknown one, recorded denied. */ public function __construct( private readonly AuditSettings $settings, @@ -65,6 +69,9 @@ public function __construct( private readonly CurrentIdentity $identity, ?Closure $clock = null, ?Closure $toolExists = null, + private readonly ?Closure $appOnly = null, + private readonly ?Closure $via = null, + private readonly ?Closure $contentDenied = null, ) { $this->clock = $clock ?? fn(): float => microtime(true); $this->toolExists = $toolExists; @@ -189,6 +196,7 @@ private function failed(ErrorEvent $event): void $error = $event->getError(); $outcome = match (true) { $request instanceof CallToolRequest && $this->isDenied($request->name) => AuditRecord::DENIED, + !$request instanceof CallToolRequest && $this->isContentDenied($request) => AuditRecord::DENIED, $error->code === Error::INVALID_PARAMS => AuditRecord::INVALID, default => AuditRecord::ERROR, }; @@ -228,9 +236,27 @@ 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), + $this->via === null ? null : ($this->via)($request), + $request instanceof CallToolRequest && $this->appOnly !== null && ($this->appOnly)($request->name) === true, )); } + /** + * @param \Mcp\Schema\JsonRpc\Request $request A request that failed. + * @return bool Whether the authorizer denied what it reads or gets (never when the authorizer itself failed). + */ + private function isContentDenied(Request $request): bool + { + if ($this->contentDenied === null) { + return false; + } + try { + return ($this->contentDenied)($request) === true; + } catch (Throwable) { + return false; + } + } + /** * Whether the gate refused an existing tool (an unknown tool is not a denial). * @@ -239,7 +265,12 @@ private function record(Request $request, SessionInterface $session, string $out */ private function isDenied(string $name): bool { - if ($this->gate->allows($name)) { + try { + if ($this->gate->allows($name)) { + return false; + } + } catch (Throwable) { + // The authorizer failed (it is why the call failed): the call is recorded as an error, not lost. return false; } diff --git a/src/Event/ContentListFilter.php b/src/Event/ContentListFilter.php new file mode 100644 index 0000000..5acfc34 --- /dev/null +++ b/src/Event/ContentListFilter.php @@ -0,0 +1,56 @@ +getResponse(); + $result = $response->result; + $filtered = match (true) { + $result instanceof ListResourcesResult => new ListResourcesResult(array_values(array_filter( + $result->resources, + fn(ResourceDefinition $resource): bool => $this->gate->allowsResource($resource->uri), + )), $result->nextCursor), + $result instanceof ListResourceTemplatesResult => new ListResourceTemplatesResult(array_values(array_filter( + $result->resourceTemplates, + fn(ResourceTemplate $template): bool => $this->gate->allowsResource($template->uriTemplate), + )), $result->nextCursor), + $result instanceof ListPromptsResult => new ListPromptsResult(array_values(array_filter( + $result->prompts, + fn(Prompt $prompt): bool => $this->gate->allowsPrompt($prompt->name), + )), $result->nextCursor), + default => null, + }; + if ($filtered !== null) { + $event->setResponse(new Response($response->getId(), $filtered)); + } + } +} diff --git a/src/Event/ToolListFilter.php b/src/Event/ToolListFilter.php index 9b601d9..bdde6d0 100644 --- a/src/Event/ToolListFilter.php +++ b/src/Event/ToolListFilter.php @@ -4,8 +4,12 @@ namespace CakeDC\Mcp\Event; use CakeDC\Mcp\Authorization\ToolGate; +use Closure; +use Mcp\Capability\RegistryInterface; use Mcp\Event\ResponseEvent; +use Mcp\Schema\JsonRpc\Request; use Mcp\Schema\JsonRpc\Response; +use Mcp\Schema\Request\ListToolsRequest; use Mcp\Schema\Result\ListToolsResult; use Mcp\Schema\Tool; @@ -16,9 +20,15 @@ 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). + * @param \Closure(): (\Mcp\Capability\RegistryInterface|null)|null $registry The registry the page came from, + * to fill a page the filter emptied from the pages after it. */ - public function __construct(private readonly ToolGate $gate) - { + public function __construct( + private readonly ToolGate $gate, + private readonly ?Closure $hidden = null, + private readonly ?Closure $registry = null, + ) { } /** @@ -33,10 +43,56 @@ public function __invoke(ResponseEvent $event): void return; } - $tools = array_values(array_filter( - $result->tools, - fn(Tool $tool): bool => $this->gate->allows($tool->name), - )); - $event->setResponse(new Response($response->getId(), new ListToolsResult($tools, $result->nextCursor))); + $tools = array_values(array_filter($result->tools, $this->keeps(...))); + $cursor = $result->nextCursor; + $registry = $this->registry === null ? null : ($this->registry)(); + if ($cursor !== null && count($tools) < count($result->tools) && $registry instanceof RegistryInterface) { + [$tools, $cursor] = $this->fill($tools, count($result->tools), $event->getRequest(), $registry, $cursor); + } + $event->setResponse(new Response($response->getId(), new ListToolsResult($tools, $cursor))); + } + + /** + * @param \Mcp\Schema\Tool $tool A tool of the page. + * @return bool Whether the caller sees it. + */ + private function keeps(Tool $tool): bool + { + return $this->gate->allows($tool->name) && ($this->hidden === null || !($this->hidden)($tool->name)); + } + + /** + * Fills a page the filter left short from the tools after it, so a client does not get empty pages (120 + * catalogued tools would list as two tools and then empty pages). The cursor is the registry's own (the + * offset after the last tool looked at), so the server's handler reads it as usual. A registry whose cursors + * are not those offsets (one of the application's own) keeps its page and its cursor: only it can read them. + * + * @param list<\Mcp\Schema\Tool> $tools The tools kept from the page. + * @param int $size The page size. + * @param \Mcp\Schema\JsonRpc\Request $request The `tools/list` request. + * @param \Mcp\Capability\RegistryInterface $registry The registry. + * @param string $next The cursor the registry gave for the next page. + * @return array{0: list<\Mcp\Schema\Tool>, 1: string|null} + */ + private function fill(array $tools, int $size, Request $request, RegistryInterface $registry, string $next): array + { + $cursor = $request instanceof ListToolsRequest ? $request->cursor : null; + $start = $cursor === null ? '0' : base64_decode($cursor, true); + if (!is_string($start) || !ctype_digit($start) || $next !== base64_encode((string)((int)$start + $size))) { + return [$tools, $next]; + } + $all = array_values($registry->getTools()->references); + $total = count($all); + $missing = $size - count($tools); + $offset = (int)$start + $size; + while ($missing > 0 && $offset < $total) { + $tool = $all[$offset++]; + if ($this->keeps($tool)) { + $tools[] = $tool; + $missing--; + } + } + + return [$tools, $offset < $total ? base64_encode((string)$offset) : null]; } } 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/Log/ConfigMistakes.php b/src/Log/ConfigMistakes.php new file mode 100644 index 0000000..4c13964 --- /dev/null +++ b/src/Log/ConfigMistakes.php @@ -0,0 +1,62 @@ + null`) or an error in the `mcp` scope. Each engine gets it once. + */ +final class ConfigMistakes +{ + /** + * @var array + */ + private static array $logged = []; + + /** + * @param string $message The message. + * @return void + */ + public static function log(string $message): void + { + if (isset(self::$logged[$message])) { + return; + } + self::$logged[$message] = true; + + $scope = [McpLogger::SCOPE]; + foreach (Log::configured() as $name) { + $engine = Log::engine((string)$name); + if ($engine === null) { + continue; + } + $levels = $engine instanceof BaseLog ? $engine->levels() : []; + $scopes = $engine instanceof BaseLog ? $engine->scopes() : null; + if ($levels !== [] && !in_array('error', $levels, true)) { + continue; + } + // Unscoped messages reach `null` scopes, scoped ones reach engines that list `mcp`, and `[]` + // takes both: the same rules as Log::write(), applied once per engine. + $takes = $scopes === null || $scopes === [] || array_intersect($scope, (array)$scopes) !== []; + if ($takes) { + $engine->log('error', $message, $scopes === null ? ['scope' => []] : ['scope' => $scope]); + } + } + } + + /** + * Forgets what was logged, so a test can see it logged again. + * + * @internal For tests. + * @return void + */ + public static function reset(): void + { + self::$logged = []; + } +} diff --git a/src/Log/McpLogger.php b/src/Log/McpLogger.php index 9366c6e..87d964e 100644 --- a/src/Log/McpLogger.php +++ b/src/Log/McpLogger.php @@ -16,6 +16,30 @@ final class McpLogger extends AbstractLogger { public const SCOPE = 'mcp'; + /** + * @param array $redact Text to replace in every message, by what replaces it: the URL of a + * client with its query, which may carry a key, by the URL without it. + */ + public function __construct(private readonly array $redact = []) + { + } + + /** + * For a client: its configured URL, logged without its query. + * + * @param string|null $url The configured URL. + * @return self + */ + public static function forUrl(?string $url): self + { + $query = $url === null ? false : strpos($url, '?'); + if ($url === null || $query === false) { + return new self(); + } + + return new self([$url => substr($url, 0, $query) . '?(query left out)']); + } + /** * @param mixed $level PSR-3 level. * @param \Stringable|string $message The message. @@ -43,6 +67,10 @@ public function log(mixed $level, string|Stringable $message, array $context = [ // Throwables go last so the one-line key=value pairs stay next to the message. usort($extra, fn(string $a, string $b): int => ($a[0] === "\n") <=> ($b[0] === "\n")); - Log::write(is_string($level) ? $level : 'info', $message . implode('', $extra), $context); + $line = $message . implode('', $extra); + if ($this->redact !== []) { + $line = strtr($line, $this->redact); + } + Log::write(is_string($level) ? $level : 'info', $line, $context); } } diff --git a/src/McpConfig.php b/src/McpConfig.php index 7ec4dfa..fff827a 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; @@ -19,6 +20,18 @@ */ final class McpConfig { + /** + * The values a route parameter takes: a slug. + */ + public const ROUTE_VALUE = '[A-Za-z0-9_-]+'; + + /** + * Route parameter names Cake routing or the plugin read, which a route of a server cannot use. + * + * @var list + */ + public const RESERVED_PARAMS = ['server', 'plugin', 'controller', 'action', 'prefix', 'pass']; + /** * Path prefix of the protected resource metadata (RFC 9728), followed by the MCP route. */ @@ -35,10 +48,15 @@ final class McpConfig 'title' => null, 'description' => null, 'websiteUrl' => null, + 'icons' => null, 'instructions' => null, + 'cache' => null, 'configure' => null, ], 'discovery' => ['scanDirs' => ['src/Mcp'], 'excludeDirs' => [], 'cache' => '_cake_mcp_'], + 'schema' => ['normalize' => false], + 'catalog' => ['enabled' => false, 'tools' => [], 'maxCalls' => 5, 'maxResultBytes' => 65536], + 'apps' => ['enabled' => false], 'session' => ['cache' => 'mcp_sessions', 'ttl' => 3600], 'http' => ['allowedHosts' => null, 'allowedOrigins' => [], 'maxBodyBytes' => 4 * 1024 * 1024], 'identity' => ['required' => true, 'attribute' => 'identity', 'scopes' => null], @@ -73,25 +91,621 @@ 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'; + + /** + * The plugin's controllers that answer at a server's route and at its metadata route. + */ + private const ENDPOINT_CONTROLLERS = ['Mcp', 'ProtectedResource']; + + /** + * 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. `identity` is never inherited: a + * named server that does not set it gets the plugin's defaults (an identity is required). + * + * @var list + */ + private const REPLACED_SECTIONS = ['auth', 'authorization', 'discovery', 'identity']; + + /** + * @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 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 servers the plugin serves: `default` first, then the keys of `Mcp.servers` in order, without the named + * servers whose config is invalid. Those are listed by `serverErrors()`: the plugin logs them, does not + * connect their routes and `bin/cake mcp check` fails on them, while the rest of the application keeps working. + * + * @return list + */ + public static function servers(): array + { + $servers = [self::DEFAULT_SERVER]; + foreach (array_keys(self::named()[0]) as $name) { + try { + self::resolve($name); + } catch (InvalidArgumentException) { + continue; + } + $servers[] = $name; + } + + return $servers; + } + + /** + * The entries of `Mcp.servers` that cannot be served, as entry name => what is wrong. The name is + * `Mcp.servers` when the whole setting is not an array of server name => config. + * + * @return array + */ + public static function serverErrors(): array + { + [$valid, $errors] = self::named(); + foreach (array_keys($valid) as $name) { + try { + self::resolve($name); + } catch (InvalidArgumentException $e) { + $errors[$name] = $e->getMessage(); + } + } + + return $errors; + } + + /** + * 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 + { + // Once the router has run, its answer: a fixed route of the application wins over a server's pattern, and + // a route the application connected itself to the plugin's controller is the default server's. + $params = $request->getAttribute('params'); + if (is_array($params) && isset($params['controller'])) { + $ours = ($params['plugin'] ?? null) === 'CakeDC/Mcp' + && in_array($params['controller'], self::ENDPOINT_CONTROLLERS, true); + if (!$ours) { + return null; + } + $server = $params['server'] ?? null; + $server = is_string($server) && $server !== '' ? $server : self::DEFAULT_SERVER; + + return in_array($server, self::servers(), true) ? $server : null; + } + $path = self::requestPath($request); + foreach (self::servers() as $server) { + $route = self::get('route', $server); + if (!is_string($route) || trim($route, '/') === '') { + continue; + } + $metadata = self::METADATA_PREFIX . '/' . trim($route, '/'); + if (self::routeValues($route, $path) !== null || self::routeValues($metadata, $path) !== null) { + return $server; + } + } + + return null; + } + + /** + * The path of $request as the router matches it, without trailing slashes. The router of CakePHP 5.3.7 and later + * percent-decodes each segment and keeps an encoded slash inside its segment; older ones decode the whole path. + * + * @param \Psr\Http\Message\ServerRequestInterface $request The request. + * @param bool|null $bySegment Whether to decode as the newer router does; null follows the installed one. + * @return string + * @internal + */ + public static function requestPath(ServerRequestInterface $request, ?bool $bySegment = null): string + { + $path = $request instanceof ServerRequest ? $request->getPath() : $request->getUri()->getPath(); + if (str_contains($path, '%')) { + $bySegment ??= function_exists('Cake\Routing\urldecodeSegments'); + $path = !$bySegment ? urldecode($path) : implode('/', array_map( + fn(string $part): string => str_replace('/', '%2f', urldecode($part)), + explode('/', $path), + )); + } + + return '/' . trim($path, '/'); + } + + /** + * The parameters of a route such as `/mcp/{tenant}`, in order. + * + * @param mixed $route A route. + * @return list + */ + public static function routeParams(mixed $route): array + { + if (!is_string($route)) { + return []; + } + preg_match_all('/\{([A-Za-z_][A-Za-z0-9_]*)\}/', $route, $matches); + + return $matches[1]; + } + + /** + * The parameters of $server's route that its `auth.resource` puts in its host + * (`https://{tenant}.example.com/mcp`). The resource's host is lowercased, so such a value is served only in + * lowercase: `ACME` would share `acme`'s resource and audience while the tools got `ACME`. + * + * @param string $server The server. + * @return list + */ + public static function hostRouteParams(string $server): array + { + try { + $auth = self::get('auth', $server); + } catch (InvalidArgumentException) { + return []; + } + $resource = is_array($auth) ? ($auth['resource'] ?? null) : null; + if (!is_string($resource) || preg_match('#^[A-Za-z][A-Za-z0-9+.-]*://([^/?\#]*)#', $resource, $match) !== 1) { + return []; + } + + $params = self::routeParams(self::get('route', $server)); + + return array_values(array_intersect(self::routeParams($match[1]), $params)); + } + + /** + * What is wrong with the parameters of a named server's route, or null. A parameter is a whole path segment, + * `{name}` with a name of letters, digits and `_`, each name once; its values are slugs (letters, digits, `-` + * and `_`). + * + * @param string $route The route. + * @return string|null + */ + public static function routeError(string $route): ?string + { + $names = []; + foreach (explode('/', trim($route, '/')) as $segment) { + if (!str_contains($segment, '{') && !str_contains($segment, '}')) { + continue; + } + if (preg_match('/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/', $segment, $match) !== 1) { + return sprintf( + 'the segment "%s" is not a parameter: write a whole segment as {name}, with letters, digits ' + . 'and "_"', + $segment, + ); + } + if (in_array($match[1], $names, true)) { + return sprintf('the parameter {%s} is there twice', $match[1]); + } + // Cake would put the value in that routing key, so a request could pick another server or controller. + if (in_array($match[1], self::RESERVED_PARAMS, true) || str_starts_with($match[1], '_')) { + return sprintf('{%s} is a name Cake routing uses: name the parameter otherwise', $match[1]); + } + $names[] = $match[1]; + } + + return null; + } + + /** + * The values of $route's parameters in $path, or null when $path is not that route. + * + * @param string $route A route, maybe with parameters. + * @param string $path A request path. + * @return array|null + */ + public static function routeValues(string $route, string $path): ?array + { + $route = '/' . trim($route, '/'); + $path = '/' . trim($path, '/'); + $params = self::routeParams($route); + if ($params === []) { + return $route === $path ? [] : null; + } + $segments = []; + foreach (explode('/', trim($route, '/')) as $segment) { + $segments[] = preg_match('/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/', $segment, $param) === 1 + ? '(?P<' . $param[1] . '>' . self::ROUTE_VALUE . ')' + : preg_quote($segment, '#'); + } + $regex = '#^/' . implode('/', $segments) . '$#D'; + if (preg_match($regex, $path, $match) !== 1) { + return null; + } + $values = []; + foreach ($params as $name) { + $values[$name] = (string)$match[$name]; + } + + return $values; + } + + /** + * $template (a route, a resource URL, an audience) with its `{name}` parameters replaced by $values. + * + * @param string $template The template. + * @param array $values Parameter name => value. + * @return string + */ + public static function withRouteValues(string $template, array $values): string + { + $pairs = []; + foreach ($values as $name => $value) { + $pairs['{' . $name . '}'] = $value; + } + + return strtr($template, $pairs); + } + + /** + * @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; + } + + [$valid, $errors] = self::named(); + if (isset($errors[$server])) { + throw new InvalidArgumentException($errors[$server]); + } + $named = $valid[$server] ?? null; + if ($named === null) { + throw new InvalidArgumentException(sprintf('"Mcp.servers.%s" is not configured.', $server)); + } + $config = $default; + unset($named['servers']); + // A typo in a section name would be ignored, and the server would run with what it meant to replace. + foreach (array_keys($named) as $key) { + if (!array_key_exists($key, self::DEFAULTS)) { + throw new InvalidArgumentException(sprintf( + '"Mcp.servers.%s.%s" is not a server setting; the settings are %s.', + $server, + $key, + implode(', ', array_keys(self::DEFAULTS)), + )); + } + } + if (!array_key_exists('auth', $named)) { + // A server with no HTTP route (served over stdio only) takes no tokens: nothing to inherit. + $config['auth'] = $named['route'] === false + ? self::DEFAULTS['auth'] + : self::inheritedAuth($config['auth'], $default['route'], (string)$named['route'], $server); + } + if (!array_key_exists('identity', $named)) { + // Never the default server's: a public default server must not make a named one public. + $config['identity'] = self::DEFAULTS['identity']; + } + foreach (self::REPLACED_SECTIONS as $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 %s.', + $server, + $section, + $section === 'identity' + ? "the plugin's default (an identity is required)" + : "the default server's", + )); + } + self::assertSectionKeys($server, $section, $named[$section]); + $config[$section] = self::merge(self::DEFAULTS[$section], $named[$section]); + unset($named[$section]); + } + // Replaced, not merged: `[]` or `null` must drop the default server's hook and cache hints. + foreach (['configure', 'cache'] as $key) { + if (is_array($named['server'] ?? null) && array_key_exists($key, $named['server'])) { + $config['server'][$key] = $named['server'][$key] === [] ? null : $named['server'][$key]; + unset($named['server'][$key]); + } + } + + $config = self::merge($config, $named); + self::assertBindsRouteValues($server, $config); + + return $config; + } + + /** + * On a route with parameters, a token is bound to one value only when what it is checked against, a configured + * `auth.resource` or external `audience`, holds every parameter. Without one the endpoint would accept a token + * for `/mcp/acme` on `/mcp/globex`: fail closed. Host mode checks no token, and a resource or audience left out + * is derived from the request, so neither is refused (`bin/cake mcp check` warns about host mode). + * + * @param string $server The named server. + * @param array $config Its resolved config. + * @return void + * @throws \InvalidArgumentException When a configured resource or audience leaves a parameter out. + */ + private static function assertBindsRouteValues(string $server, array $config): void + { + $params = self::routeParams($config['route'] ?? null); + $auth = is_array($config['auth'] ?? null) ? $config['auth'] : []; + $mode = $auth['mode'] ?? null; + if ($params === [] || $mode === null || $mode === 'host') { + return; + } + $bound = []; + if (is_string($auth['resource'] ?? null) && $auth['resource'] !== '') { + $bound['auth.resource'] = [$auth['resource']]; + } + $external = is_array($auth['external'] ?? null) ? $auth['external'] : []; + if ($mode === 'external' && ($external['audience'] ?? null) !== null) { + $bound['auth.external.audience'] = array_filter((array)$external['audience'], 'is_string'); + } + foreach ($bound as $key => $values) { + foreach ($values as $value) { + $missing = array_values(array_diff($params, self::routeParams($value))); + if ($missing === []) { + self::assertParamsApart($server, $key, $value); + continue; + } + throw new InvalidArgumentException(sprintf( + '"Mcp.servers.%s.%s" is "%s", which has no {%s}: a token for one value of %s would be accepted ' + . 'for another. Put {%s} in it, or leave auth.resource and external.audience out to derive them ' + . 'from the request.', + $server, + $key, + $value, + $missing[0], + $missing[0], + implode('}, {', $missing), + )); + } + } + } + + /** + * Two parameters of a bound value must be kept apart by a character a value cannot hold (`/`, `.`, `:`): with + * `{org}-{team}`, the values (`x-y`, `z`) and (`x`, `y-z`) give the same resource or audience, so a token for + * one would be accepted for the other. + * + * @param string $server The named server. + * @param string $key The setting, for the message. + * @param string $value Its value. + * @return void + * @throws \InvalidArgumentException + */ + private static function assertParamsApart(string $server, string $key, string $value): void + { + $parts = preg_split('/(\{[^}\/]+\})/', $value, -1, PREG_SPLIT_DELIM_CAPTURE) ?: []; + // Odd indexes are the placeholders; the even one between two of them is what separates them. + $count = count($parts); + for ($i = 3; $i < $count; $i += 2) { + if (preg_match('/^' . self::ROUTE_VALUE . '$/', $parts[$i - 1]) === 1 || $parts[$i - 1] === '') { + throw new InvalidArgumentException(sprintf( + '"Mcp.servers.%s.%s" is "%s", with nothing between %s and %s that a value cannot hold: two ' + . 'pairs of values would give the same %s. Separate them with "/", "." or ":".', + $server, + $key, + $value, + $parts[$i - 2], + $parts[$i], + $key === 'auth.resource' ? 'resource' : 'audience', + )); + } + } + } + + /** + * A replaced section starts again from the plugin's defaults, which are the permissive ones: the key that + * decides how open the server is must be written, and an unknown key (a typo) fails. + * + * @param string $server The named server. + * @param string $section A key of REPLACED_SECTIONS. + * @param array $values What the named server wrote for it. + * @return void + * @throws \InvalidArgumentException + */ + private static function assertSectionKeys(string $server, string $section, array $values): void + { + $required = ['auth' => 'mode', 'authorization' => 'authorizer'][$section] ?? null; + if ($required !== null && !array_key_exists($required, $values)) { + throw new InvalidArgumentException(sprintf( + '"Mcp.servers.%s.%s.%s" must be set: a named server\'s "%s" starts again from the plugin\'s ' + . 'defaults, so without it the server would use the default %s.', + $server, + $section, + $required, + $section, + $section === 'auth' ? 'host mode, where tokens and scopes are not checked' : 'AllowAllToolAuthorizer', + )); + } + if ($section === 'auth') { + // `auth` is checked key by key when the endpoint reads it. + return; + } + // A typo would leave the plugin's default: for `discovery`, src/Mcp, the default server's tools. + $defaults = self::DEFAULTS[$section] ?? null; + if (!is_array($defaults)) { + return; + } + foreach (array_keys($values) as $key) { + if (!array_key_exists($key, $defaults)) { + throw new InvalidArgumentException(sprintf( + '"Mcp.servers.%s.%s.%s" is not a setting of "%s"; the settings are %s.', + $server, + $section, + $key, + $section, + implode(', ', array_keys($defaults)), + )); + } + } + } + + /** + * The default server's `auth` as a named server that does not write its own inherits it: with its own + * resource, so neither server accepts the other's tokens. + * + * @param mixed $auth The default server's resolved `auth`. + * @param mixed $defaultRoute The default server's route. + * @param string $route The named server's route. + * @param string $server The named server. + * @return mixed + * @throws \InvalidArgumentException When the inherited auth names an external audience, which cannot be + * derived for another server. + */ + private static function inheritedAuth(mixed $auth, mixed $defaultRoute, string $route, string $server): mixed + { + if (!is_array($auth)) { + return $auth; + } + $audience = is_array($auth['external'] ?? null) ? $auth['external']['audience'] ?? null : null; + if (($auth['mode'] ?? null) === 'external' && $audience !== null) { + throw new InvalidArgumentException(sprintf( + '"Mcp.servers.%s.auth" must be set: the default server\'s "Mcp.auth.external.audience" cannot be ' + . 'shared, or this server would accept the default server\'s tokens. Give it its own "auth" with ' + . 'its own audience.', + $server, + )); + } + if (is_string($auth['resource'] ?? null) && $auth['resource'] !== '') { + $auth['resource'] = self::resourceAt($auth['resource'], $defaultRoute, $route); + } + + return $auth; + } + + /** + * $resource with its path moved from the default server's route to $route. A path prefix before the default + * route (a proxy's, say) stays; a path that does not end with the default route is replaced whole. + * + * @param string $resource The default server's `auth.resource`. + * @param mixed $defaultRoute The default server's route. + * @param string $route The named server's route. + * @return string + */ + private static function resourceAt(string $resource, mixed $defaultRoute, string $route): string + { + $parts = parse_url($resource); + if ( + $parts === false || !isset($parts['scheme'], $parts['host']) + || isset($parts['user']) || isset($parts['pass']) || isset($parts['fragment']) + ) { + // Left as written: the endpoint refuses it with the same message as the default server's. + return $resource; + } + $path = rtrim($parts['path'] ?? '', '/'); + $prefix = ''; + if (is_string($defaultRoute) && trim($defaultRoute, '/') !== '') { + $defaultPath = '/' . trim($defaultRoute, '/'); + if (str_ends_with($path, $defaultPath)) { + $prefix = substr($path, 0, -strlen($defaultPath)); + } + } + + return $parts['scheme'] . '://' . $parts['host'] . (isset($parts['port']) ? ':' . $parts['port'] : '') + . $prefix . '/' . trim($route, '/'); + } + + /** + * The entries of `Mcp.servers` whose shape is valid, and the others with what is wrong with them. One wrong + * entry never hides the valid ones. + * + * @return array{0: array>, 1: array} + */ + private static function named(): array + { + $servers = Configure::read('Mcp.servers') ?? []; + if (!is_array($servers)) { + return [[], ['Mcp.servers' => '"Mcp.servers" must be an array of server name => config.']]; + } + $valid = []; + $errors = []; + foreach ($servers as $name => $config) { + if (is_int($name)) { + // PHP keeps a numeric key an int: a list written by mistake, or a name like "2024". + $errors['Mcp.servers.' . $name] = sprintf( + '"Mcp.servers.%d": a server name must be a word, not a number; "Mcp.servers" is an array of ' + . 'server name => config, not a list.', + $name, + ); + continue; + } + if (!is_array($config)) { + $errors[$name] = sprintf( + '"Mcp.servers.%s" must be the config array of the server; "Mcp.servers" is an array of server ' + . 'name => config.', + $name, + ); + } elseif (preg_match('/^[A-Za-z0-9_-]+$/', $name) !== 1) { + $errors[$name] = sprintf( + 'The server name "%s" in "Mcp.servers" may only have letters, digits, "-" and "_".', + $name, + ); + } elseif ($name === self::DEFAULT_SERVER) { + $errors[$name] = '"Mcp.servers.default" is not allowed: the top-level "Mcp" config is the default ' + . 'server.'; + } elseif ( + ($config['route'] ?? null) !== false + && (!is_string($config['route'] ?? null) || trim($config['route'], '/') === '') + ) { + $errors[$name] = sprintf( + '"Mcp.servers.%s.route" must be the path of the server, for example "/mcp/%s", or false for a ' + . 'server served over stdio only.', + $name, + $name, + ); + } elseif (is_string($config['route']) && self::routeError($config['route']) !== null) { + $errors[$name] = sprintf( + '"Mcp.servers.%s.route": %s.', + $name, + (string)self::routeError($config['route']), + ); + } else { + $valid[$name] = $config; + } + } + + /** @var array> $valid */ + return [$valid, $errors]; + } + /** * 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; } @@ -104,12 +718,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).'); } @@ -122,11 +737,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)); } @@ -177,11 +793,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, and a third lets anyone fetch its Client ID Metadata Document (`client.json`). + * * @return list> */ public static function rbacPermissions(): array { - return [ + $rules = [ [ 'role' => '*', 'plugin' => 'CakeDC/Mcp', @@ -190,10 +809,29 @@ 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'], + ]; + // Their Client ID Metadata Document, which authorization servers fetch without a session. + $rules[] = [ + 'role' => '*', + 'plugin' => 'CakeDC/Mcp', + 'controller' => ['McpClient'], + 'action' => ['metadata'], + 'bypassAuth' => true, + ]; + } + + return $rules; } /** - * 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. @@ -201,14 +839,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/src/McpPlugin.php b/src/McpPlugin.php index 5d024e9..183d21c 100644 --- a/src/McpPlugin.php +++ b/src/McpPlugin.php @@ -10,11 +10,14 @@ 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; use CakeDC\Mcp\Identity\CurrentIdentity; +use CakeDC\Mcp\Log\ConfigMistakes; use CakeDC\Mcp\OAuth\AuthSettings; +use CakeDC\Mcp\Server\McpRoute; use CakeDC\Mcp\Server\ServerFactory; /** @@ -33,10 +36,26 @@ 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'); + // A mistake in one entry stops that entry only: it is logged, its routes are not connected and + // `bin/cake mcp check` fails on it, while the rest of the application keeps working. + foreach (McpConfig::serverErrors() as $name => $error) { + // An entry named `default` is ignored: the top-level config still serves the default server. + ConfigMistakes::log($name === McpConfig::DEFAULT_SERVER + ? sprintf('"Mcp.servers.default" is ignored: %s', $error) + : sprintf('MCP server "%s" is not served: %s', $name, $error)); + } + foreach (ClientConfig::errors() as $name => $error) { + ConfigMistakes::log(sprintf('MCP client "%s" is not usable: %s', $name, $error)); + } + + $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 +79,43 @@ public function bootstrap(PluginApplicationInterface $app): void */ public function routes(RouteBuilder $routes): void { - $path = McpConfig::get('route'); - if (!is_string($path) || $path === '') { - return; + // 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; + } + // 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]; + // A route such as /mcp/{tenant}: each parameter is one path segment, a slug. + $patterns = array_fill_keys(McpConfig::routeParams($path), McpConfig::ROUTE_VALUE); + $routes->connect( + $path, + ['plugin' => 'CakeDC/Mcp', 'controller' => 'Mcp', 'action' => 'handle'] + $param, + )->setMethods(['GET', 'POST', 'DELETE', 'OPTIONS'])->setPatterns($patterns); + // 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'])->setPatterns($patterns); } - $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']); + // The sign-in of user mode clients (Mcp.clients with `auth` `user`), only when one is configured. + // Never at the site's root: a route that is not a path is a logged mistake, and `mcp check` fails on it. + if (ClientConfig::anyUserMode() && ClientConfig::routeError() === null) { + $base = '/' . trim((string)ClientConfig::setting('route'), '/'); + // The Client ID Metadata Document (client.json), which authorization servers fetch. + $actions = ['connect' => 'connect', 'callback' => 'callback', 'client.json' => 'metadata']; + foreach ($actions as $path => $action) { + $routes->connect( + $base . '/{client}/' . $path, + ['plugin' => 'CakeDC/Mcp', 'controller' => 'McpClient', 'action' => $action], + )->setPass(['client'])->setPatterns(['client' => '[A-Za-z0-9_-]+'])->setMethods(['GET']); + } + } } /** @@ -97,6 +139,7 @@ public function console(CommandCollection $commands): CommandCollection public function services(ContainerInterface $container): void { $container->addShared(CurrentIdentity::class); + $container->addShared(McpRoute::class); $container->addShared(ServerFactory::class) ->addArgument($container) ->addArgument(CurrentIdentity::class); diff --git a/src/Middleware/AuditRefusalMiddleware.php b/src/Middleware/AuditRefusalMiddleware.php index 9b39847..594fb3c 100644 --- a/src/Middleware/AuditRefusalMiddleware.php +++ b/src/Middleware/AuditRefusalMiddleware.php @@ -7,6 +7,7 @@ use CakeDC\Mcp\Audit\AuditSettings; use CakeDC\Mcp\Audit\AuditWriter; use CakeDC\Mcp\Identity\CurrentIdentity; +use Closure; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; @@ -25,11 +26,13 @@ final class AuditRefusalMiddleware implements MiddlewareInterface * @param \CakeDC\Mcp\Audit\AuditSettings $settings The audit settings. * @param \CakeDC\Mcp\Audit\AuditWriter $writer Writes the records. * @param \CakeDC\Mcp\Identity\CurrentIdentity $identity The token owner, set by authentication. + * @param \Closure(string): bool|null $appOnly Whether a tool is app-only, so its records carry `app=1`. */ public function __construct( private readonly AuditSettings $settings, private readonly AuditWriter $writer, private readonly CurrentIdentity $identity, + private readonly ?Closure $appOnly = null, ) { } @@ -68,6 +71,8 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface $message['method'] === 'resources/read' ? [] : $this->writer->arguments($params['arguments'] ?? null), $outcome === AuditRecord::UNAUTHORIZED ? 'Unauthorized' : 'insufficient_scope', null, + app: $message['method'] === 'tools/call' && is_string($name) && $this->appOnly !== null + && ($this->appOnly)($name), )); return $response; 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/Middleware/HeaderEncodingMiddleware.php b/src/Middleware/HeaderEncodingMiddleware.php new file mode 100644 index 0000000..7546ab0 --- /dev/null +++ b/src/Middleware/HeaderEncodingMiddleware.php @@ -0,0 +1,67 @@ +getHeaders() as $name => $values) { + $name = (string)$name; + if (strncasecmp($name, 'mcp-', 4) !== 0) { + continue; + } + foreach ($values as $value) { + if (!mb_check_encoding($value, 'UTF-8')) { + return $this->badRequest($name); + } + } + } + + return $handler->handle($request); + } + + /** + * @param string $header The header. + * @return \Psr\Http\Message\ResponseInterface + */ + private function badRequest(string $header): ResponseInterface + { + return $this->responseFactory->createResponse(400) + ->withHeader('Content-Type', 'application/json') + ->withBody($this->streamFactory->createStream((string)json_encode([ + 'jsonrpc' => '2.0', + 'id' => null, + 'error' => [ + 'code' => -32600, + 'message' => sprintf('Invalid Request: the %s header is not valid UTF-8.', $header), + ], + ]))); + } +} 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/src/OAuth/AuthSettings.php b/src/OAuth/AuthSettings.php index 3129996..6d703cc 100644 --- a/src/OAuth/AuthSettings.php +++ b/src/OAuth/AuthSettings.php @@ -43,18 +43,48 @@ 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. + * @param array $route The values of the parameters of its route in this request + * (`/mcp/{tenant}`): the resource and a configured audience are those of that value. * @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, array $route = []): self { - $auth = McpConfig::get('auth'); + try { + return self::read($server, $route); + } catch (InvalidArgumentException $e) { + if ($server === McpConfig::DEFAULT_SERVER) { + throw $e; + } + // The messages name the top-level setting: name the server's own, or say that it inherits it. + $own = Configure::check(sprintf('Mcp.servers.%s.auth', $server)); + throw new InvalidArgumentException( + $own + ? str_replace('"Mcp.auth', sprintf('"Mcp.servers.%s.auth', $server), $e->getMessage()) + : sprintf('%s (server %s inherits it)', $e->getMessage(), $server), + 0, + $e, + ); + } + } + + /** + * @param string $server The MCP server whose settings to read. + * @param array $route The values of the parameters of its route in this request. + * @return self + * @throws \InvalidArgumentException For an invalid setting, named as the top-level one. + */ + private static function read(string $server, array $route): self + { + $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 +115,18 @@ 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, $route); + // On a route such as /mcp/{tenant}, each value is its own resource: so is a configured audience. + if ($route !== [] && is_string($external['audience'] ?? null)) { + $external['audience'] = McpConfig::withRouteValues($external['audience'], $route); + } elseif ($route !== [] && is_array($external['audience'] ?? null)) { + $external['audience'] = array_map( + fn(mixed $audience): mixed => is_string($audience) + ? McpConfig::withRouteValues($audience, $route) + : $audience, + $external['audience'], + ); + } return new self( $mode, @@ -98,6 +139,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,24 +223,26 @@ 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. + * @param array $values The values of the route's parameters. * @return string */ - private static function resource(mixed $configured): string + private static function resource(mixed $configured, string $server, array $values = []): string { if ($configured !== null) { if (!is_string($configured)) { throw new InvalidArgumentException('"Mcp.auth.resource" must be a URL or null.'); } - return self::canonicalUrl($configured, '"Mcp.auth.resource"'); + return self::canonicalUrl(McpConfig::withRouteValues($configured, $values), '"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'), '/') . (is_string($base) ? rtrim($base, '/') : '') - . (is_string($route) ? $route : ''), + . (is_string($route) ? McpConfig::withRouteValues($route, $values) : ''), '"Mcp.auth.resource" (derived from App.fullBaseUrl, App.base and Mcp.route)', ); } diff --git a/src/OAuth/ResourceServer.php b/src/OAuth/ResourceServer.php index a990d71..1064434 100644 --- a/src/OAuth/ResourceServer.php +++ b/src/OAuth/ResourceServer.php @@ -209,7 +209,7 @@ private function authorizationServer(): AuthorizationServer $resources = $server->config()->resources; $declared = $resources->get($this->settings->resource); if ($declared === null) { - throw new RuntimeException(sprintf( + throw new UndeclaredResourceException(sprintf( 'The MCP resource "%s" (Mcp.auth.resource) is not declared in OAuthServer.resources (declared: %s).', $this->settings->resource, implode(', ', array_map( diff --git a/src/OAuth/UndeclaredResourceException.php b/src/OAuth/UndeclaredResourceException.php new file mode 100644 index 0000000..b52be6f --- /dev/null +++ b/src/OAuth/UndeclaredResourceException.php @@ -0,0 +1,14 @@ + $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'] : []; + + return self::walk($schema, ''); + } + + /** + * The problems of the properties of $schema, and of the objects nested in them (`filter.date_from`) or in + * their items (`rows[].tags`). + * + * @param array $schema An object schema. + * @param string $prefix The path of $schema, ending with `.`, or `` for the input schema. + * @return list + */ + private static function walk(array $schema, string $prefix): array + { + $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; + } + $path = $prefix . $name; + $type = $property['type'] ?? null; + if (is_array($type)) { + $problems[] = sprintf('%s: type union %s', $path, implode('|', array_map('strval', $type))); + } + if ($type === 'array' && ($property['items'] ?? []) === []) { + $problems[] = sprintf('%s: array without item type', $path); + } + $description = $property['description'] ?? null; + if (!in_array($name, $required, true) && (!is_string($description) || trim($description) === '')) { + $problems[] = sprintf('%s: optional without a description', $path); + } + $problems = [...$problems, ...self::walk($property, $path . '.')]; + if (is_array($property['items'] ?? null)) { + $problems = [...$problems, ...self::walk($property['items'], $path . '[].')]; + } + } + + return $problems; + } +} diff --git a/src/Schema/SchemaNormalizer.php b/src/Schema/SchemaNormalizer.php new file mode 100644 index 0000000..a408e6d --- /dev/null +++ b/src/Schema/SchemaNormalizer.php @@ -0,0 +1,68 @@ + $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)) { + continue; + } + // The objects nested in a property, or in its items, follow the same rule with their own `required`. + $property = self::normalize($property); + if (is_array($property['items'] ?? null)) { + $property['items'] = self::normalize($property['items']); + } + if (!in_array($name, $required, true) && ($property['default'] ?? null) === null) { + $property = self::optional($property); + } + $properties[$name] = $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 $v): bool => $v !== null)); + } + if (array_key_exists('default', $property) && $property['default'] === null) { + unset($property['default']); + } + + return $property; + } +} diff --git a/src/Server/CacheHints.php b/src/Server/CacheHints.php new file mode 100644 index 0000000..e57fa8a --- /dev/null +++ b/src/Server/CacheHints.php @@ -0,0 +1,97 @@ + 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 + { + // Both mean "no hints": a named server writes one of them to drop the default server's. + if ($config === null || $config === []) { + 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; + } + + /** + * $policy with `tools/list` private: an authorizer can give each user different tools, so a shared cache must + * never serve one user's list to another. + * + * @param \Mcp\Server\Wire\CachePolicy $policy The policy. + * @return \Mcp\Server\Wire\CachePolicy + */ + public static function privateToolList(CachePolicy $policy): CachePolicy + { + return self::private($policy, ['tools/list']); + } + + /** + * $policy with $methods private, keeping their ttl: results an authorizer filters per caller. + * + * @param \Mcp\Server\Wire\CachePolicy $policy The policy. + * @param list $methods The methods. + * @return \Mcp\Server\Wire\CachePolicy + */ + public static function private(CachePolicy $policy, array $methods): CachePolicy + { + foreach ($methods as $method) { + if ($policy->scopeFor($method) === CacheScope::Public) { + $policy = $policy->withMethod($method, $policy->ttlFor($method), CacheScope::Private); + } + } + + 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/src/Server/Conditions.php b/src/Server/Conditions.php new file mode 100644 index 0000000..3e7e125 --- /dev/null +++ b/src/Server/Conditions.php @@ -0,0 +1,101 @@ + What was removed: ` ()`. + * @throws \InvalidArgumentException When a condition cannot be evaluated; the message names the element. + */ + public static function prune(RegistryInterface $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]) { + // Keyed by the element's own name or URI: a registry of the hook's own may return its pages as lists. + $references = []; + foreach ($page->references as $key => $element) { + $references[self::key($element, $key)] = $element; + } + // 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; + // The method's condition adds to its class's: every one must hold. + foreach (HandlerAttributes::all($get($key), McpWhen::class) as $condition) { + 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()); + break; + } + } + } + } + + return $skipped; + } + + /** + * The name of a tool or prompt, the URI of a resource or the URI template of a template. + * + * @internal + * @param mixed $element A definition from a registry page. + * @param string|int $key Its key in the page, used when the definition has none of these. + * @return string + */ + public static function key(mixed $element, int|string $key): string + { + return match (true) { + $element instanceof Tool, $element instanceof Prompt => $element->name, + $element instanceof ResourceDefinition => $element->uri, + $element instanceof ResourceTemplate => $element->uriTemplate, + default => (string)$key, + }; + } + + /** + * @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/HandlerAttributes.php b/src/Server/HandlerAttributes.php new file mode 100644 index 0000000..55cbfac --- /dev/null +++ b/src/Server/HandlerAttributes.php @@ -0,0 +1,63 @@ + $class The attribute class. + * @return list + */ + public static function all(ElementReference $reference, string $class): array + { + $handler = $reference->handler; + if (is_string($handler) && class_exists($handler)) { + $handler = [$handler, '__invoke']; + } + if (!is_array($handler)) { + return []; + } + $owner = is_object($handler[0]) ? $handler[0]::class : $handler[0]; + if (!class_exists($owner)) { + return []; + } + try { + $attributes = [ + ...(new ReflectionMethod($owner, $handler[1]))->getAttributes($class), + ...(new ReflectionClass($owner))->getAttributes($class), + ]; + } catch (ReflectionException) { + return []; + } + + return array_map(fn(ReflectionAttribute $attribute): object => $attribute->newInstance(), $attributes); + } + + /** + * The first `$class` attribute of an element's handler: on the method first, then on its class (an invokable + * class). Closures registered in code have none. + * + * @template T of object + * @param \Mcp\Capability\Registry\ElementReference $reference The element. + * @param class-string $class The attribute class. + * @return T|null + */ + public static function first(ElementReference $reference, string $class): ?object + { + return self::all($reference, $class)[0] ?? null; + } +} diff --git a/src/Server/McpRoute.php b/src/Server/McpRoute.php new file mode 100644 index 0000000..e973e37 --- /dev/null +++ b/src/Server/McpRoute.php @@ -0,0 +1,43 @@ +getParam('tenant')`). Empty for a route without + * parameters, and over stdio. + */ +final class McpRoute +{ + /** + * @var array + */ + private array $values = []; + + /** + * @param array $values Parameter name => value. + * @return void + */ + public function set(array $values): void + { + $this->values = $values; + } + + /** + * @return array Parameter name => value. + */ + public function values(): array + { + return $this->values; + } + + /** + * @param string $name A parameter of the route. + * @return string|null Its value in this request, or null. + */ + public function get(string $name): ?string + { + return $this->values[$name] ?? null; + } +} diff --git a/src/Server/ServerFactory.php b/src/Server/ServerFactory.php index 0d83df6..ae31593 100644 --- a/src/Server/ServerFactory.php +++ b/src/Server/ServerFactory.php @@ -4,33 +4,62 @@ 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\AllowAllToolAuthorizer; +use CakeDC\Mcp\Authorization\ContentGate; +use CakeDC\Mcp\Authorization\ContentGuard; +use CakeDC\Mcp\Authorization\ContentNotificationBus; use CakeDC\Mcp\Authorization\RbacToolAuthorizer; use CakeDC\Mcp\Authorization\ToolAuthorizerInterface; use CakeDC\Mcp\Authorization\ToolCallGuard; use CakeDC\Mcp\Authorization\ToolGate; +use CakeDC\Mcp\Catalog\ToolCatalog; use CakeDC\Mcp\Container\ContainerBridge; +use CakeDC\Mcp\Event\AppToolFilter; use CakeDC\Mcp\Event\AuditListener; +use CakeDC\Mcp\Event\ContentListFilter; 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; +use CakeDC\Mcp\OAuth\AuthSettings; +use CakeDC\Mcp\Schema\SchemaNormalizer; use CakeDC\Mcp\TestSuite\RecordingTransport; use InvalidArgumentException; +use Mcp\Capability\Discovery\CachedDiscoverer; +use Mcp\Capability\Discovery\Discoverer; use Mcp\Capability\Registry; +use Mcp\Capability\Registry\ReferenceHandler; +use Mcp\Capability\Registry\ResourceTemplateReference; +use Mcp\Capability\RegistryInterface; use Mcp\Event\ErrorEvent; use Mcp\Event\RequestEvent; use Mcp\Event\ResponseEvent; +use Mcp\Exception\ResourceNotFoundException; use Mcp\Schema\Enum\ProtocolVersion; +use Mcp\Schema\Extension\Apps\McpApps; +use Mcp\Schema\Icon; +use Mcp\Schema\JsonRpc\Request; +use Mcp\Schema\Request\GetPromptRequest; +use Mcp\Schema\Request\ReadResourceRequest; +use Mcp\Schema\Tool; +use Mcp\Schema\ToolAnnotations; use Mcp\Server; use Mcp\Server\Builder; use Mcp\Server\Session\Psr16SessionStore; +use Mcp\Server\Subscription\NotificationBusInterface; +use Mcp\Server\Transport\Http\OAuth\ScopePolicy; +use Mcp\Server\Wire\CachePolicy; use Psr\Container\ContainerInterface; use Psr\Log\AbstractLogger; use Psr\Log\LoggerInterface; use Psr\Log\LogLevel; +use Psr\Log\NullLogger; +use ReflectionProperty; use RuntimeException; use stdClass; use Stringable; @@ -42,16 +71,67 @@ */ final class ServerFactory { + /** + * What #[McpWhen] removed in the last build. + * + * @var list + */ + private array $skipped = []; + + /** + * The registry of the last build. + */ + private ?RegistryInterface $lastRegistry = null; + + /** + * Whether the last build announced the MCP Apps extension (from `Mcp.apps.enabled` or the host hook). + */ + private bool $appsAnnounced = false; + + /** + * The cache policy the config or the hook set, before `tools/list` is forced private. + */ + private ?CachePolicy $cachePolicy = null; + + /** + * The route values when the container has no McpRoute (a container without the plugin's services). + */ + private ?McpRoute $route = null; + /** * @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 */ @@ -76,65 +156,211 @@ 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. + $authorizer = $this->authorizer(); + $gate = new ToolGate( + $authorizer, + $this->identity, + $trusted, + $catalogOn ? [ToolCatalog::FIND, ToolCatalog::CALL] : [], + ); $events = new EventDispatcher(); - $events->listen(ResponseEvent::class, new ToolListFilter($gate)); - // The guard goes first: the SDK asks request handlers in the order they were added. + /** @var \CakeDC\Mcp\Catalog\ToolCatalog|null $toolCatalog Set after the host hook. */ + $toolCatalog = null; + // The catalog's own rule, so tools/list hides exactly what find_tools and call_tools offer. + $events->listen(ResponseEvent::class, new ToolListFilter( + $gate, + $catalogOn ? function (string $tool) use (&$toolCatalog): bool { + return $toolCatalog?->has($tool) ?? false; + } : null, + // The registry of the build: a page the filter empties is filled from the next ones. + fn(): ?RegistryInterface => $this->lastRegistry, + )); + if (McpConfig::get('schema.normalize', $this->server) === true) { + // After the filter, on the tools the caller may see. + $events->listen(ResponseEvent::class, new ToolSchemaNormalizer()); + } + $appsOn = McpConfig::get('apps.enabled', $this->server) === true; + if ($appsOn) { + // Clients that do not render apps never get app-only tools listed. Only with Mcp.apps on: a 2.1 + // application that wrote `visibility: ["app"]` itself keeps its tools/list. + $events->listen(ResponseEvent::class, new AppToolFilter()); + } + // Denied resources and prompts, when the authorizer decides for them. + // 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); + // A concrete URI is also checked against the template that serves it, found in the registry the server + // ends up with (by reference: the host hook may still replace it). + $contentGate = new ContentGate( + $authorizer, + $this->identity, + $trusted, + function (string $uri) use (&$registry): ?string { + try { + $reference = $registry->getResource($uri); + } catch (ResourceNotFoundException) { + return null; + } + + return $reference instanceof ResourceTemplateReference + ? $reference->resourceTemplate->uriTemplate + : null; + }, + ); + if ($contentGate->active()) { + $events->listen(ResponseEvent::class, new ContentListFilter($contentGate)); + } + // The guards go first: the SDK asks request handlers in the order they were added. $builder = Server::builder()->addRequestHandler(new ToolCallGuard($gate)); - $audit = AuditSettings::fromConfig(); + $ownHandlers = 1; + if ($contentGate->active()) { + $builder->addRequestHandler(new ContentGuard($contentGate)); + $ownHandlers++; + } + $builder->setRegistry($registry); + $audit = AuditSettings::fromConfig($this->server, $this->route()->values()); 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), $gate, $this->identity, - toolExists: fn(string $name): ?bool => $registry->hasTools() ? $registry->hasTool($name) : null, + // By reference: the host hook may still replace the registry. + toolExists: function (string $name) use (&$registry): ?bool { + return $registry->hasTools() ? $registry->hasTool($name) : null; + }, + appOnly: function (string $name) use (&$registry): bool { + return $registry->hasTool($name) && AppTools::appOnly($registry->getTool($name)->tool); + }, + via: function (Request $request) use (&$toolCatalog): ?string { + return $toolCatalog?->made($request) ? ToolCatalog::CALL : null; + }, + contentDenied: function (Request $request) use (&$registry, $contentGate): bool { + if ($request instanceof ReadResourceRequest && !$contentGate->allowsRead($request->uri)) { + try { + $registry->getResource($request->uri); + + return true; + } catch (ResourceNotFoundException) { + return false; + } + } + + return $request instanceof GetPromptRequest + && !$contentGate->allowsPrompt($request->name) + && $registry->hasPrompt($request->name); + }, ); $events->listen(RequestEvent::class, $listener->onRequest(...)); $events->listen(ResponseEvent::class, $listener->onResponse(...)); $events->listen(ErrorEvent::class, $listener->onError(...)); } $this->configure($builder); + // After the hook, which sets the bus: a listen stream carries no update of a resource the caller cannot read. + $bus = (new ReflectionProperty(Builder::class, 'notificationBus'))->getValue($builder); + if ($bus instanceof NotificationBusInterface && $contentGate->decidesResources()) { + $builder->setNotificationBus(new ContentNotificationBus($bus, $contentGate)); + } + $extensions = (new ReflectionProperty(Builder::class, 'extensions'))->getValue($builder); + $hookEnabledApps = is_array($extensions) && isset($extensions[McpApps::EXTENSION_ID]); + if ($appsOn && !$hookEnabledApps) { + // After the hook, which may have enabled it already (a 2.1 application serving apps that way). + $builder->enableExtension(new McpApps()); + } + $this->appsAnnounced = $appsOn || $hookEnabledApps; + // The registry the server will use, the plugin's or one the hook set. + $registry = $this->registryOf($builder); + // One bridge for the server and the catalog's inner calls: a tool class the host did not register is one + // object per server, whether it is called by name or through call_tools. + $bridge = new ContainerBridge($this->container); + if ($catalogOn) { + $this->assertCatalogCanRunEverything($builder, $ownHandlers); + $toolCatalog = new ToolCatalog( + $registry, + $gate, + $patterns, + self::positiveInt($catalog['maxCalls'] ?? 5, 'maxCalls'), + new ReferenceHandler($bridge), + $logger, + $this->scopePolicy(), + $events, + McpConfig::get('schema.normalize', $this->server) === true, + self::positiveInt($catalog['maxResultBytes'] ?? ToolCatalog::MAX_RESULT_BYTES, 'maxResultBytes'), + ); + $this->addCatalog($builder, $toolCatalog); + } // 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'), + $this->icons(), websiteUrl: $this->optionalString('server.websiteUrl'), title: $this->optionalString('server.title'), ) - ->setContainer(new ContainerBridge($this->container)) + ->setContainer($bridge) ->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->sessionPrefix(), + (int)McpConfig::get('session.ttl', $this->server), )); - $instructions = McpConfig::get('server.instructions'); + $cachePolicy = CacheHints::fromConfig(McpConfig::get('server.cache', $this->server)); + if ($cachePolicy !== null) { + $builder->setCachePolicy($cachePolicy); + } + // Whoever set the policy (the config or the hook), a list filtered per caller is never public. + $policy = (new ReflectionProperty(Builder::class, 'cachePolicy'))->getValue($builder); + $this->cachePolicy = $policy instanceof CachePolicy ? $policy : null; + if ($policy instanceof CachePolicy) { + $private = array_merge( + // Per caller with an authorizer; per client with MCP Apps, which lists app-only tools only to a + // client that renders apps (a shared cache keyed by method and cursor would mix the two lists). + $authorizer instanceof AllowAllToolAuthorizer && !$appsOn ? [] : ['tools/list'], + // A resource or prompt an authorizer filters is never in a shared cache either. + $contentGate->decidesResources() + ? ['resources/list', 'resources/templates/list', 'resources/read'] + : [], + $contentGate->decidesPrompts() ? ['prompts/list'] : [], + ); + $builder->setCachePolicy(CacheHints::private($policy, $private)); + } + + $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)); + $excludeDirs = array_values(array_filter( + (array)McpConfig::get('discovery.excludeDirs', $this->server), + 'is_string', + )); + $cache = McpConfig::discoveryCache($this->server); if ($scanDirs !== []) { - $cache = McpConfig::discoveryCache(); - $builder->setDiscovery( - rtrim(ROOT, DS), - $scanDirs, - array_values(array_filter((array)McpConfig::get('discovery.excludeDirs'), 'is_string')), - $cache !== null ? Cache::pool($cache) : null, - ); + $pool = $cache !== null ? Cache::pool($cache) : null; + $builder->setDiscovery(rtrim(ROOT, DS), $scanDirs, $excludeDirs, $pool); } - return $builder->build(); + $server = $builder->build(); + $this->skipped = Conditions::prune($registry, $this->server); + AppTools::link($registry); + if ($toolCatalog !== null) { + $this->assertCatalogOwnsItsTools($registry, $toolCatalog); + if ($scanDirs !== []) { + $this->assertNoDiscoveredToolTakesTheCatalogsNames($scanDirs, $excludeDirs, $cache); + } + } + $this->lastRegistry = $registry; + + return $server; } /** @@ -146,7 +372,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; } @@ -165,7 +391,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; } @@ -191,7 +417,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 @@ -199,7 +424,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']; @@ -215,18 +454,7 @@ public function toolNames(): 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( @@ -235,7 +463,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; @@ -244,7 +472,376 @@ public function log(mixed $level, string|Stringable $message, array $context = [ } } - return $names; + return $tools; + } + + /** + * The registry the builder holds after the host hook: the plugin's, or any RegistryInterface the hook set. + * + * @param \Mcp\Server\Builder $builder The builder. + * @return \Mcp\Capability\RegistryInterface + */ + private function registryOf(Builder $builder): RegistryInterface + { + $registry = (new ReflectionProperty(Builder::class, 'registry'))->getValue($builder); + assert($registry instanceof RegistryInterface); + + return $registry; + } + + /** + * Inner calls of `call_tools` run through the plugin's gate, scopes, validation and audit, not through request + * handlers, a reference handler or a schema validator the host hook added: refuse the combination. + * + * @param \Mcp\Server\Builder $builder The builder, after the host hook. + * @param int $ownHandlers How many request handlers the plugin added itself, before the hook. + * @return void + * @throws \InvalidArgumentException When the hook added one of them, or a tool named like the catalog's. + */ + private function assertCatalogCanRunEverything(Builder $builder, int $ownHandlers): void + { + $read = fn(string $property): mixed => (new ReflectionProperty(Builder::class, $property))->getValue($builder); + $handlers = $read('requestHandlers'); + $added = []; + if (is_array($handlers) && count($handlers) > $ownHandlers) { + $added[] = 'request handlers'; + } + if ($read('referenceHandler') !== null) { + $added[] = 'a reference handler'; + } + if ($read('schemaValidator') !== null) { + $added[] = 'a schema validator'; + } + if ($added !== []) { + throw new InvalidArgumentException(sprintf( + 'Mcp.server.configure added %s, and with Mcp.catalog on, a tool run by call_tools would not go ' + . 'through it. Turn the catalog off for this server, or do the same in an authorizer.', + implode(' and ', $added), + )); + } + $explicit = array_map( + fn(mixed $tool): mixed => is_array($tool) && $tool['definition'] instanceof Tool + ? ['name' => $tool['definition']->name] + : null, + (array)$read('explicitTools'), + ); + foreach ([...(array)$read('tools'), ...$explicit] as $tool) { + $name = is_array($tool) ? $tool['name'] ?? null : null; + if ($name === ToolCatalog::FIND || $name === ToolCatalog::CALL) { + throw new InvalidArgumentException(sprintf( + '"%s" is the tool catalog\'s own tool: Mcp.server.configure cannot add a tool with that name.', + $name, + )); + } + } + } + + /** + * After the build: the catalog's tools are its own, not a discovered tool with the same name. + * + * @param \Mcp\Capability\RegistryInterface $registry The registry. + * @param \CakeDC\Mcp\Catalog\ToolCatalog $catalog The catalog. + * @return void + * @throws \InvalidArgumentException When another tool took one of the names. + */ + private function assertCatalogOwnsItsTools(RegistryInterface $registry, ToolCatalog $catalog): void + { + foreach ([ToolCatalog::FIND => 'find', ToolCatalog::CALL => 'call'] as $name => $method) { + $handler = $registry->hasTool($name) ? $registry->getTool($name)->handler : null; + if (!is_array($handler) || $handler[0] !== $catalog || $handler[1] !== $method) { + throw new InvalidArgumentException(sprintf( + '"%s" is the tool catalog\'s own tool: rename the tool of this server that has that name.', + $name, + )); + } + } + } + + /** + * The SDK skips a discovered tool whose name is already taken, here by the catalog, with a debug line only: the + * application's tool would vanish when the catalog is turned on. The discovery is read again (from its cache + * when it has one) to say so. + * + * @param list $scanDirs The scanned directories. + * @param list $excludeDirs The excluded directories. + * @param string|null $cache The discovery cache config. + * @return void + * @throws \InvalidArgumentException When a discovered tool has one of the catalog's names. + */ + private function assertNoDiscoveredToolTakesTheCatalogsNames( + array $scanDirs, + array $excludeDirs, + ?string $cache, + ): void { + $discoverer = new Discoverer(new NullLogger()); + if ($cache !== null) { + $discoverer = new CachedDiscoverer($discoverer, Cache::pool($cache), new NullLogger()); + } + $tools = $discoverer->discover(rtrim(ROOT, DS), $scanDirs, $excludeDirs)->getTools(); + foreach ([ToolCatalog::FIND, ToolCatalog::CALL] as $name) { + if (isset($tools[$name])) { + throw new InvalidArgumentException(sprintf( + '"%s" is the tool catalog\'s own tool: rename the discovered tool %s, which the catalog hides ' + . 'while Mcp.catalog.enabled is on.', + $name, + self::handlerName($tools[$name]->handler), + )); + } + } + } + + /** + * @param mixed $handler A tool handler. + * @return string + */ + private static function handlerName(mixed $handler): string + { + if (is_array($handler) && count($handler) === 2 && is_string($handler[1])) { + $class = is_object($handler[0]) ? $handler[0]::class : (string)$handler[0]; + + return $class . '::' . $handler[1] . '()'; + } + + return is_string($handler) ? $handler : get_debug_type($handler); + } + + /** + * 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], + ); + } + + /** + * @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.`: an integer, or a string of digits as env() gives. + * @param string $key `maxCalls` or `maxResultBytes`. + * @return int + * @throws \InvalidArgumentException When it is not a positive integer. + */ + private static function positiveInt(mixed $value, string $key): int + { + // A string of digits too: what env() gives. + if (is_string($value) && ctype_digit($value)) { + $value = (int)$value; + } + if (!is_int($value) || $value < 1) { + throw new InvalidArgumentException(sprintf('"Mcp.catalog.%s" must be a positive integer.', $key)); + } + + 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; + } + + /** + * 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; + } + + /** + * Whether this server tells clients about MCP Apps: `Mcp.apps.enabled`, or the host hook enabled the extension. + * + * @internal Used by `bin/cake mcp check`; not part of the public API. + * @return bool + */ + public function appsAnnounced(): bool + { + $this->build(true, $this->quietLogger()); + + return $this->appsAnnounced; + } + + /** + * The values of the parameters of this server's route in the current request (`/mcp/{tenant}`), shared with + * the tools through the container. + * + * @return \CakeDC\Mcp\Server\McpRoute + */ + public function route(): McpRoute + { + if ($this->container->has(McpRoute::class)) { + $route = $this->container->get(McpRoute::class); + if ($route instanceof McpRoute) { + return $route; + } + } + + return $this->route ??= new McpRoute(); + } + + /** + * The session keys of this server, and of this value of its route parameters, kept apart from the others. + * + * @return string + */ + private function sessionPrefix(): string + { + $prefix = $this->server === McpConfig::DEFAULT_SERVER ? 'mcp-' : 'mcp-' . $this->server . '-'; + $values = $this->route()->values(); + + return $values === [] ? $prefix : $prefix . hash('sha256', (string)json_encode($values)) . '-'; + } + + /** + * `Mcp.server.icons` as the SDK's icons. + * + * @return list<\Mcp\Schema\Icon>|null + * @throws \InvalidArgumentException When an entry is not an icon. + */ + private function icons(): ?array + { + $icons = McpConfig::get('server.icons', $this->server); + if ($icons === null || $icons === []) { + return null; + } + if (!is_array($icons) || !array_is_list($icons)) { + throw new InvalidArgumentException('"Mcp.server.icons" must be null or a list of icons.'); + } + try { + return array_map(fn(mixed $icon): Icon => Icon::fromArray(is_array($icon) ? $icon : []), $icons); + } catch (InvalidArgumentException $e) { + throw new InvalidArgumentException( + sprintf('"Mcp.server.icons": %s Each icon needs a "src".', $e->getMessage()), + 0, + $e, + ); + } + } + + /** + * The cache hints policy set by `Mcp.server.cache` or by the host hook, before the plugin forces `tools/list` + * private; null when neither set one. + * + * @internal Used by `bin/cake mcp check`; not part of the public API. + * @return \Mcp\Server\Wire\CachePolicy|null + */ + public function cachePolicy(): ?CachePolicy + { + $this->build(true, $this->quietLogger()); + + return $this->cachePolicy; + } + + /** + * Whether $tool is a registered app-only tool, for the audit records the endpoint writes before the server + * runs (a refused token). + * + * @internal Used by the MCP controller; not part of the public API. + * @param string $tool A tool name. + * @return bool + */ + public function isAppOnlyTool(string $tool): bool + { + if ($this->lastRegistry === null) { + $this->build(true, $this->quietLogger()); + } + $registry = $this->lastRegistry; + + return $registry !== null && $registry->hasTool($tool) && AppTools::appOnly($registry->getTool($tool)->tool); + } + + /** + * 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); + } + } + }; } /** @@ -255,12 +852,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/src/TestSuite/McpTestTrait.php b/src/TestSuite/McpTestTrait.php index 79711a2..6e82c2e 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; @@ -19,6 +20,7 @@ use CakeDC\Mcp\Server\ServerFactory; use Closure; use Mcp\Schema\Enum\ProtocolVersion; +use Mcp\Schema\Extension\Apps\McpApps; use Mcp\Server\Authorization\AccessToken; use PHPUnit\Framework\Assert; use stdClass; @@ -55,6 +57,32 @@ trait McpTestTrait */ protected array $_mcpClaims = []; + /** + * The MCP server the requests go to (`Mcp.servers`). + */ + protected string $_mcpServer = McpConfig::DEFAULT_SERVER; + + /** + * The values of the server's route parameters (`/mcp/{tenant}`) the requests are made with. + * + * @var array + */ + protected array $_mcpRoute = []; + + /** + * 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()`. * @@ -67,6 +95,16 @@ trait McpTestTrait */ protected ?string $_mcpTool = null; + /** + * The prompt name of the last `mcpGetPrompt()`. + */ + protected ?string $_mcpPrompt = null; + + /** + * The URI of the last `mcpReadResource()`. + */ + protected ?string $_mcpResource = null; + /** * What the server logged in the `mcp` scope during the last `mcpCallTool()`, * warnings and worse. Shown when an assertion fails. @@ -98,6 +136,21 @@ 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`. For a server on a + * route with parameters (`/mcp/{tenant}`), $route gives their values, as the HTTP endpoint would read them from + * the path: tools see them through `McpRoute`, and the scope policy uses that value's resource. + * + * @param string $server The server. + * @param array $route The values of the route's parameters. + * @return void + */ + public function mcpUseServer(string $server, array $route = []): void + { + $this->_mcpServer = $server; + $this->_mcpRoute = $route; + } + /** * Calls a tool and keeps the response for the `assertMcp*()` methods. * @@ -111,189 +164,964 @@ 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; + } + + /** + * Gets a prompt as the current identity, and keeps the response for `assertMcpPrompt*()`. + * + * @param string $name The prompt name. + * @param array $arguments Its arguments. + * @return array The JSON-RPC response. + */ + public function mcpGetPrompt(string $name, array $arguments = []): array + { + $this->_mcpPrompt = $name; + $params = ['name' => $name]; + if ($arguments !== []) { + $params['arguments'] = $arguments; + } + $this->_mcpResponse = $this->mcpRequest('prompts/get', $params, log: $this->_mcpLog); + + return $this->_mcpResponse; + } + + /** + * Reads a resource as the current identity (a concrete URI, also one a template matches), and keeps the + * response for `assertMcpResource*()`. + * + * @param string $uri The resource URI. + * @return array The JSON-RPC response. + */ + public function mcpReadResource(string $uri): array + { + $this->_mcpResource = $uri; + $this->_mcpResponse = $this->mcpRequest('resources/read', ['uri' => $uri], log: $this->_mcpLog); + + return $this->_mcpResponse; + } + + /** + * Asks for the completions of an argument of a prompt (`['type' => 'ref/prompt', 'name' => ...]`) or of a + * variable of a resource template (`['type' => 'ref/resource', 'uri' => 'orders://{number}']`), and keeps + * the response for `assertMcpCompletionValues()`. + * + * @param array $ref The reference. + * @param string $argument The argument or variable name. + * @param string $value What the user typed so far. + * @return array The JSON-RPC response. + */ + public function mcpComplete(array $ref, string $argument, string $value): array + { + $this->_mcpResponse = $this->mcpRequest('completion/complete', [ + 'ref' => $ref, + 'argument' => ['name' => $argument, 'value' => $value], ], log: $this->_mcpLog); return $this->_mcpResponse; } /** - * The definitions of the tools the current identity may use. + * The resources the current identity sees in `resources/list`. + * + * @return list> + */ + public function mcpListResources(): array + { + return $this->mcpListAll('resources/list', 'resources', false); + } + + /** + * The resource templates the current identity sees in `resources/templates/list`. + * + * @return list> + */ + public function mcpListResourceTemplates(): array + { + return $this->mcpListAll('resources/templates/list', 'resourceTemplates', false); + } + + /** + * The prompts the current identity sees in `prompts/list`. + * + * @return list> + */ + public function mcpListPrompts(): array + { + return $this->mcpListAll('prompts/list', 'prompts', false); + } + + /** + * Asserts the messages of the last `mcpGetPrompt()`: one `['role' => ..., 'text' => ...]` per message, in order. + * A message whose content is not text has `text` null. + * + * @param list $expected The expected messages. + * @param string $message The failure message. + * @return void + */ + public function assertMcpPromptMessages(array $expected, string $message = ''): void + { + Assert::assertSame( + $expected, + $this->mcpPromptMessages(), + $message ?: 'Unexpected prompt messages. Response: ' . $this->mcpJson($this->mcpResponse()), + ); + } + + /** + * Asserts that a text message of the last `mcpGetPrompt()` contains $text. + * + * @param string $text The expected text. + * @param string $message The failure message. + * @return void + */ + public function assertMcpPromptContains(string $text, string $message = ''): void + { + Assert::assertStringContainsString( + $text, + implode("\n", array_filter(array_column($this->mcpPromptMessages(), 'text'), 'is_string')), + $message, + ); + } + + /** + * Asserts that the last `mcpGetPrompt()` was answered with a JSON-RPC error (an unknown prompt, missing + * arguments, a prompt that failed). + * + * @param string|null $contains Text the error message must contain. + * @param string $message The failure message. + * @return void + */ + public function assertMcpPromptError(?string $contains = null, string $message = ''): void + { + $this->assertMcpJsonRpcError(null, $contains, $message); + } + + /** + * Asserts that the last `mcpReadResource()` returned a content with this exact text, and with $mimeType + * when given. + * + * @param string $expected The expected text. + * @param string|null $mimeType The expected MIME type of that content. + * @param string $message The failure message. + * @return void + */ + public function assertMcpResourceText(string $expected, ?string $mimeType = null, string $message = ''): void + { + $contents = $this->mcpResourceContents(); + $matching = array_filter( + $contents, + fn(array $content): bool => ($content['text'] ?? null) === $expected + && ($mimeType === null || ($content['mimeType'] ?? null) === $mimeType), + ); + Assert::assertNotSame([], $matching, $message ?: sprintf( + 'No content of the resource has the text %s%s. Contents: %s', + json_encode($expected), + $mimeType === null ? '' : ' with MIME type ' . $mimeType, + $this->mcpJson($contents), + )); + } + + /** + * Asserts that a text content of the last `mcpReadResource()` contains $text. + * + * @param string $text The expected text. + * @param string $message The failure message. + * @return void + */ + public function assertMcpResourceContains(string $text, string $message = ''): void + { + Assert::assertStringContainsString( + $text, + implode("\n", array_filter(array_column($this->mcpResourceContents(), 'text'), 'is_string')), + $message, + ); + } + + /** + * Asserts that the last `mcpReadResource()` was answered with a JSON-RPC error (an unknown URI, a resource + * that failed). + * + * @param string|null $contains Text the error message must contain. + * @param string $message The failure message. + * @return void + */ + public function assertMcpResourceError(?string $contains = null, string $message = ''): void + { + $this->assertMcpJsonRpcError(null, $contains, $message); + } + + /** + * Asserts that the authorizer denied the last `mcpReadResource()`: it was answered exactly like an unknown URI, + * and the URI exists (a resource, or one a template matches), so a typo cannot pass as a denial. + * + * @param string $message The failure message. + * @return void + */ + public function assertMcpResourceDenied(string $message = ''): void + { + $uri = (string)$this->_mcpResource; + $error = $this->mcpResponse()['error'] ?? null; + Assert::assertTrue( + is_array($error) && ($error['message'] ?? null) === sprintf('Resource not found for uri: "%s".', $uri), + $message ?: sprintf( + 'Expected "%s" to be answered like an unknown URI, got: %s', + $uri, + $this->mcpJson($this->mcpResponse()), + ), + ); + $response = $this->_mcpResponse; + try { + $read = $this->mcpRequest('resources/read', ['uri' => $uri], true); + } finally { + $this->_mcpResponse = $response; + } + // Read without the authorizer, a registered resource whose handler fails answers its own error: it exists. + $trusted = $read['error'] ?? null; + Assert::assertFalse( + is_array($trusted) && ($trusted['message'] ?? null) === sprintf('Resource not found for uri: "%s".', $uri), + $message + ?: sprintf('Resource "%s" is not registered, so its rejection proves nothing. Check the URI.', $uri), + ); + } + + /** + * Asserts that the authorizer denied the last `mcpGetPrompt()`: it was answered exactly like an unknown prompt, + * and the prompt exists, so a typo cannot pass as a denial. + * + * @param string $message The failure message. + * @return void + */ + public function assertMcpPromptDenied(string $message = ''): void + { + $name = (string)$this->_mcpPrompt; + $error = $this->mcpResponse()['error'] ?? null; + Assert::assertTrue( + is_array($error) && ($error['message'] ?? null) === sprintf('Prompt not found: "%s".', $name), + $message ?: sprintf( + 'Expected "%s" to be answered like an unknown prompt, got: %s', + $name, + $this->mcpJson($this->mcpResponse()), + ), + ); + Assert::assertContains( + $name, + array_column($this->mcpListAll('prompts/list', 'prompts', true), 'name'), + $message + ?: sprintf('Prompt "%s" is not registered, so its rejection proves nothing. Check the name.', $name), + ); + } + + /** + * Asserts the values of the last `mcpComplete()`, in order. + * + * @param list $expected The expected values. + * @param string $message The failure message. + * @return void + */ + public function assertMcpCompletionValues(array $expected, string $message = ''): void + { + $response = $this->mcpResponse(); + $values = $response['result']['completion']['values'] ?? null; + if (!is_array($values)) { + Assert::fail($message ?: 'The completion failed: ' . $this->mcpJson($response) . $this->mcpLogText()); + } + Assert::assertSame($expected, $values, $message); + } + + /** + * Asserts that the current identity sees a resource in `resources/list`. + * + * @param string $uri The resource URI. + * @param string $message The failure message. + * @return void + */ + public function assertMcpResourceListed(string $uri, string $message = ''): void + { + Assert::assertContains( + $uri, + array_column($this->mcpListResources(), 'uri'), + $message ?: sprintf('Resource "%s" is not listed for the current identity.', $uri), + ); + } + + /** + * Asserts that the current identity does not see a resource in `resources/list`. It also checks that the + * resource exists, so a typo cannot pass as hidden. + * + * @param string $uri The resource URI. + * @param string $message The failure message. + * @return void + */ + public function assertMcpResourceNotListed(string $uri, string $message = ''): void + { + $this->mcpAssertHidden('resources/list', 'resources', 'uri', $uri, 'Resource', $message); + } + + /** + * Asserts that the current identity sees a resource template in `resources/templates/list`. + * + * @param string $uriTemplate The URI template, `orders://{number}`. + * @param string $message The failure message. + * @return void + */ + public function assertMcpResourceTemplateListed(string $uriTemplate, string $message = ''): void + { + Assert::assertContains( + $uriTemplate, + array_column($this->mcpListResourceTemplates(), 'uriTemplate'), + $message + ?: sprintf('Resource template "%s" is not listed for the current identity.', $uriTemplate), + ); + } + + /** + * Asserts that the current identity does not see a resource template in `resources/templates/list`, and + * that it exists. + * + * @param string $uriTemplate The URI template. + * @param string $message The failure message. + * @return void + */ + public function assertMcpResourceTemplateNotListed(string $uriTemplate, string $message = ''): void + { + $this->mcpAssertHidden( + 'resources/templates/list', + 'resourceTemplates', + 'uriTemplate', + $uriTemplate, + 'Resource template', + $message, + ); + } + + /** + * Asserts that the current identity sees a prompt in `prompts/list`. + * + * @param string $name The prompt name. + * @param string $message The failure message. + * @return void + */ + public function assertMcpPromptListed(string $name, string $message = ''): void + { + Assert::assertContains( + $name, + array_column($this->mcpListPrompts(), 'name'), + $message ?: sprintf('Prompt "%s" is not listed for the current identity.', $name), + ); + } + + /** + * Asserts that the current identity does not see a prompt in `prompts/list`, and that it exists. + * + * @param string $name The prompt name. + * @param string $message The failure message. + * @return void + */ + public function assertMcpPromptNotListed(string $name, string $message = ''): void + { + $this->mcpAssertHidden('prompts/list', 'prompts', 'name', $name, 'Prompt', $message); + } + + /** + * The definitions of the tools the current identity may use. + * + * @return list> + */ + public function mcpListTools(): array + { + return $this->mcpToolDefinitions(false); + } + + /** + * @return array The JSON-RPC response to the last `mcpCallTool()`, `mcpGetPrompt()`, + * `mcpReadResource()` or `mcpComplete()`. + */ + public function mcpResponse(): array + { + if ($this->_mcpResponse === null) { + Assert::fail( + 'No request was sent yet. Call mcpCallTool(), mcpGetPrompt(), mcpReadResource() or mcpComplete().', + ); + } + + return $this->_mcpResponse; + } + + /** + * The text content of the last result (or tool error), one line per item. + * + * @return string + */ + public function mcpResultText(): string + { + $content = $this->mcpResult()['content'] ?? []; + $texts = []; + foreach (is_array($content) ? $content : [] as $item) { + if (is_array($item) && ($item['type'] ?? null) === 'text' && is_string($item['text'] ?? null)) { + $texts[] = $item['text']; + } + } + + return implode("\n", $texts); + } + + /** + * Asserts that the last tool call returned a result that is not a tool error. + * + * @param string $message The failure message. + * @return void + */ + public function assertMcpToolSucceeded(string $message = ''): void + { + $response = $this->mcpResponse(); + Assert::assertArrayHasKey( + 'result', + $response, + $message ?: 'The tool call failed: ' . $this->mcpJson($response) . $this->mcpLogText(), + ); + Assert::assertNotTrue( + $this->mcpResult()['isError'] ?? false, + $message ?: 'The tool returned an error: ' . $this->mcpResultText() . $this->mcpLogText(), + ); + } + + /** + * Asserts that the last tool call returned a tool error, the kind the model + * reads (`ToolCallException`, `ToolError::invalid()`). + * + * @param string|null $contains Text the error message must contain. + * @param string $message The failure message. + * @return void + */ + public function assertMcpToolError(?string $contains = null, string $message = ''): void + { + Assert::assertTrue( + ($this->mcpResult()['isError'] ?? false) === true, + $message ?: 'Expected a tool error, got: ' . $this->mcpJson($this->mcpResponse()) . $this->mcpLogText(), + ); + if ($contains !== null) { + Assert::assertStringContainsString($contains, $this->mcpResultText(), $message); + } + } + + /** + * Asserts that the last tool call was answered with a JSON-RPC error: invalid + * arguments (-32602), an unexpected exception (-32603), an unknown or denied tool. + * + * @param int|null $code The expected error code. + * @param string|null $contains Text the error message must contain. + * @param string $message The failure message. + * @return void + */ + public function assertMcpJsonRpcError(?int $code = null, ?string $contains = null, string $message = ''): void + { + $response = $this->mcpResponse(); + $error = $response['error'] ?? null; + if (!is_array($error)) { + Assert::fail( + $message ?: 'Expected a JSON-RPC error, got: ' . $this->mcpJson($response) . $this->mcpLogText(), + ); + } + if ($code !== null) { + Assert::assertSame($code, $error['code'] ?? null, $message ?: 'Unexpected JSON-RPC error code.'); + } + if ($contains !== null) { + Assert::assertStringContainsString($contains, (string)($error['message'] ?? ''), $message); + } + } + + /** + * Asserts that the authorizer rejected the last tool call. A denied tool is + * answered exactly like an unknown one, so this also checks that the tool + * exists; otherwise a typo in the name would pass as a denial. + * + * @param string $message The failure message. + * @return void + */ + public function assertMcpToolDenied(string $message = ''): void + { + $this->mcpResponse(); + $tool = (string)$this->_mcpTool; + $this->assertMcpJsonRpcError(-32602, sprintf('Tool not found: "%s".', $tool), $message); + Assert::assertContains( + $tool, + $this->mcpRegisteredToolNames(), + $message ?: sprintf('Tool "%s" is not registered, so its rejection proves nothing. Check the name.', $tool), + ); + } + + /** + * Asserts the last call was refused because the access token lacks scopes, as the HTTP endpoint + * answers with 403 `insufficient_scope` (only with scopes given to `mcpActingAs()`, in the oauth and + * external modes). Only tool calls get this answer: a refused `tools/list` fails the test right away. + * + * @param list|null $scopes The scopes the call needs, any when null. + * @param string $message Shown on failure. + * @return void + */ + public function assertMcpInsufficientScope(?array $scopes = null, string $message = ''): void + { + $response = $this->mcpResponse(); + $error = $response['error'] ?? null; + Assert::assertTrue( + is_array($error) && ($error['message'] ?? null) === 'insufficient_scope', + $message ?: 'Expected the call to be refused for missing scopes, got: ' . $this->mcpJson($response), + ); + if ($scopes !== null) { + Assert::assertEqualsCanonicalizing( + $scopes, + $error['data']['scopes'] ?? null, + $message, + ); + } + } + + /** + * Asserts that the text of the last result contains a string. + * + * @param string $text The expected text. + * @param string $message The failure message. + * @return void + */ + public function assertMcpResultContains(string $text, string $message = ''): void + { + Assert::assertStringContainsString($text, $this->mcpResultText(), $message); + } + + /** + * Asserts the `structuredContent` of the last result. Key order does not + * matter, value types do. + * + * @param array $expected The expected structured content. + * @param string $message The failure message. + * @return void + */ + public function assertMcpStructuredContent(array $expected, string $message = ''): void + { + Assert::assertSame( + $this->mcpSortKeys($expected), + $this->mcpSortKeys($this->mcpResult()['structuredContent'] ?? null), + $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. $expected may be a closure + * that gets the value: the assertion passes when it returns `true` (strictly), and it is not called for a + * path that does not exist. + * + * @param string $path Dot path into the structured content. + * @param mixed $expected The expected value, or a closure that tells whether the value is right. + * @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)); + } + if ($expected instanceof Closure) { + Assert::assertTrue( + $expected($value) === true, + $message ?: sprintf( + 'The closure did not return true for "%s" in the structuredContent: %s.', + $path, + (string)json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), + ), + ); + + return; + } + Assert::assertSame($expected, $value, $message); + } + + /** + * Asserts that a dot path, or each of several, does not exist in the last result's `structuredContent`. A key + * that is there with a `null` value exists (`assertMcpStructuredContentHas()` passes on it), so it fails here. + * + * @param list|string $paths A dot path, or a list of them. + * @param string $message The failure message. + * @return void + */ + public function assertMcpStructuredContentMissing(string|array $paths, string $message = ''): void + { + foreach ((array)$paths as $path) { + Assert::assertFalse( + $this->mcpStructuredContentAt($path)[0], + $message ?: sprintf('The structuredContent has "%s".', $path), + ); + } + } + + /** + * Asserts that the last result's `structuredContent` does not hold $fragment: fails exactly when + * `assertMcpStructuredContentSubset($fragment)` would pass. The same rule, so it is anchored at the top of the + * structured content; for pairs anywhere, use `assertMcpStructuredContentLacks()`. + * + * @param array $fragment The part that must not be there whole. + * @param string $message The failure message. + * @return void + */ + public function assertMcpStructuredContentNotSubset(array $fragment, string $message = ''): void + { + $actual = $this->mcpResult()['structuredContent'] ?? null; + Assert::assertFalse( + self::mcpIsSubset($fragment, $actual), + $message ?: sprintf( + 'The structuredContent %s holds %s.', + $this->mcpJson(is_array($actual) ? $actual : []), + $this->mcpJson($fragment), + ), + ); + } + + /** + * Asserts that none of the key and value pairs of $pairs is in any object of the last result's + * `structuredContent`, at any depth (`['sku' => 'X']` fails when any object, however nested, has `sku` "X"). + * Value types matter. + * + * @param array $pairs Key => value pairs that must appear nowhere. + * @param string $message The failure message. + * @return void + */ + public function assertMcpStructuredContentLacks(array $pairs, string $message = ''): void + { + $actual = $this->mcpResult()['structuredContent'] ?? null; + foreach ($pairs as $key => $value) { + Assert::assertFalse( + self::mcpHasPairAnywhere($actual, (string)$key, $value), + $message ?: sprintf( + 'The structuredContent has "%s": %s.', + $key, + (string)json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), + ), + ); + } + } + + /** + * Asserts the last result's `structuredContent`, or the value at a dot path of it, ignoring the order of list + * items at every level (key order never matters). Value types matter and duplicates count: `[1, 1, 2]` is not + * `[1, 2, 2]`. Fails when the path does not exist. + * + * @param mixed $expected The expected value. + * @param string $path A dot path, or an empty string for the whole structured content. + * @param string $message The failure message. + * @return void + */ + public function assertMcpStructuredContentIgnoringOrder( + mixed $expected, + string $path = '', + string $message = '', + ): void { + [$found, $value] = $this->mcpStructuredContentAt($path); + if (!$found) { + Assert::fail($message ?: sprintf('The structuredContent has no "%s".', $path)); + } + Assert::assertTrue(self::mcpSame($expected, $value, true), $message ?: sprintf( + '"%s" in the structuredContent is %s, not %s in any order.', + $path === '' ? '(all)' : $path, + (string)json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), + (string)json_encode($expected, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), + )); + } + + /** + * Asserts the keys of the last result's `structuredContent`, not their values. $shape describes them level by + * level: a string is a key that must exist, `key => [...]` a key and what its value holds, and `'*' => [...]` + * what every item of the list at that level holds (the list must not be empty: a wildcard that checks nothing + * fails). With $exact, a described level may have no other keys. + * + * @param array $shape The keys, for example `['order' => ['id', 'lines' => ['*' => ['sku']]], 'total']`. + * @param bool $exact Whether keys other than the described ones fail. + * @param string $message The failure message. + * @return void + */ + public function assertMcpStructuredContentKeys(array $shape, bool $exact = false, string $message = ''): void + { + $problem = self::mcpShapeProblem($shape, $this->mcpResult()['structuredContent'] ?? null, '', $exact); + Assert::assertNull($problem, $message ?: (string)$problem); + } + + /** + * 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 the last result's `structuredContent` holds $expected: every key of an object with the same + * value (recursively, other keys allowed), lists compared whole. Value types matter. + * + * @param array $expected The expected part. + * @param string $message The failure message. + * @return void + */ + public function assertMcpStructuredContentSubset(array $expected, string $message = ''): void + { + $actual = $this->mcpResult()['structuredContent'] ?? null; + Assert::assertTrue( + self::mcpIsSubset($expected, $actual), + $message ?: sprintf( + 'The structuredContent %s does not hold %s.', + $this->mcpJson(is_array($actual) ? $actual : []), + $this->mcpJson($expected), + ), + ); + } + + /** + * Asserts how many items (or keys) the list or object at a dot path of the last result's `structuredContent` + * has; an empty path is the whole structured content. + * + * @param string $path Dot path, or an empty string. + * @param int $count The expected count. + * @param string $message The failure message. + * @return void + */ + public function assertMcpStructuredContentCount(string $path, int $count, string $message = ''): void + { + [$found, $value] = $this->mcpStructuredContentAt($path); + if (!$found || !is_array($value)) { + Assert::fail($message ?: sprintf('The structuredContent has no list or object at "%s".', $path)); + } + Assert::assertCount($count, $value, $message); + } + + /** + * Asserts the JSON type of the value at a dot path of the last result's `structuredContent`: `string`, + * `number` (an integer is a number too), `integer`, `boolean`, `array`, `object` or `null`. An empty path is + * the whole structured content. + * + * @param string $path Dot path, or an empty string. + * @param string $type The JSON type. + * @param string $message The failure message. + * @return void + */ + public function assertMcpStructuredContentType(string $path, string $type, string $message = ''): void + { + [$found, $value] = $this->mcpStructuredContentAt($path); + if (!$found) { + Assert::fail($message ?: sprintf('The structuredContent has no "%s".', $path)); + } + $actual = match (true) { + $value === null => 'null', + is_bool($value) => 'boolean', + is_int($value) => 'integer', + is_float($value) => 'number', + is_string($value) => 'string', + is_array($value) && array_is_list($value) && $value !== [] => 'array', + default => 'object', + }; + $matches = $actual === $type || ($type === 'number' && $actual === 'integer') + || ($value === [] && ($type === 'array' || $type === 'object')); + Assert::assertTrue( + $matches, + $message ?: sprintf('"%s" in the structuredContent is %s, not %s.', $path, $actual, $type), + ); + } + + /** + * Asserts that the values of the last `mcpComplete()` include $value. + * + * @param string $value The expected value. + * @param string $message The failure message. + * @return void + */ + public function assertMcpCompletionContains(string $value, string $message = ''): void + { + $values = $this->mcpResponse()['result']['completion']['values'] ?? null; + if (!is_array($values)) { + Assert::fail($message ?: 'The completion failed: ' . $this->mcpJson($this->mcpResponse())); + } + Assert::assertContains($value, $values, $message); + } + + /** + * Asserts that another identity sees a prompt in `prompts/list`, with default scopes and no claims. The + * test's own identity, scopes and claims stay as they were. + * + * @param mixed $identity The identity. + * @param string $name The prompt name. + * @param string $message The failure message. + * @return void + */ + public function assertMcpPromptListedFor(mixed $identity, string $name, string $message = ''): void + { + $this->mcpAs($identity, fn() => $this->assertMcpPromptListed($name, $message)); + } + + /** + * Asserts that another identity does not see a prompt in `prompts/list` (and that it exists). * - * @return list> + * @param mixed $identity The identity. + * @param string $name The prompt name. + * @param string $message The failure message. + * @return void */ - public function mcpListTools(): array + public function assertMcpPromptNotListedFor(mixed $identity, string $name, string $message = ''): void { - return $this->mcpToolDefinitions(false); + $this->mcpAs($identity, fn() => $this->assertMcpPromptNotListed($name, $message)); } /** - * @return array The JSON-RPC response to the last `mcpCallTool()`. + * Asserts that another identity sees a resource in `resources/list`. + * + * @param mixed $identity The identity. + * @param string $uri The resource URI. + * @param string $message The failure message. + * @return void */ - public function mcpResponse(): array + public function assertMcpResourceListedFor(mixed $identity, string $uri, string $message = ''): void { - if ($this->_mcpResponse === null) { - Assert::fail('No tool was called yet. Call mcpCallTool() first.'); - } - - return $this->_mcpResponse; + $this->mcpAs($identity, fn() => $this->assertMcpResourceListed($uri, $message)); } /** - * The text content of the last result (or tool error), one line per item. + * Asserts that another identity does not see a resource in `resources/list` (and that it exists). * - * @return string + * @param mixed $identity The identity. + * @param string $uri The resource URI. + * @param string $message The failure message. + * @return void */ - public function mcpResultText(): string + public function assertMcpResourceNotListedFor(mixed $identity, string $uri, string $message = ''): void { - $content = $this->mcpResult()['content'] ?? []; - $texts = []; - foreach (is_array($content) ? $content : [] as $item) { - if (is_array($item) && ($item['type'] ?? null) === 'text' && is_string($item['text'] ?? null)) { - $texts[] = $item['text']; - } - } - - return implode("\n", $texts); + $this->mcpAs($identity, fn() => $this->assertMcpResourceNotListed($uri, $message)); } /** - * Asserts that the last tool call returned a result that is not a tool error. + * 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 assertMcpToolSucceeded(string $message = ''): void + public function assertMcpToolListedFor(mixed $identity, string $name, string $message = ''): void { - $response = $this->mcpResponse(); - Assert::assertArrayHasKey( - 'result', - $response, - $message ?: 'The tool call failed: ' . $this->mcpJson($response) . $this->mcpLogText(), - ); - Assert::assertNotTrue( - $this->mcpResult()['isError'] ?? false, - $message ?: 'The tool returned an error: ' . $this->mcpResultText() . $this->mcpLogText(), - ); + $this->mcpAs($identity, fn() => $this->assertMcpToolListed( + $name, + $message ?: sprintf('Tool "%s" is not listed for that identity.', $name), + )); } /** - * Asserts that the last tool call returned a tool error, the kind the model - * reads (`ToolCallException`, `ToolError::invalid()`). + * 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 string|null $contains Text the error message must contain. + * @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 assertMcpToolError(?string $contains = null, string $message = ''): void + public function assertMcpToolNotListedFor(mixed $identity, string $name, string $message = ''): void { - Assert::assertTrue( - ($this->mcpResult()['isError'] ?? false) === true, - $message ?: 'Expected a tool error, got: ' . $this->mcpJson($this->mcpResponse()) . $this->mcpLogText(), - ); - if ($contains !== null) { - Assert::assertStringContainsString($contains, $this->mcpResultText(), $message); - } + $this->mcpAs($identity, fn() => $this->assertMcpToolNotListed($name, $message)); } /** - * Asserts that the last tool call was answered with a JSON-RPC error: invalid - * arguments (-32602), an unexpected exception (-32603), an unknown or denied tool. + * Runs $assertion as $identity, then puts back the test's identity, scopes and claims. * - * @param int|null $code The expected error code. - * @param string|null $contains Text the error message must contain. - * @param string $message The failure message. + * @param mixed $identity The identity. + * @param callable(): void $assertion The assertion. * @return void */ - public function assertMcpJsonRpcError(?int $code = null, ?string $contains = null, string $message = ''): void + private function mcpAs(mixed $identity, callable $assertion): void { - $response = $this->mcpResponse(); - $error = $response['error'] ?? null; - if (!is_array($error)) { - Assert::fail( - $message ?: 'Expected a JSON-RPC error, got: ' . $this->mcpJson($response) . $this->mcpLogText(), - ); - } - if ($code !== null) { - Assert::assertSame($code, $error['code'] ?? null, $message ?: 'Unexpected JSON-RPC error code.'); - } - if ($contains !== null) { - Assert::assertStringContainsString($contains, (string)($error['message'] ?? ''), $message); + $saved = [$this->_mcpIdentity, $this->_mcpScopes, $this->_mcpClaims]; + $this->mcpActingAs($identity); + try { + $assertion(); + } finally { + [$this->_mcpIdentity, $this->_mcpScopes, $this->_mcpClaims] = $saved; } } /** - * Asserts that the authorizer rejected the last tool call. A denied tool is - * answered exactly like an unknown one, so this also checks that the tool - * exists; otherwise a typo in the name would pass as a denial. - * - * @param string $message The failure message. - * @return void + * @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. */ - public function assertMcpToolDenied(string $message = ''): void + private function mcpStructuredContentAt(string $path): array { - $this->mcpResponse(); - $tool = (string)$this->_mcpTool; - $this->assertMcpJsonRpcError(-32602, sprintf('Tool not found: "%s".', $tool), $message); - Assert::assertContains( - $tool, - array_column($this->mcpToolDefinitions(true), 'name'), - $message ?: sprintf('Tool "%s" is not registered, so its rejection proves nothing. Check the name.', $tool), - ); + $value = $this->mcpResult()['structuredContent'] ?? null; + if ($path === '') { + return [$value !== null, $value]; + } + foreach (explode('.', $path) as $key) { + if (!is_array($value) || !array_key_exists($key, $value)) { + return [false, null]; + } + $value = $value[$key]; + } + + return [true, $value]; } /** - * Asserts the last call was refused because the access token lacks scopes, as the HTTP endpoint - * answers with 403 `insufficient_scope` (only with scopes given to `mcpActingAs()`, in the oauth and - * external modes). Only tool calls get this answer: a refused `tools/list` fails the test right away. + * The notifications the server sent during the last `mcpCallTool()`, all of them or those of one method + * (`notifications/progress`, `notifications/message`...). * - * @param list|null $scopes The scopes the call needs, any when null. - * @param string $message Shown on failure. - * @return void + * @param string|null $method A notification method, or null for all. + * @return list> */ - public function assertMcpInsufficientScope(?array $scopes = null, string $message = ''): void + public function mcpNotifications(?string $method = null): array { - $response = $this->mcpResponse(); - $error = $response['error'] ?? null; - Assert::assertTrue( - is_array($error) && ($error['message'] ?? null) === 'insufficient_scope', - $message ?: 'Expected the call to be refused for missing scopes, got: ' . $this->mcpJson($response), - ); - if ($scopes !== null) { - Assert::assertEqualsCanonicalizing( - $scopes, - $error['data']['scopes'] ?? null, - $message, - ); - } + return array_values(array_filter( + $this->_mcpNotifications, + fn(array $notification): bool => $method === null || ($notification['method'] ?? null) === $method, + )); } /** - * Asserts that the text of the last result contains a string. + * Asserts that the last call sent a notification of $method. * - * @param string $text The expected text. + * @param string $method The notification method, for example `notifications/message`. * @param string $message The failure message. * @return void */ - public function assertMcpResultContains(string $text, string $message = ''): void + public function assertMcpNotificationSent(string $method, string $message = ''): void { - Assert::assertStringContainsString($text, $this->mcpResultText(), $message); + Assert::assertNotEmpty( + $this->mcpNotifications($method), + $message ?: sprintf('The last call sent no %s notification.', $method), + ); } /** - * Asserts the `structuredContent` of the last result. Key order does not - * matter, value types do. + * Asserts that the last call reported progress: at least once, or exactly $count times. * - * @param array $expected The expected structured content. + * @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 assertMcpStructuredContent(array $expected, string $message = ''): void + public function assertMcpProgressSent(?int $count = null, string $message = ''): void { - Assert::assertSame( - $this->mcpSortKeys($expected), - $this->mcpSortKeys($this->mcpResult()['structuredContent'] ?? null), - $message, - ); + $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)); } /** @@ -329,7 +1157,7 @@ public function assertMcpToolNotListed(string $name, string $message = ''): void ); Assert::assertContains( $name, - array_column($this->mcpToolDefinitions(true), 'name'), + $this->mcpRegisteredToolNames(), $message ?: sprintf('Tool "%s" is not registered, so its absence proves nothing. Check the name.', $name), ); } @@ -378,14 +1206,18 @@ private function mcpRequest(string $method, ?array $params, bool $trusted = fals if ($params !== null) { $request['params'] = $params; } + // A request refused before it reaches the server (a missing scope) sends no notifications either. + $this->_mcpLastNotifications = []; $factory = $this->mcpContainer()->get(ServerFactory::class); 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); + $factory->route()->set($this->_mcpRoute); - $scopes = McpConfig::get('identity.scopes'); + $scopes = McpConfig::get('identity.scopes', $this->_mcpServer); $token = null; if ($this->_mcpIdentity !== null) { $token = IdentityMiddleware::accessTokenFor( @@ -400,10 +1232,14 @@ 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, $this->_mcpRoute); $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())); @@ -430,10 +1266,20 @@ private function mcpRequest(string $method, ?array $params, bool $trusted = fals [ (string)json_encode(['jsonrpc' => '2.0', 'id' => 1, 'method' => 'initialize', 'params' => [ 'protocolVersion' => ProtocolVersion::latestHandshake()->value, - 'capabilities' => new stdClass(), + // With MCP Apps on, the trait is a host that renders apps, so app-only tools are listed to it. + 'capabilities' => McpConfig::get('apps.enabled', $this->_mcpServer) === true + ? ['extensions' => [McpApps::EXTENSION_ID => ['mimeTypes' => [McpApps::MIME_TYPE]]]] + : new stdClass(), '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, @@ -453,9 +1299,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; @@ -489,6 +1345,155 @@ private function mcpToolDefinitions(bool $trusted): array return $tools; } + /** + * @param mixed $expected The expected part. + * @param mixed $actual The value. + * @return bool Whether $actual holds $expected (objects by key, other values identical). + */ + private static function mcpIsSubset(mixed $expected, mixed $actual): bool + { + if (!is_array($expected) || array_is_list($expected)) { + return self::mcpSame($expected, $actual, false); + } + if (!is_array($actual)) { + return false; + } + foreach ($expected as $key => $value) { + if (!array_key_exists($key, $actual) || !self::mcpIsSubset($value, $actual[$key])) { + return false; + } + } + + return true; + } + + /** + * Every page of a list method. + * + * @param string $method `resources/list`, `resources/templates/list` or `prompts/list`. + * @param string $key The key of the items in the result. + * @param bool $trusted Skip the authorizer, to see everything registered. + * @return list> + */ + private function mcpListAll(string $method, string $key, bool $trusted): array + { + $items = []; + $cursor = null; + for ($page = 0; $page < 100; $page++) { + $response = $this->mcpRequest($method, $cursor === null ? null : ['cursor' => $cursor], $trusted); + // A server with nothing of that kind does not announce the capability, and answers "method not found". + if (($response['error']['code'] ?? null) === -32601) { + return []; + } + $result = $response['result'] ?? null; + if (!is_array($result) || !is_array($result[$key] ?? null)) { + Assert::fail($method . ' failed: ' . $this->mcpJson($response)); + } + foreach ($result[$key] as $item) { + if (is_array($item)) { + $items[] = $item; + } + } + $cursor = $result['nextCursor'] ?? null; + if (!is_string($cursor)) { + break; + } + } + + return $items; + } + + /** + * Asserts that $value is not in what the current identity lists, and is in what is registered. + * + * @param string $method The list method. + * @param string $key The key of the items in the result. + * @param string $field The item field compared with $value. + * @param string $value The URI, URI template or name. + * @param string $what `Resource`, `Resource template` or `Prompt`, for the messages. + * @param string $message The failure message. + * @return void + */ + private function mcpAssertHidden( + string $method, + string $key, + string $field, + string $value, + string $what, + string $message, + ): void { + Assert::assertNotContains( + $value, + array_column($this->mcpListAll($method, $key, false), $field), + $message ?: sprintf('%s "%s" is listed for the current identity.', $what, $value), + ); + Assert::assertContains( + $value, + array_column($this->mcpListAll($method, $key, true), $field), + $message ?: sprintf( + '%s "%s" is not registered, so its absence proves nothing. Check the name.', + $what, + $value, + ), + ); + } + + /** + * @return list The messages of the last `mcpGetPrompt()`. + */ + private function mcpPromptMessages(): array + { + $response = $this->mcpResponse(); + $messages = $response['result']['messages'] ?? null; + if (!is_array($messages)) { + Assert::fail('The prompt failed: ' . $this->mcpJson($response) . $this->mcpLogText()); + } + $found = []; + foreach ($messages as $item) { + $content = is_array($item) ? ($item['content'] ?? null) : null; + $found[] = [ + 'role' => is_array($item) ? (string)($item['role'] ?? '') : '', + 'text' => is_array($content) && ($content['type'] ?? null) === 'text' + && is_string($content['text'] ?? null) ? $content['text'] : null, + ]; + } + + return $found; + } + + /** + * @return list> The contents of the last `mcpReadResource()`. + */ + private function mcpResourceContents(): array + { + $response = $this->mcpResponse(); + $contents = $response['result']['contents'] ?? null; + if (!is_array($contents)) { + Assert::fail('The resource read failed: ' . $this->mcpJson($response) . $this->mcpLogText()); + } + + return array_values(array_filter($contents, 'is_array')); + } + + /** + * Every tool registered on the server, including those `tools/list` leaves out (catalogued and app-only + * tools), as `bin/cake mcp check` sees them. + * + * @return list + */ + private function mcpRegisteredToolNames(): array + { + $factory = $this->mcpContainer()->get(ServerFactory::class); + if (!$factory instanceof ServerFactory) { + Assert::fail('The container has no MCP ServerFactory. Is the CakeDC/Mcp plugin loaded?'); + } + + return array_map( + fn(array $tool): string => (string)$tool['name'], + $factory->forServer($this->_mcpServer)->registeredToolDefinitions(), + ); + } + /** * @return array The `result` of the last tool call, or an empty array. */ @@ -499,6 +1504,136 @@ private function mcpResult(): array return is_array($result) ? $result : []; } + /** + * @param mixed $value A decoded JSON value. + * @param string $key A key. + * @param mixed $expected Its value. + * @return bool Whether some object in $value, at any depth, has $key with exactly $expected. + */ + private static function mcpHasPairAnywhere(mixed $value, string $key, mixed $expected): bool + { + if (!is_array($value)) { + return false; + } + if (!array_is_list($value) && array_key_exists($key, $value) && self::mcpSame($expected, $value[$key], false)) { + return true; + } + foreach ($value as $child) { + if (self::mcpHasPairAnywhere($child, $key, $expected)) { + return true; + } + } + + return false; + } + + /** + * Whether two decoded JSON values are equal. The order of an object's keys never matters; with $anyOrder, the + * order of list items does not either, but each expected item is matched with an actual one of its own, so + * duplicates count. Value types matter. + * + * @param mixed $expected The expected value. + * @param mixed $actual The actual value. + * @param bool $anyOrder Whether list items may be in any order. + * @return bool + */ + private static function mcpSame(mixed $expected, mixed $actual, bool $anyOrder): bool + { + if (!is_array($expected) || !is_array($actual)) { + return $expected === $actual; + } + if (count($expected) !== count($actual) || array_is_list($expected) !== array_is_list($actual)) { + return false; + } + if (!array_is_list($expected)) { + foreach ($expected as $key => $value) { + if (!array_key_exists($key, $actual) || !self::mcpSame($value, $actual[$key], $anyOrder)) { + return false; + } + } + + return true; + } + if (!$anyOrder) { + foreach ($expected as $index => $value) { + if (!self::mcpSame($value, $actual[$index], false)) { + return false; + } + } + + return true; + } + $unused = $actual; + foreach ($expected as $value) { + $match = null; + foreach ($unused as $index => $candidate) { + if (self::mcpSame($value, $candidate, true)) { + $match = $index; + break; + } + } + if ($match === null) { + return false; + } + unset($unused[$match]); + } + + return true; + } + + /** + * @param array $shape A level of the shape of assertMcpStructuredContentKeys(). + * @param mixed $value The value at that level. + * @param string $at Its dot path, for the message. + * @param bool $exact Whether other keys are a problem. + * @return string|null What is wrong, or null. + */ + private static function mcpShapeProblem(array $shape, mixed $value, string $at, bool $exact): ?string + { + $where = $at === '' ? 'the structuredContent' : '"' . $at . '"'; + if (array_key_exists('*', $shape)) { + if (!is_array($value) || !array_is_list($value) || $value === []) { + return sprintf('%s is not a list with items, so "*" checks nothing.', ucfirst($where)); + } + foreach ($value as $index => $item) { + $problem = self::mcpShapeProblem( + is_array($shape['*']) ? $shape['*'] : [], + $item, + ltrim($at . '.' . $index, '.'), + $exact, + ); + if ($problem !== null) { + return $problem; + } + } + + return null; + } + if (!is_array($value) || ($value !== [] && array_is_list($value))) { + return sprintf('%s is not an object.', ucfirst($where)); + } + $named = []; + foreach ($shape as $key => $inner) { + $name = is_int($key) ? (string)$inner : (string)$key; + $named[] = $name; + if (!array_key_exists($name, $value)) { + return sprintf('%s has no "%s".', ucfirst($where), $name); + } + if (!is_int($key) && is_array($inner)) { + $problem = self::mcpShapeProblem($inner, $value[$name], ltrim($at . '.' . $name, '.'), $exact); + if ($problem !== null) { + return $problem; + } + } + } + $other = array_diff(array_map('strval', array_keys($value)), $named); + if ($exact && $other !== []) { + return sprintf('%s has keys that are not described: %s.', ucfirst($where), implode(', ', $other)); + } + + return null; + } + /** * @param mixed $value A decoded JSON value. * @return mixed The value with the keys of its objects sorted, recursively. diff --git a/src/TestSuite/RecordingTransport.php b/src/TestSuite/RecordingTransport.php index 706d22e..dfb35cc 100644 --- a/src/TestSuite/RecordingTransport.php +++ b/src/TestSuite/RecordingTransport.php @@ -3,6 +3,7 @@ namespace CakeDC\Mcp\TestSuite; +use LogicException; use Mcp\Server\Authorization\AccessToken; use Mcp\Server\Transport\InMemoryTransport; use Symfony\Component\Uid\Uuid; @@ -14,6 +15,11 @@ */ class RecordingTransport extends InMemoryTransport { + /** + * The most times a handler may suspend itself (to send a notification) in one request. + */ + private const MAX_STEPS = 1000000; + /** * Every message the server sent, decoded. * @@ -21,6 +27,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 +47,65 @@ 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; reaching it fails loudly. + for ($step = 0; $this->sessionFiber !== null; $step++) { + if ($step >= self::MAX_STEPS) { + throw new LogicException(sprintf( + 'The handler suspended itself %d times without ending; RecordingTransport stopped it.', + self::MAX_STEPS, + )); + } + $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/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/src/Tool/ToolValidation.php b/src/Tool/ToolValidation.php new file mode 100644 index 0000000..13587e8 --- /dev/null +++ b/src/Tool/ToolValidation.php @@ -0,0 +1,60 @@ + $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); + } + } + + /** + * The same check for the arguments of a prompt: the client gets the lines as the error of `prompts/get`. + * + * @param array $arguments The prompt'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. + * @return void + * @throws \Mcp\Exception\PromptGetException When a rule fails. + */ + public static function checkPrompt( + array $arguments, + Validator $validator, + string $message = 'The arguments are invalid.', + bool $newRecord = true, + ): void { + $errors = $validator->validate($arguments, $newRecord); + if ($errors !== []) { + throw new PromptGetException(ToolError::invalid($errors, $message)->getMessage()); + } + } +} 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/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/app.twig b/templates/bake/tests/app.twig new file mode 100644 index 0000000..f5003ce --- /dev/null +++ b/templates/bake/tests/app.twig @@ -0,0 +1,41 @@ +{{ element('Bake.file_header', { + namespace: testNamespace, + classImports: [ + 'Cake\\Core\\Plugin', + 'Cake\\TestSuite\\TestCase', + 'CakeDC\\Mcp\\McpPlugin', + 'CakeDC\\Mcp\\TestSuite\\McpTestTrait', + "#{namespace}\\Mcp\\#{className}", + ], +}) }} + +class {{ className }}Test extends TestCase +{ + use McpTestTrait; + + protected function setUp(): void + { + parent::setUp(); + // The page's layout comes from the plugin, which a test case does not load by itself. + if (!Plugin::isLoaded('CakeDC/Mcp')) { + Plugin::getCollection()->add(new McpPlugin()); + } + } + + 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/templates/bake/tests/prompt.twig b/templates/bake/tests/prompt.twig new file mode 100644 index 0000000..d422d73 --- /dev/null +++ b/templates/bake/tests/prompt.twig @@ -0,0 +1,22 @@ +{{ element('Bake.file_header', { + namespace: testNamespace, + classImports: [ + 'Cake\\TestSuite\\TestCase', + 'CakeDC\\Mcp\\TestSuite\\McpTestTrait', + ], +}) }} + +class {{ className }}Test extends TestCase +{ + use McpTestTrait; + + public function testItBuildsMessages(): void + { + $this->mcpActingAs(['id' => 1]); + + $this->mcpGetPrompt('{{ mcpName }}', ['topic' => 'example']); + + $this->assertMcpPromptContains('example'); + $this->assertMcpPromptListed('{{ mcpName }}'); + } +} diff --git a/templates/bake/tests/resource.twig b/templates/bake/tests/resource.twig new file mode 100644 index 0000000..162a402 --- /dev/null +++ b/templates/bake/tests/resource.twig @@ -0,0 +1,22 @@ +{{ element('Bake.file_header', { + namespace: testNamespace, + classImports: [ + 'Cake\\TestSuite\\TestCase', + 'CakeDC\\Mcp\\TestSuite\\McpTestTrait', + ], +}) }} + +class {{ className }}Test extends TestCase +{ + use McpTestTrait; + + public function testItHasContent(): void + { + $this->mcpActingAs(['id' => 1]); + + $this->mcpReadResource('app://{{ uriName }}'); + + $this->assertMcpResourceContains('# {{ className }}'); + $this->assertMcpResourceListed('app://{{ uriName }}'); + } +} 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/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/Conformance/MemoryConnectionStore.php b/tests/Conformance/MemoryConnectionStore.php new file mode 100644 index 0000000..536c8f9 --- /dev/null +++ b/tests/Conformance/MemoryConnectionStore.php @@ -0,0 +1,108 @@ + + */ + private array $connections = []; + + /** + * @var array + */ + private array $registrations = []; + + /** + * @inheritDoc + */ + public function get(string $client, string $userId): ?StoredConnection + { + return $this->connections[$client . "\0" . $userId] ?? null; + } + + /** + * @inheritDoc + */ + public function save(StoredConnection $connection): void + { + $this->connections[$connection->client . "\0" . $connection->userId] = $connection; + } + + /** + * @inheritDoc + */ + public function saveRefreshed(StoredConnection $connection, string $claimId): bool + { + $this->save($connection); + + return true; + } + + /** + * @inheritDoc + */ + public function markStepUp(string $client, string $userId, string $scope): void + { + $stored = $this->get($client, $userId); + if ($stored !== null) { + $this->save($stored->withStepUp(explode(' ', $scope))); + } + } + + /** + * @inheritDoc + */ + public function delete(string $client, string $userId): void + { + unset($this->connections[$client . "\0" . $userId]); + } + + /** + * @inheritDoc + */ + public function claimRefresh(string $client, string $userId, string $claimId, int $leaseSeconds): bool + { + return true; + } + + /** + * @inheritDoc + */ + public function releaseRefresh(string $client, string $userId, string $claimId): void + { + } + + /** + * @inheritDoc + */ + public function registration(string $client, string $issuer): ?Registration + { + return $this->registrations[$client . "\0" . $issuer] ?? null; + } + + /** + * @inheritDoc + */ + public function saveRegistration(Registration $registration): void + { + $this->registrations[$registration->client . "\0" . $registration->issuer] = $registration; + } + + /** + * @inheritDoc + */ + public function deleteRegistration(string $client, string $issuer): void + { + unset($this->registrations[$client . "\0" . $issuer]); + } +} diff --git a/tests/Conformance/baseline-client-2025-11-25.yml b/tests/Conformance/baseline-client-2025-11-25.yml new file mode 100644 index 0000000..de44a9d --- /dev/null +++ b/tests/Conformance/baseline-client-2025-11-25.yml @@ -0,0 +1,11 @@ +# Client scenarios of the official conformance suite expected to fail at 2025-11-25, with the reason. +client: + # The plugin's MCP client does not answer elicitation requests (no user to ask in a PHP request). + - elicitation-sep1034-client-defaults + # The plugin's client id is the URL of its own client.json route, not the one the suite names, and the suite + # cannot fetch a document on this machine. + - auth/basic-cimd + # The client learns the first scope from the 401 of its unauthenticated probe (initialize); this server lets the + # probe through and challenges later calls, so the first sign-in asks for scopes_supported and the server keeps + # answering 403. + - auth/scope-step-up diff --git a/tests/Conformance/baseline-client-2026-07-28.yml b/tests/Conformance/baseline-client-2026-07-28.yml new file mode 100644 index 0000000..9936baa --- /dev/null +++ b/tests/Conformance/baseline-client-2026-07-28.yml @@ -0,0 +1,14 @@ +# Client scenarios of the official conformance suite expected to fail at 2026-07-28, with the reason. +client: + # The SDK (mcp/sdk) does not retry server/discover with a version the server lists in its + # UnsupportedProtocolVersion error: not the plugin's code. + - request-metadata + # The plugin's client id is the URL of its own client.json route, not the one the suite names. + - auth/basic-cimd + # The first scope comes from the 401 of the probe; this server challenges server/discover with 403, and the SDK's + # handshake fallback after it fails (see the 2025-11-25 baseline). + - auth/scope-step-up + # The plugin's MCP client does not answer input requests (elicitation, sampling) of an InputRequiredResult. + - sep-2322-client-request-state + # The SDK (mcp/sdk) leaves out the Mcp-Param header of an empty string value: not the plugin's code. + - http-custom-headers:sep-2243-client-mirrors-designated-params diff --git a/tests/Conformance/client.php b/tests/Conformance/client.php new file mode 100644 index 0000000..cd2322f --- /dev/null +++ b/tests/Conformance/client.php @@ -0,0 +1,130 @@ +` with MCP_CONFORMANCE_SCENARIO, MCP_CONFORMANCE_PROTOCOL_VERSION and, for some + * scenarios, MCP_CONFORMANCE_CONTEXT (JSON) set, and checks what the client sends to its scenario server. + * + * The auth scenarios run the user mode sign-in without a browser: the suite's authorization server approves at + * once, so the authorization URL answers with a redirect to the callback, whose query completes the sign-in. + * Their servers are on localhost over plain http, so the client allows that (`allowPrivateNetwork`, + * `allowInsecure`), which a real deployment would not. + */ + +use Cake\Core\Configure; +use Cake\Http\Client; +use Cake\Routing\Router; +use CakeDC\Mcp\Client\ClientConfig; +use CakeDC\Mcp\Client\ClientRegistry; +use CakeDC\Mcp\Client\Exception\NotConnectedException; +use CakeDC\Mcp\Client\McpClients; +use CakeDC\Mcp\Client\OAuth\ClientMetadataDocument; +use CakeDC\Mcp\Client\UserConnection; +use CakeDC\Mcp\McpPlugin; +use CakeDC\Mcp\Test\Conformance\MemoryConnectionStore; +use Mcp\Exception\ExceptionInterface; + +require dirname(__DIR__, 2) . '/vendor/autoload.php'; +require __DIR__ . '/MemoryConnectionStore.php'; + +const USER = 'conformance-user'; + +$url = $argv[$argc - 1] ?? ''; +$scenario = (string)getenv('MCP_CONFORMANCE_SCENARIO'); +$version = getenv('MCP_CONFORMANCE_PROTOCOL_VERSION'); +$context = json_decode((string)getenv('MCP_CONFORMANCE_CONTEXT'), true); +$context = is_array($context) ? $context : []; +$auth = str_starts_with($scenario, 'auth/'); + +Configure::write('Mcp.client', ['name' => 'cakephp-mcp-conformance', 'version' => '1.0.0']); +$config = [ + 'url' => $url, + 'timeout' => 20, + 'protocolVersion' => is_string($version) && $version !== '' ? $version : null, +]; +if ($auth) { + $config += ['auth' => 'user', 'allowPrivateNetwork' => true, 'allowInsecure' => true]; + foreach (['client_id' => 'clientId', 'client_secret' => 'clientSecret'] as $from => $to) { + if (is_string($context[$from] ?? null)) { + $config[$to] = $context[$from]; + } + } + if (isset($config['clientSecret']) && is_string($context['issuer'] ?? null)) { + $config['issuer'] = $context['issuer']; + } +} +Configure::write('Mcp.clients.conformance', array_filter($config, fn(mixed $value): bool => $value !== null)); +McpClients::setRegistry(new ClientRegistry(null, new MemoryConnectionStore())); +// The connect, callback and client.json routes, on a base URL the authorization server can fetch for the Client +// ID Metadata Document scenario (it does not fetch it). +Router::reload(); +Router::fullBaseUrl($scenario === 'auth/basic-cimd' ? 'https://conformance.example.com' : 'http://localhost:3000'); +(new McpPlugin())->routes(Router::createRouteBuilder('/')); + +/** + * Signs the user in: the authorization URL, its redirect to the callback, and the code exchange. + */ +$signIn = function (): void { + $callback = ClientMetadataDocument::callbackUrl(ClientConfig::fromConfig('conformance')); + [$pending, $authorize] = McpClients::registry()->flow('conformance')->start(USER, $callback, '/'); + $response = (new Client(['redirect' => 0, 'timeout' => 20]))->get($authorize); + $location = $response->getHeaderLine('Location'); + parse_str((string)parse_url($location, PHP_URL_QUERY), $query); + McpClients::registry()->flow('conformance')->complete($pending, array_map('strval', $query)); +}; + +/** + * Runs $work for the user, signing in first when needed, and again (at most twice) when the server asks for + * more scope. + */ +$asUser = function (callable $work) use ($signIn): void { + $user = McpClients::get('conformance')->for(USER); + for ($attempt = 0;; $attempt++) { + try { + $work($user); + + return; + } catch (NotConnectedException) { + if ($attempt > 2) { + throw new RuntimeException('Still not connected after signing in.'); + } + $signIn(); + } catch (ExceptionInterface $e) { + if (!$user instanceof UserConnection || !$user->needsMoreScope() || $attempt > 2) { + throw $e; + } + $signIn(); + } + } +}; + +$work = function ($client) use ($scenario, $context): void { + $tools = $client->listTools(); + if (is_array($context['toolCalls'] ?? null)) { + foreach ($context['toolCalls'] as $call) { + $client->callTool((string)$call['name'], (array)($call['arguments'] ?? [])); + } + } elseif ($scenario === 'tools_call') { + $client->callTool('add_numbers', ['a' => 2, 'b' => 3]); + } elseif ($scenario === 'json-schema-2020-12-preservation') { + foreach ($tools as $tool) { + if ($tool->name === 'json_schema_2020_12_tool') { + $client->callTool('json_schema_echo', ['schema' => $tool->inputSchema]); + } + } + } elseif ($scenario !== 'initialize') { + // Exercise every tool once, with no arguments. + foreach ($tools as $tool) { + $client->callTool($tool->name); + } + } +}; + +try { + $auth ? $asUser($work) : $work(McpClients::get('conformance')); + McpClients::closeAtShutdown(); +} catch (Throwable $e) { + fwrite(STDERR, $e::class . ': ' . $e->getMessage() . "\n"); + exit(1); +} diff --git a/tests/Conformance/run-client.sh b/tests/Conformance/run-client.sh new file mode 100755 index 0000000..38fd18b --- /dev/null +++ b/tests/Conformance/run-client.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# +# Runs the client side of the official MCP conformance suite against the plugin's MCP client (client.php). The +# suite starts its own scenario servers, so no Docker is needed: Node 22, PHP and the Composer dependencies. +# +# tests/Conformance/run-client.sh both protocol revisions +# tests/Conformance/run-client.sh 2026-07-28 one revision + +set -uo pipefail + +cd "$(dirname "$0")" + +PACKAGE="${CONFORMANCE_PACKAGE:-@modelcontextprotocol/conformance@alpha}" +if [ $# -gt 0 ]; then + SPECS=("$@") +else + SPECS=(2025-11-25 2026-07-28) +fi + +rm -rf results-client +status=0 +for spec in "${SPECS[@]}"; do + echo "== Conformance: client, ${spec} ==" + npx --yes "$PACKAGE" client \ + --command "php $(pwd)/client.php" \ + --suite all \ + --spec-version "$spec" \ + --expected-failures "baseline-client-${spec}.yml" \ + --output-dir "results-client/${spec}" || status=1 +done + +exit $status diff --git a/tests/Support/CountingTool.php b/tests/Support/CountingTool.php new file mode 100644 index 0000000..3aefc97 --- /dev/null +++ b/tests/Support/CountingTool.php @@ -0,0 +1,20 @@ +calls; + } +} diff --git a/tests/Support/DelegatingRegistry.php b/tests/Support/DelegatingRegistry.php new file mode 100644 index 0000000..b938f51 --- /dev/null +++ b/tests/Support/DelegatingRegistry.php @@ -0,0 +1,174 @@ +listPages ? new Page(array_values($page->references), $page->nextCursor) : $page; + } + + public function registerTool(Tool $tool, callable|array|string $handler): ToolReference + { + return $this->inner->registerTool($tool, $handler); + } + + public function registerResource(ResourceDefinition $resource, callable|array|string $handler): ResourceReference + { + return $this->inner->registerResource($resource, $handler); + } + + public function registerResourceTemplate( + ResourceTemplate $template, + callable|array|string $handler, + array $completionProviders = [], + ): ResourceTemplateReference { + return $this->inner->registerResourceTemplate($template, $handler, $completionProviders); + } + + public function registerPrompt( + Prompt $prompt, + callable|array|string $handler, + array $completionProviders = [], + ): PromptReference { + return $this->inner->registerPrompt($prompt, $handler, $completionProviders); + } + + public function unregisterTool(string $name): void + { + $this->inner->unregisterTool($name); + } + + public function unregisterResource(string $uri): void + { + $this->inner->unregisterResource($uri); + } + + public function unregisterResourceTemplate(string $uriTemplate): void + { + $this->inner->unregisterResourceTemplate($uriTemplate); + } + + public function unregisterPrompt(string $name): void + { + $this->inner->unregisterPrompt($name); + } + + public function publishesListChanges(): bool + { + return $this->inner->publishesListChanges(); + } + + public function hasTool(string $name): bool + { + return $this->inner->hasTool($name); + } + + public function hasResource(string $uri): bool + { + return $this->inner->hasResource($uri); + } + + public function hasResourceTemplate(string $uriTemplate): bool + { + return $this->inner->hasResourceTemplate($uriTemplate); + } + + public function hasPrompt(string $name): bool + { + return $this->inner->hasPrompt($name); + } + + public function hasTools(): bool + { + return $this->inner->hasTools(); + } + + public function getTools(?int $limit = null, ?string $cursor = null): Page + { + return $this->page($this->inner->getTools($limit, $cursor)); + } + + public function getTool(string $name): ToolReference + { + return $this->inner->getTool($name); + } + + public function hasResources(): bool + { + return $this->inner->hasResources(); + } + + public function getResources(?int $limit = null, ?string $cursor = null): Page + { + return $this->page($this->inner->getResources($limit, $cursor)); + } + + public function getResource(string $uri, bool $includeTemplates = true): ResourceReference|ResourceTemplateReference + { + return $this->inner->getResource($uri, $includeTemplates); + } + + public function hasResourceTemplates(): bool + { + return $this->inner->hasResourceTemplates(); + } + + public function getResourceTemplates(?int $limit = null, ?string $cursor = null): Page + { + return $this->page($this->inner->getResourceTemplates($limit, $cursor)); + } + + public function getResourceTemplate(string $uriTemplate): ResourceTemplateReference + { + return $this->inner->getResourceTemplate($uriTemplate); + } + + public function hasPrompts(): bool + { + return $this->inner->hasPrompts(); + } + + public function getPrompts(?int $limit = null, ?string $cursor = null): Page + { + return $this->page($this->inner->getPrompts($limit, $cursor)); + } + + public function getPrompt(string $name): PromptReference + { + return $this->inner->getPrompt($name); + } +} diff --git a/tests/Support/FakeOAuthServer.php b/tests/Support/FakeOAuthServer.php new file mode 100644 index 0000000..bdaae81 --- /dev/null +++ b/tests/Support/FakeOAuthServer.php @@ -0,0 +1,206 @@ +> + */ + 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; + + /** + * Whether token answers leave `scope` out (RFC 6749 5.1: then the scope granted is the one asked for). + */ + public bool $omitScope = 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'], + // The application, for its client metadata document. + 'app.example.com' => ['93.184.216.36'], + ]); + $this->guarded = new ScriptedGuardedTransport(); + $this->resourceMetadata([ + '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 MCP server's protected resource metadata at RESOURCE_METADATA, on the MCP server's own origin + * (read like the configured url) and through the guard (as an address the server named). + * + * @param array $document The document. + * @return void + */ + public function resourceMetadata(array $document): void + { + $this->mcp->documents[self::RESOURCE_METADATA] = $document; + $this->guarded->json(self::RESOURCE_METADATA, $document); + } + + /** + * 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. + * @param \Closure|null $sleep `fn(int $microseconds): void` while another request refreshes; no wait by default. + * @return \CakeDC\Mcp\Client\ClientRegistry A registry on these doubles. + */ + public function registry(?ConnectionStoreInterface $store = null, ?Closure $sleep = null): ClientRegistry + { + return new ClientRegistry( + new FixedHttpClientFactory($this->mcp), + $store ?? new TableConnectionStore(), + new GuardedHttp(new EndpointGuard($this->dns), $this->guarded, 1024 * 1024), + $sleep ?? function (): void { + }, + $this->dns, + ); + } + + /** + * @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