servers = $servers ?? new ServerSettings(); } public function routes(): array { return [ ['path' => '/settings', 'methods' => 'GET', 'callback' => [$this, 'show'], 'capability' => 'settings.read', 'args' => ['reveal' => ['type' => 'boolean', 'default' => false]]], ['path' => '/settings', 'methods' => 'PUT', 'callback' => [$this, 'update'], 'capability' => 'settings.write'], ['path' => '/settings/schema', 'methods' => 'GET', 'callback' => [$this, 'schema'], 'capability' => 'settings.read'], ]; } /** * These three routes resolve their Settings › Access row rather than the base's * `alpaca_bot/capability/{route}`: accessRow() hands the row to Access::effective(), which * applies 0.5's `alpaca_bot/capability/settings` over the stored row and then the row's own * key, and that chain is the whole of the split. * * `$declared` is what the route table carries — a row name for all three of today's routes — * so the verb is read off the table rather than off the request: the GET and the PUT share a * path, and `routeKey()` would hand both the one key again. * * Only a row Access declares is resolved as one. A route added here that names a plain * capability falls through to the base and is authorised like every other route in the * plugin, `alpaca_bot/capability/{route}` and all. Without that test it would be handed to * Access::effective() as if it were a row: an undeclared row fails closed to * `manage_options`, so the route would quietly be authorised at that rather than at what it * declared, and the only filter it offered a site would be one named after the *declared * capability* — Access::hook() builds the name from the token it is handed, so a route * declaring `edit_posts` would fire `alpaca_bot/capability/edit_posts`, a hook nobody * documents, since bin/hooks-doc.php reads string literals and this name is built at runtime. * The check is against Access::defaults() rather than a list kept here so that a row the access * model declares a default for is usable from this table the day it exists. That is every row * but `mcp.`, which exists only once a server does and is deliberately not in * defaults(); such a row would fall through to the base, and no route here wants one. * * What Access resolves is returned as it comes, and is never handed back to * parent::capability() as its `$declared` — the fallback above passes the route's *declared* * value, never a resolved one. That is deliberate rather than a shortcut. The base reads `$declared` * for Controller::CHAT, which is the literal string 'chat', while a site's * `alpaca_bot/capability/settings/read` filter may return any capability name it likes — * 'chat' among them, since Capability::filtered() honours every non-empty non-numeric string. * Routing a resolved capability back through that comparison would let such a filter flip a * settings route onto the Chat row; returning here means a capability name can never be read * as the sentinel. It also means these routes apply no `{route}` filter at all, which is what * retires `alpaca_bot/capability/settings/schema` and keeps `alpaca_bot/capability/settings` * to the one application Access makes of it. * * A controller nobody handed an Access — a test, a site building one by hand — resolves the * row to Access::defaults() instead, `manage_options` for both; accessRow() answers that case * once, in the base, so nothing here builds a second Access over the same Store. * * @since 0.6.0 */ protected function capability(string $route, string $declared, \WP_REST_Request $request): string { return isset(Access::defaults()[$declared]) ? $this->accessRow($declared, $request) : parent::capability($route, $declared, $request); } public function show(\WP_REST_Request $request): \WP_REST_Response { if ((bool) $request->get_param('reveal') && current_user_can('manage_options')) { $settings = $this->store->all(); if (is_array($settings['toolkits.mcp_servers'] ?? null)) { foreach ($settings['toolkits.mcp_servers'] as $i => $row) { if (is_array($row)) { $settings['toolkits.mcp_servers'][$i]['header_value'] = Secrets::resolve($row); } } } $response = new \WP_REST_Response($settings); $response->header('Cache-Control', 'no-store'); return $response; } return new \WP_REST_Response($this->masked($this->store->all())); } public function update(\WP_REST_Request $request): \WP_REST_Response|\WP_Error { $input = array_intersect_key($request->get_params(), Schema::fields()); if ($input === []) { return Errors::badRequest(__('No settings were sent. Send a JSON body of dotted keys, e.g. {"models.temperature": 0.7}.', 'alpaca-bot')); } $cleared = []; if (array_key_exists('toolkits.mcp_servers', $input)) { $stored = $this->store->get('toolkits.mcp_servers'); $dropped = self::droppedRows($input['toolkits.mcp_servers'], $stored); if ($dropped !== []) { $lines = []; foreach ($dropped as $row) { /* translators: %s: the row's index in the posted list */ $name = $row['url'] === '' ? sprintf(__('row %s', 'alpaca-bot'), $row['index']) : $row['url']; /* translators: 1: an MCP server's URL, or which row it is, 2: why the row cannot be kept */ $lines[] = sprintf(__('%1$s: %2$s', 'alpaca-bot'), $name, $row['reason']); } return Errors::badRequest(__('Nothing was saved: an MCP server row could not be kept.', 'alpaca-bot') . ' ' . implode(' ', $lines), 'alpaca_bot_mcp_row', ['rows' => $dropped]); } $rows = Schema::sanitizeMcpServers($input['toolkits.mcp_servers'], $stored); $refused = $this->servers->refusals($rows, $stored); if ($refused !== []) { // Nothing is written, so no write's action clears what passed on the way. $this->servers->forgetPassed(); $reasons = []; foreach ($refused as $i => $reason) { /* translators: 1: an MCP server's URL, 2: why its address was refused */ $reasons[] = sprintf(__('%1$s: %2$s', 'alpaca-bot'), $rows[$i]['url'], $reason); } return Errors::badRequest(__('Nothing was saved: an MCP server\'s address did not pass the check.', 'alpaca-bot') . ' ' . implode(' ', $reasons), 'alpaca_bot_mcp_address'); } $cleared = $this->servers->clearedByMove($rows, $stored); } $this->store->replace($input); $response = new \WP_REST_Response($this->masked($this->store->all())); if ($cleared !== []) { $response->header('X-Alpaca-Bot-Mcp-Cleared', implode(',', $cleared)); } return $response; } /** * The rows of a posted `toolkits.mcp_servers` that the schema would drop and that a PUT must * not lose quietly: one that names a stored server's id, and a new one with a URL. A row whose * `remove` is ticked, and a blank row, are not among them (Schema::droppedMcpRows()). Each is * `{index, id, url, reason}`: its key in the posted list, the id it posted when that is a * string, the URL it posted with any user name and password taken out * (Schema::withoutUserinfo()), so a refused credential is not answered back, and why. The * header value is not read. * * @return list */ private static function droppedRows(#[\SensitiveParameter] mixed $raw, mixed $stored): array { $storedIds = Schema::serverIds($stored); $out = []; foreach (Schema::droppedMcpRows($raw) as $key => $fault) { /** @var array $row droppedMcpRows() lists arrays only */ $row = is_array($raw) ? $raw[$key] : []; $id = is_string($row['id'] ?? null) ? $row['id'] : null; $url = is_string($row['url'] ?? null) ? Schema::withoutUserinfo($row['url']) : ''; if (!in_array($id, $storedIds, true) && trim($url) === '') { continue; } $prefix = is_string($row['prefix'] ?? null) ? $row['prefix'] : ''; $out[] = ['index' => $key, 'id' => $id, 'url' => $url, 'reason' => match ($fault) { 'url' => __('the URL has to be https with a host.', 'alpaca-bot'), 'userinfo' => __('the URL may not carry a user name or password; send a credential as the header value, which reads back masked.', 'alpaca-bot'), /* translators: %s: what a header name has to be (Schema::mcpHeaderNameRule()) */ 'header' => sprintf(__('the header name has to be %s.', 'alpaca-bot'), Schema::mcpHeaderNameRule()), /* translators: %s: what a prefix has to be (Schema::mcpPrefixRule()) */ 'prefix' => sprintf(__('the prefix has to be %s.', 'alpaca-bot'), Schema::mcpPrefixRule()), /* translators: %s: a tool-name prefix */ 'taken' => sprintf(__('the prefix %s is already used by an earlier row of this request.', 'alpaca-bot'), $prefix), }]; } return $out; } /** * Schema::sections() and Schema::fields() as data: the `sanitize` callables are dropped (they * are server-side and would only serialise as a class name), a secret field is flagged * `secret` so a form renders it as a password input and knows the mask applies, and the mask * itself is named so the client compares against the same string this controller does. */ public function schema(\WP_REST_Request $request): \WP_REST_Response { $fields = []; foreach (Schema::fields() as $key => $field) { unset($field['sanitize']); if (in_array($key, Schema::SECRETS, true)) { $field['secret'] = true; } if ($key === 'toolkits.mcp_servers') { $field['secret_fields'] = ['header_value']; } $fields[$key] = $field; } return new \WP_REST_Response(['sections' => Schema::sections(), 'fields' => $fields, 'mask' => Schema::MASK]); } /** * @param array $settings * @return array */ private function masked(array $settings): array { foreach (Schema::SECRETS as $key) { if (($settings[$key] ?? '') !== '') { $settings[$key] = Schema::MASK; } } if (array_key_exists('toolkits.mcp_servers', $settings)) { $settings['toolkits.mcp_servers'] = Schema::maskedServers($settings['toolkits.mcp_servers']); } return $settings; } }