diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..5cfc2ea --- /dev/null +++ b/.gitattributes @@ -0,0 +1,8 @@ +# Kept out of the archives Composer installs. +/.github export-ignore +/tests export-ignore +/.gitattributes export-ignore +/.gitignore export-ignore +/phpcs.xml export-ignore +/phpstan.neon export-ignore +/phpunit.xml.dist export-ignore diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..591d039 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,76 @@ +name: CI + +on: + push: + branches: ['1.next-cake4'] + pull_request: + +permissions: + contents: read + +jobs: + testsuite: + runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + php-version: ['8.2', '8.3'] + dependencies: ['highest'] + include: + - php-version: '8.2' + dependencies: 'lowest' + name: PHP ${{ matrix.php-version }} (${{ matrix.dependencies }}) + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + path: cakephp-mcp + - uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 + with: + php-version: ${{ matrix.php-version }} + extensions: mbstring, intl, pdo_sqlite, openssl + coverage: none + - uses: ramsey/composer-install@a8d0d959dab41457692a5e2041bd9b757a119e3f # 3.2.1 + with: + dependency-versions: ${{ matrix.dependencies }} + working-directory: cakephp-mcp + - run: vendor/bin/phpunit + working-directory: cakephp-mcp + + cs-stan: + runs-on: ubuntu-24.04 + name: Coding standard and static analysis + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + path: cakephp-mcp + - uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 + with: + php-version: '8.3' + coverage: none + - uses: ramsey/composer-install@a8d0d959dab41457692a5e2041bd9b757a119e3f # 3.2.1 + with: + working-directory: cakephp-mcp + - run: vendor/bin/phpcs + working-directory: cakephp-mcp + - run: vendor/bin/phpstan analyse --no-progress + working-directory: cakephp-mcp + + conformance: + runs-on: ubuntu-24.04 + name: MCP conformance + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + path: cakephp-mcp + - uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 + with: + php-version: '8.3' + coverage: none + - uses: ramsey/composer-install@a8d0d959dab41457692a5e2041bd9b757a119e3f # 3.2.1 + with: + working-directory: cakephp-mcp + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: '22' + - run: tests/Conformance/run.sh + working-directory: cakephp-mcp diff --git a/.gitignore b/.gitignore index 4f38912..4970756 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,7 @@ -.idea -vendor -composer.lock +/vendor/ +/composer.lock +/.phpunit.cache/ +/tests/test_app/tmp/ +.phpunit.result.cache +/tests/Conformance/tmp/ +/tests/Conformance/results/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..d8f43a0 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,80 @@ +# Changelog + +## 1.1.0 (2026-11-19) + +Port of 2.1.1 to CakePHP 4.5+, replacing the 1.x prototype. Require `^1.1`: version 1.0.0 on Packagist is the +CakePHP 5 code of 2.0.0, tagged by mistake. + +- Everything in 2.1.1 except OAuth 2.1: the endpoint for both protocol eras, stdio, tool discovery with constructor injection, `CurrentIdentity`, per-tool authorization and `RbacToolAuthorizer`, the audit log, `bin/cake mcp check`, `bin/cake mcp inspector`, `McpTestTrait` and `ToolError::invalid()`. +- Only `host` mode: the identity set by your authentication (`cakephp/authentication` 2.x) becomes the SDK access token. Any other `Mcp.auth.mode` (`oauth` and `external` are 2.x only) stops the application at bootstrap with the reason. +- Not ported: the protected resource metadata route and its `401` challenge, the scope policy (`Mcp.auth.scopes`, `403 insufficient_scope`), `McpTestTrait::assertMcpInsufficientScope()` and the rate limiting example (CakePHP 4 has no `RateLimitMiddleware`). `mcpActingAs()` still takes scopes and claims, which never refuse a call. +- The SDK gets the PSR-17 factories of `laminas/laminas-diactoros`, which CakePHP 4 already requires. +- `bin/cake mcp check` follows the CakePHP 4 log scopes: the skeleton's `debug` and `error` engines have `'scopes' => false` and take only messages without a scope. +- Requires `mcp/sdk` ^0.9 and `psr/log` ^2.0 or ^3.0. +- Tests on PHPUnit 9; phpcs and PHPStan level 8; the official MCP conformance suite passes for both protocol revisions. +- PHP 8.2 and 8.3: CakePHP 4 needs `laminas/laminas-diactoros` 2.x, which does not install on PHP 8.4. + +The entries below 1.1.0 are the history of the 2.x line (CakePHP 5), kept for reference: their OAuth features are not in 1.x. + +## 2.1.1 (2026-11-07) + +- `bin/cake mcp check` lists the tools the server offers and warns when there is none. +- `bin/cake mcp check` checks the authorizer: with `RbacToolAuthorizer`, it warns when there are no rules, or none for plugin `CakeDC/Mcp` and controller `Tools`, because then no one can call a tool. +- `bin/cake mcp check` warns, in `oauth` and `external` modes, about tools that need no scope and about names in `Mcp.auth.scopes.tools` that are not tools. +- `bin/cake mcp check` warns when no Log engine takes the errors of the `mcp` scope (the skeleton's `debug` and `error` engines do not), so a failing tool would leave no trace. +- `bin/cake mcp check` decides whether the audit lines reach a Log engine as `Log::write()` does: an engine of the `mcp` scope, or one given as an object, now counts. +- `bin/cake mcp check` prints only its results: listing the tools no longer writes the SDK's info lines to the console (warnings and errors still go to the `mcp` log). +- Docs: testing the endpoint with `OAuthTestTrait` links to the oauth plugin's note on the migrations the test database needs. + +## 2.1.0 (2026-11-07) + +- Audit log of MCP calls (`Mcp.audit`), off by default: allowed, denied, failed and refused calls with the identity, client, tool, arguments and duration, to the `mcp_audit` log scope and the `Mcp.audit` event. See the Audit log section of `docs/configuration.md`, which also shows how to store the records in a table. +- `bin/cake mcp check` reports the audit log, and warns when it is on and no Log engine lists the `mcp_audit` scope. +- Fix: a `403 insufficient_scope` reached clients as `401`, because PHP turns any response with a `WWW-Authenticate` header into a 401 when, as in Cake's `ResponseEmitter`, the status line is sent first. The endpoint now keeps the 403 (see the troubleshooting guide). +- Docs: rate limiting the MCP route with CakePHP's `RateLimitMiddleware` (per token, per user or per address). +- Docs: the Logging section said the skeleton's `debug` and `error` engines receive the `mcp` messages; they have `'scopes' => null` and do not. +- Tests: the rate limiting example is skipped on CakePHP before 5.3, which has no `RateLimitMiddleware`. +- Docs: claude.ai custom connectors are now under Customize > Connectors > Add custom connector. + +## 2.0.0 (2026-11-07) + +Complete rewrite for CakePHP 5 on top of the official `mcp/sdk`, with OAuth 2.1 for remote MCP clients. Version +1.0.0 on Packagist was this same code tagged by mistake: require `^2.0`. The 1.x line (`1.next-cake4`) is the +CakePHP 4 plugin. + +### Server + +- Remote MCP over Streamable HTTP at a Cake route (`/mcp` by default), serving both protocol eras (handshake with sessions, and the stateless 2026-07-28 revision). +- `bin/cake mcp server` for stdio. +- `bin/cake mcp inspector` opens the MCP Inspector already configured for this server, over stdio or HTTP. +- Tool discovery through `#[McpTool]`, `#[McpResource]` and `#[McpPrompt]` attributes in `src/Mcp/`, with constructor injection from Cake's container (autowired). +- Sessions and the discovery cache stored in Cake cache configs. +- Authentication delegated to the host: the identity set by `cakephp/authentication` becomes the SDK access token and the injectable `CurrentIdentity`. +- Per-tool authorization with `ToolAuthorizerInterface`; `RbacToolAuthorizer` for `cakedc/auth` permission rules. +- `server.title`, `server.description` and `server.websiteUrl` config keys, reported in the server info. +- `Mcp.server.configure` hands the SDK builder to the host for anything the plugin does not configure itself; the plugin's own settings and the authorizer still apply. +- `McpTestTrait` calls the application's tools in memory from a Cake test case, acting as any identity, with assertions for results, tool errors, JSON-RPC errors, denials and `tools/list`. +- `ToolError::invalid()` turns Cake validation errors (an entity or a `Validator` result) into a tool error the model can read and act on. +- Checked against the official MCP conformance suite for both protocol revisions, behind nginx and php-fpm (`tests/Conformance/run.sh`, also in CI). +- DNS-rebinding protection defaults to the `App.fullBaseUrl` host. That only protects when `App.fullBaseUrl` is set explicitly (the Cake 5 skeleton derives it from the request `Host` otherwise); set `Mcp.http.allowedHosts`, which is required for servers with `identity.required` set to `false`. +- Removed `bin/mcp-server` and `CakeDC\Mcp\Server\CakeServer`. +- Requires `mcp/sdk` ^0.9. + +### OAuth 2.1 for remote clients + +- `Mcp.auth` with three modes: `host` (default, as 2.0), `oauth` (access tokens of `cakedc/cakephp-oauth-server` in the same application) and `external` (JWT access tokens of Auth0, Keycloak, Microsoft Entra ID, WorkOS or any OpenID Connect issuer, through `firebase/php-jwt` and `psr/cache`). The `Mcp.auth` section is validated strictly and fails closed. +- Protected resource metadata (RFC 9728) at `/.well-known/oauth-protected-resource` plus the MCP route, and the `401` challenge that points MCP clients to it. +- Scope policy per method and per tool (`Mcp.auth.scopes`), with `implies` and step-up through `403 insufficient_scope`. +- `McpConfig::isEndpoint()` recognises the MCP route and its metadata path, for the CSRF skip callback and to keep other bearer-token authenticators off them. +- `bin/cake mcp check` inspects the endpoint configuration (authentication, resource, metadata route, allowed hosts, CSRF, authenticators, including the `Auth.Authenticators` of `cakedc/users`) without network calls. +- `McpTestTrait::mcpActingAs()` takes scopes and claims, and `assertMcpInsufficientScope()` asserts a refused call. In `oauth` mode the scopes are expanded with the `implies` of the declared resource, as the authorization server does. +- `McpConfig::rbacPermissions()` returns the `bypassAuth` rule `cakedc/users` hosts need for the endpoint and its metadata. +- oauth mode needs `cakedc/cakephp-oauth-server` 1.0.0 or newer (it brings `cakedc/oauth-server`), CakePHP 5.1.10+ and `cakephp/authentication` 3.3.6+. +- `Mcp.http.maxBodyBytes` (default 4 MiB, the SDK's own limit) bounds the request body. The same value is passed to the SDK transport and to its `AuthorizationMiddleware`. +- A POST over that limit is answered with `413` and a JSON-RPC error (code `-32600`) whose message and `data.maxBodyBytes` name the limit and suggest a smaller payload, before authentication. Before, `oauth` and `external` modes answered it with a `400` Bearer `invalid_request` challenge. +- `bin/cake mcp check` understands a Token authenticator of `cakedc/cakephp-oauth-server` 1.0.0 that protects several resources (`OAuthServer.users.resource` as a list), and passes when one of them is the MCP endpoint at the MCP route. + +### Contributors + +- Contributors: the PHPUnit suite now runs on SQLite with the oauth packages. It needs the sibling clones `../oauth-server` and `../cakephp-oauth-server` (path repositories); both are public repositories, and CI checks them out at their `1.0.0` tags. +- Contributors: `tests/Conformance/run.sh` (and so CI) runs the newest published alpha of the official conformance suite instead of a pinned version; `CONFORMANCE_PACKAGE` still pins one for a reproducible run. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..500dd79 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2025-2026 Cake Development Corporation (https://www.cakedc.com) + +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. diff --git a/README.md b/README.md index 702f6c0..e15fe14 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,130 @@ -# MCP Server for CakePHP +# CakePHP MCP Server -## Installation - * composer require cakedc/cakephp-mcp +Expose tools, resources and prompts from a CakePHP 4 application to Claude and +any other [Model Context Protocol](https://modelcontextprotocol.io) client. +Built on the official [`mcp/sdk`](https://github.com/modelcontextprotocol/php-sdk). -## Usage - * Select one or many methods in your CakePHP project. Add the attribute to expose the method to the MCP server. +This is the 1.x line, for CakePHP 4.5+. The 2.x line (CakePHP 5) also has +OAuth 2.1 for remote clients; see [Not available in 1.x](#not-available-in-1x). +- Remote MCP over Streamable HTTP, mounted as a regular Cake route (`/mcp`). +- `bin/cake mcp server` for local stdio clients, and `bin/cake mcp inspector` to try the server by hand. +- Tools are plain PHP classes with `#[McpTool]` attributes, with constructor injection. +- Authentication stays in your app (`cakephp/authentication`); the plugin reads the identity. +- `bin/cake mcp check` finds what keeps remote clients from connecting, without network calls. +- 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. + +## Requirements + +- PHP 8.2 or 8.3 (CakePHP 4 needs `laminas/laminas-diactoros` 2.x, which stops at PHP 8.3) +- CakePHP 4.5+ +- `cakephp/authentication` 2.x (or any authentication that sets the `identity` request attribute) + +## Install + +```bash +composer require cakedc/cakephp-mcp:^1.1 +``` + +It installs `mcp/sdk` ^0.9, the official PHP SDK. Require `^1.1`: version 1.0.0 +on Packagist is the CakePHP 5 code of 2.0.0, tagged by mistake. + +Load the plugin in `src/Application.php`: + +```php +$this->addPlugin('CakeDC/Mcp'); +``` + +Let MCP requests through CSRF protection (in `Application::middleware()`): + +```php +$csrf = new CsrfProtectionMiddleware(); +$csrf->skipCheckCallback(fn (ServerRequest $request): bool => $request->getPath() === '/mcp'); +``` + +## Your first tool + +Create `src/Mcp/ArticleTools.php`: + +```php +namespace App\Mcp; + +use Cake\ORM\Locator\LocatorAwareTrait; +use Mcp\Capability\Attribute\McpTool; + +class ArticleTools +{ + use LocatorAwareTrait; + + /** + * Lists the titles of the latest articles. + * + * @return list + */ + #[McpTool(name: 'latest_articles')] + public function latest(int $limit = 5): array + { + return $this->fetchTable('Articles')->find() + ->select(['title']) + ->order(['created' => 'DESC']) + ->limit($limit) + ->all() + ->extract('title') + ->toList(); + } +} ``` -example here + +## Authenticate callers + +By default `/mcp` requires an identity. Add an authenticator that reads a Bearer +token, for example with `cakephp/authentication`: + +```php +$service->loadIdentifier('Authentication.Token', ['tokenField' => 'api_token']); +$service->loadAuthenticator('Authentication.Token', [ + 'header' => 'Authorization', + 'tokenPrefix' => 'Bearer', +]); ``` -## Test your MCP server works properly +## Connect Claude + +- Claude Code: `claude mcp add --transport http my-app https://example.com/mcp --header "Authorization: Bearer "` +- claude.ai: Customize > Connectors > Add custom connector, with the URL and (where available) a request header. + +## Not available in 1.x + +The 1.x line is a port of 2.1.1 to CakePHP 4. It leaves out what needs +CakePHP 5 or packages that only exist for it: + +- OAuth 2.1 for remote clients: the `oauth` and `external` values of + `Mcp.auth.mode`, the protected resource metadata + (`/.well-known/oauth-protected-resource`) and its `401` challenge, and the + scope policy (`Mcp.auth.scopes`) with `403 insufficient_scope`. Only `host` + mode is available; any other value stops the application at bootstrap. +- `McpTestTrait::assertMcpInsufficientScope()`. `mcpActingAs()` still takes + scopes and claims, which reach the access token but never refuse a call. +- The rate limiting example, since CakePHP 4 has no `RateLimitMiddleware`. + +Everything else (the endpoint, stdio, tools, authorization, the audit log, +`mcp check`, `mcp inspector` and `McpTestTrait`) is the same as in 2.1.1. + +## Documentation + +- [Installation](docs/installation.md) +- [Configuration](docs/configuration.md) +- [Writing tools](docs/tools.md) +- [Authentication](docs/authentication.md) +- [Authorization](docs/authorization.md) +- [Testing your tools](docs/testing.md) +- [stdio](docs/stdio.md) +- [Connecting clients](docs/clients.md) +- [Troubleshooting](docs/troubleshooting.md) +- [Protocol conformance](docs/conformance.md) + +## License + +MIT. Copyright (c) Cake Development Corporation. diff --git a/bin/mcp-server b/bin/mcp-server deleted file mode 100755 index df5b343..0000000 --- a/bin/mcp-server +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/env php -info('Starting CakePHP MCP Server...'); - -$root = dirname(__DIR__, 4); -$server = \CakeDC\Mcp\Server\CakeServer::builder(new \App\Application($root . '/config')) - ->setServerInfo('CakePHP MCP Server', '1.0.0', 'CakePHP MCP Server') - ->setContainer(container()) - ->setLogger(logger()) - ->setDiscovery($root, ['./src']) - ->build(); - -$transport = new StdioTransport(logger: logger()); - -$server->connect($transport); - -$transport->listen(); -logger()->info('Server listener has been successfully stopped.'); diff --git a/composer.json b/composer.json index cdfba59..f138891 100644 --- a/composer.json +++ b/composer.json @@ -1,23 +1,56 @@ { "name": "cakedc/cakephp-mcp", - "description": "MCP server for CakePHP", + "description": "Model Context Protocol (MCP) server for CakePHP: expose tools, resources and prompts to Claude and other MCP clients over HTTP or stdio", + "type": "cakephp-plugin", + "license": "MIT", + "keywords": ["cakephp", "mcp", "model context protocol", "ai", "claude", "llm"], + "authors": [ + { + "name": "Cake Development Corporation", + "homepage": "https://www.cakedc.com" + } + ], + "require": { + "php": "~8.2.0 || ~8.3.0", + "cakephp/cakephp": "^4.5", + "laminas/laminas-diactoros": "^2.2", + "mcp/sdk": "^0.9", + "psr/log": "^2.0 || ^3.0", + "symfony/finder": "^6.4 || ^7.0 || ^8.0" + }, + "require-dev": { + "cakedc/auth": "^9.1", + "cakephp/authentication": "^2.10", + "cakephp/cakephp-codesniffer": "^5.1", + "phpstan/phpstan": "^2.1", + "phpunit/phpunit": "^9.6" + }, + "suggest": { + "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" + }, "autoload": { "psr-4": { "CakeDC\\Mcp\\": "src/" } }, - "require": { - "php": ">8.2", - "mcp/sdk": "dev-feature/compat-psr-message-1", - "cakephp/cakephp": "^4.0" + "autoload-dev": { + "psr-4": { + "CakeDC\\Mcp\\Test\\": "tests/", + "TestApp\\": "tests/test_app/src/" + } }, - "bin": [ - "bin/mcp-server" - ], - "repositories": { - "mcp-sdk": { - "type": "vcs", - "url": "git@github.com:steinkel/php-sdk.git" + "scripts": { + "test": "phpunit", + "cs-check": "phpcs --colors -p", + "cs-fix": "phpcbf --colors -p", + "stan": "phpstan analyse --no-progress" + }, + "config": { + "sort-packages": true, + "allow-plugins": { + "dealerdirect/phpcodesniffer-composer-installer": true, + "php-http/discovery": false } } } diff --git a/config/bootstrap.php b/config/bootstrap.php deleted file mode 100644 index 1e93bdd..0000000 --- a/config/bootstrap.php +++ /dev/null @@ -1,57 +0,0 @@ -critical('Uncaught exception: '.$t->getMessage(), ['exception' => $t]); - - exit(1); -}); - -function logger(): LoggerInterface -{ - return new class extends AbstractLogger { - public function log($level, Stringable|string $message, array $context = []): void - { - $debug = $_SERVER['DEBUG'] ?? false; - - if (!$debug && 'debug' === $level) { - return; - } - - $logMessage = sprintf( - "[%s] %s %s\n", - strtoupper($level), - $message, - ([] === $context || !$debug) ? '' : json_encode($context), - ); - - if (($_SERVER['FILE_LOG'] ?? false) || !defined('STDERR')) { - file_put_contents('dev.log', $logMessage, \FILE_APPEND); - } else { - fwrite(\STDERR, $logMessage); - } - } - }; -} - -function container(): Container -{ - $container = new Container(); - $container->set(LoggerInterface::class, logger()); - - return $container; -} diff --git a/docs/authentication.md b/docs/authentication.md new file mode 100644 index 0000000..c977aff --- /dev/null +++ b/docs/authentication.md @@ -0,0 +1,139 @@ +# Authentication + +The plugin does not authenticate anyone itself. Your application does, with the +tools it already uses (`cakephp/authentication`, `cakedc/users`, and so on), +and the plugin reads the result. + +## The identity contract + +`IdentityMiddleware` looks for the identity in the request attribute named by +`Mcp.identity.attribute` (default `identity`, which is what +`cakephp/authentication` sets). When it finds one it: + +- stores it as the `CurrentIdentity` that tools can inject; +- gives the SDK an access token whose `sub` claim is the identity's id. + +The id is taken from `getIdentifier()` when the identity has that method +(`Authentication\Identity`), otherwise from the `id` key of an array, +`ArrayObject` or entity. + +`Mcp.identity.required` (default `true`) decides what happens without an +identity. With `false`, unauthenticated calls go through and tools see no +identity. + +## Bearer tokens + +Add a token authenticator to your authentication service. With a token column +on your users table: + +```php +public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface +{ + $service = new AuthenticationService(); + $service->loadIdentifier('Authentication.Token', ['tokenField' => 'api_token']); + $service->loadAuthenticator('Authentication.Token', [ + 'header' => 'Authorization', + 'tokenPrefix' => 'Bearer', + ]); + + return $service; +} +``` + +For tokens that are not a column on one table, use a callback identifier: + +```php +$service->loadIdentifier('Authentication.Callback', [ + 'callback' => fn (array $data): ?ArrayObject => $this->tokens->identityFor($data['token'] ?? null), +]); +$service->loadAuthenticator('Authentication.Token', [ + 'header' => 'Authorization', + 'tokenPrefix' => 'Bearer', +]); +``` + +The authenticator is not tied to the MCP path, so the rest of your app keeps +working as before. + +## Scopes + +`Mcp.identity.scopes` can map an identity to the scope strings the SDK access +token carries: + +```php +Configure::write('Mcp.identity.scopes', fn (mixed $identity): array => ['articles:read']); +``` + +Tools read them with `RequestContext::getAccessToken()?->getScopes()`; see +[Writing tools](tools.md). + +## Missing identity + +When an identity is required and the request has none, the response is: + +``` +HTTP/1.1 401 Unauthorized +WWW-Authenticate: Bearer +Content-Type: application/json + +{"error":"unauthorized","error_description":"Authentication required."} +``` + +CORS preflight requests (OPTIONS) carry no credentials and are never +challenged. + +## cakedc/auth and cakedc/users + +Applications built on `cakedc/auth` or `cakedc/users` already put the identity +in the `identity` attribute, so the plugin reads it unchanged. Two defaults of +`cakedc/users` get in the way of the endpoint, though, and need configuration: + +1. `cakedc/users` loads `RequestAuthorizationMiddleware` with `RbacPolicy`, which + authorizes the route before the controller runs. The plugin's + `skipAuthorization()` call never gets a chance, and an anonymous request is + redirected to the login page instead of receiving the plugin's 401. Add a + permission rule for the endpoint 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: + + ```php + // config/permissions.php + use CakeDC\Mcp\McpConfig; + + return [ + 'CakeDC/Auth.permissions' => array_merge(McpConfig::rbacPermissions(), [ + // ... your rules + ]), + ]; + ``` + + It is this rule, which you can also write by hand: + + ```php + [ + 'role' => '*', + 'plugin' => 'CakeDC/Mcp', + 'controller' => 'Mcp', + 'action' => 'handle', + 'bypassAuth' => true, + ], + ``` + +2. The default `Token` authenticator of `cakedc/users` reads the `api_key` query + parameter (`'header' => null`, `'queryParam' => 'api_key'`), not the + `Authorization` header. Configure a header based Bearer authenticator, as + shown in [Bearer tokens](#bearer-tokens), for example through + `Auth.Authenticators.Token` (`'header' => 'Authorization'`, + `'queryParam' => null`, `'tokenPrefix' => 'Bearer'`). + +The key names above come from `cakedc/users` and `cakedc/auth` as installed in +a local project; check them against the versions you use. To restrict tools by +role, see [Authorization](authorization.md). + +## OAuth + +The 1.x line (CakePHP 4) only has `host` mode: your authentication puts the +identity in the request, as described above. Signing remote clients such as +claude.ai connectors in with OAuth 2.1 (the `oauth` and `external` modes of +`Mcp.auth.mode`) needs cakedc/cakephp-mcp 2.x on CakePHP 5. With 1.x, give +those clients a Bearer token in a request header (see [Clients](clients.md)). diff --git a/docs/authorization.md b/docs/authorization.md new file mode 100644 index 0000000..cff0026 --- /dev/null +++ b/docs/authorization.md @@ -0,0 +1,146 @@ +# Authorization + +Authentication says who is calling. Authorization says which tools that caller +may use. The plugin checks it on every `tools/list` and `tools/call`. + +## The interface + +```php +namespace CakeDC\Mcp\Authorization; + +interface ToolAuthorizerInterface +{ + public function canCall(mixed $identity, string $tool): bool; +} +``` + +`$identity` is the host identity as your authentication produced it (or `null` +when identity is not required and the caller is anonymous). `$tool` is the MCP +tool name. + +The default is `AllowAllToolAuthorizer`: every authenticated caller may use +every tool. + +## A custom authorizer + +```php +namespace App\Mcp; + +use CakeDC\Mcp\Authorization\ToolAuthorizerInterface; + +class StaffOnlyAuthorizer implements ToolAuthorizerInterface +{ + public function canCall(mixed $identity, string $tool): bool + { + if (str_starts_with($tool, 'admin_')) { + return ($identity['role'] ?? null) === 'admin'; + } + + return $identity !== null; + } +} +``` + +Configure it by class name (built through the container, so it can have +injected dependencies) or by instance. The authorizer is chosen only through +`Mcp.authorization.authorizer`; binding `ToolAuthorizerInterface` in the +container is not consulted: + +```php +Configure::write('Mcp.authorization.authorizer', \App\Mcp\StaffOnlyAuthorizer::class); +// or +Configure::write('Mcp.authorization.authorizer', new StaffOnlyAuthorizer()); +``` + +## What a denied caller sees + +- A denied tool is hidden from `tools/list`. +- Calling it anyway gets the same answer as calling a tool that does not + exist: JSON-RPC error `-32602` with the message `Tool not found: "".` + +So callers generally cannot discover which protected tools exist. One +exception: tools whose input schema uses `x-mcp-header` annotations can be told +apart on the stateless (2026-07-28) era, because header validation runs before +the guard. + +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. + +## RbacToolAuthorizer (cakedc/auth) + +If your app uses `cakedc/auth` permissions, install it and select +`RbacToolAuthorizer`: + +```bash +composer require cakedc/auth +``` + +```php +use CakeDC\Mcp\Authorization\RbacToolAuthorizer; + +Configure::write('Mcp.authorization', [ + 'authorizer' => RbacToolAuthorizer::class, + 'rbac' => [ + 'permissions' => [ + // editors may use two tools + [ + 'role' => 'editor', + 'plugin' => 'CakeDC/Mcp', + 'controller' => 'Tools', + 'action' => ['find_order', 'whoami'], + ], + // admins may use all of them + [ + 'role' => 'admin', + 'plugin' => 'CakeDC/Mcp', + 'controller' => 'Tools', + 'action' => '*', + ], + // any role, but only for the user whose id is 1 + [ + 'role' => '*', + 'plugin' => 'CakeDC/Mcp', + 'controller' => 'Tools', + 'action' => 'own_profile', + 'allowed' => fn ($user, $role, $request): bool => ($user['id'] ?? null) === 1, + ], + ], + ], +]); +``` + +Tool `X` is checked as plugin `CakeDC/Mcp`, controller `Tools`, action `X`. +Rules are the same format as `config/permissions.php`, and `Mcp.authorization.rbac` +accepts the same options as the cakedc/auth `Rbac` class (`permissions`, +`permissions_provider_class`, `role_field`, `default_role`, `log`, and so on). +You can also pass a prepared `Rbac` instance to `new RbacToolAuthorizer($rbac)` +and configure the authorizer by instance. + +Identities that are not arrays or `ArrayAccess` objects are denied. + +### Warning: host rules without a plugin key + +cakedc/auth rules only constrain the keys they list. A host rule that has no +`plugin` key, for example: + +```php +['role' => 'admin', 'controller' => '*', 'action' => '*'] +``` + +also grants every MCP tool to admins, because the missing `plugin` matches +anything. Write MCP rules with `'plugin' => 'CakeDC/Mcp', 'controller' => 'Tools'`, +and review the host-wide wildcard rules whenever the MCP rules share a +permissions file with the rest of your application. + +`bin/cake mcp check` warns when the rules it loads are empty, or when none of +them can allow plugin `CakeDC/Mcp` and controller `Tools`: then no one can +call a tool. + +## stdio + +Per-tool authorization is skipped for stdio by default (`Mcp.stdio.trusted`). +See [stdio](stdio.md). diff --git a/docs/clients.md b/docs/clients.md new file mode 100644 index 0000000..14ffe8c --- /dev/null +++ b/docs/clients.md @@ -0,0 +1,71 @@ +# Connecting clients + +## Claude Code over HTTP + +```bash +claude mcp add --transport http my-app https://example.com/mcp \ + --header "Authorization: Bearer " +``` + +Check that it connected with `claude mcp list`, or `/mcp` inside Claude Code. +The server must be reachable from your machine, and its host must be allowed +(`http.allowedHosts`; by default the host of `App.fullBaseUrl`, which only restricts anything when it is set explicitly, so set `http.allowedHosts` for a real deployment). + +For a server running on your own machine you can use the local URL, for +example `https://my-app.ddev.site/mcp`. + +## Claude Code over stdio + +```bash +claude mcp add my-app -- bin/cake mcp server +``` + +See [stdio](stdio.md). + +## claude.ai + +In claude.ai go to Customize > Connectors > Add custom connector, and enter the +URL of your endpoint. Where your account allows custom request headers you can +send the Bearer token there. Connectors that sign people in with OAuth need +cakedc/cakephp-mcp 2.x on CakePHP 5; the 1.x line only reads the identity of +your own authentication. + +## MCP Inspector + +The Inspector is a small web app for trying a server by hand: list the tools, +call them and see the raw JSON-RPC messages, which helps when a client says +only that the connection failed. It needs Node.js 22.19 or later. +`bin/cake mcp inspector` runs version 2 of the Inspector (`@modelcontextprotocol/inspector@2`). + +`bin/cake mcp inspector` opens it already pointed at your server: + +```bash +bin/cake mcp inspector # starts `bin/cake mcp server` over stdio +bin/cake mcp inspector --http --header "Authorization: Bearer " +bin/cake mcp inspector --url https://staging.example.com/mcp --header "Authorization: Bearer " +``` + +- Without options it uses stdio and starts `bin/cake mcp server` (with + `stdio.identity` and `stdio.trusted`). The Inspector starts it with only a + few environment variables (`PATH`, `HOME`, `USER` and similar), so if your + app reads its settings from the environment, pass them by name with + `--env DATABASE_URL --env DEBUG`. Apps configured through `config/.env` or + `app_local.php` need nothing. +- `--http` uses the endpoint at `App.fullBaseUrl` plus `Mcp.route`. If + `App.fullBaseUrl` is not set in the console, pass the URL with `--url`. +- `--header` adds a request header, as `"Name: Value"`. Repeat it for more. +- `--dry-run` prints the Inspector configuration and command instead of + starting it. Header and environment values are shown as `***`. + +The configuration goes to a temporary file only you can read, and it is +deleted when the Inspector stops, also when you stop it with Ctrl+C. On Linux +and macOS that needs PHP's `pcntl` extension, usual in the CLI; without it the +command warns and prints the path to delete. If the PHP process is killed +outright (for example `kill -9`), remove `mcp-inspector-*.json` from the +temporary directory yourself. If the token is wrong, the endpoint answers +401 and the Inspector offers an OAuth sign-in. The 1.x line has no OAuth +sign-in, so check the token instead. + +You can also start the Inspector yourself with +`npx @modelcontextprotocol/inspector`, choose the Streamable HTTP transport, +enter the URL and add the `Authorization: Bearer ` header. diff --git a/docs/configuration.md b/docs/configuration.md new file mode 100644 index 0000000..2dda79e --- /dev/null +++ b/docs/configuration.md @@ -0,0 +1,323 @@ +# Configuration + +All settings live under the `Mcp` key in Configure. You only write what you +want to change; everything else keeps its default. These are the defaults +(`CakeDC\Mcp\McpConfig::DEFAULTS`): + +```php +'Mcp' => [ + 'route' => '/mcp', + 'server' => [ + 'name' => 'CakePHP MCP Server', + 'version' => '1.0.0', + 'title' => null, + 'description' => null, + 'websiteUrl' => null, + 'instructions' => null, + 'configure' => null, + ], + 'discovery' => ['scanDirs' => ['src/Mcp'], 'excludeDirs' => [], 'cache' => '_cake_mcp_'], + 'session' => ['cache' => 'mcp_sessions', 'ttl' => 3600], + 'http' => ['allowedHosts' => null, 'allowedOrigins' => [], 'maxBodyBytes' => 4194304], + 'identity' => ['required' => true, 'attribute' => 'identity', 'scopes' => null], + 'authorization' => ['authorizer' => AllowAllToolAuthorizer::class, 'rbac' => []], + 'auth' => ['mode' => 'host'], + 'stdio' => ['identity' => null, 'trusted' => true], +], +``` + +## 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.instructions`: optional text telling the client's model how to use your server. `null` sends none. +- `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.cache`: name of the cache config for the discovery result. Set it to `null` or an empty string to disable the cache. +- `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 CakePHP 4 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`. +- `http.allowedOrigins`: origins accepted for browser clients, also used for CORS. Empty by default. +- `http.maxBodyBytes`: the largest request body the endpoint reads, in bytes. Default `4194304` (4 MiB, the SDK's own limit). It is passed to the SDK transport and to its `AuthorizationMiddleware`, and a larger POST is answered with `413` and a JSON-RPC error (code `-32600`, `data.maxBodyBytes`) that names the limit, before authentication. Raise it when your tools take large arguments, such as base64 uploads. A value that is not a positive integer makes the endpoint answer `500 Internal error`. +- `identity.required`: answer 401 when the request has no identity. +- `identity.attribute`: request attribute that holds the identity. +- `identity.scopes`: optional `fn (mixed $identity): array` returning scope strings for the SDK access token. +- `authorization.authorizer`: class name or instance of a `ToolAuthorizerInterface`. +- `authorization.rbac`: options for `RbacToolAuthorizer` (the `cakedc/auth` Rbac config). +- `auth`: how the endpoint authenticates remote clients; only `host` in 1.x. See [Mcp.auth](#mcpauth). +- `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). + +## Mcp.auth + +- `auth.mode`: `host`, the only mode of the 1.x line (CakePHP 4): your authentication puts the identity in the request, and the plugin reads it (see [Authentication](authentication.md)). + +The `oauth` and `external` modes of 2.x (OAuth 2.1 access tokens of +`cakedc/cakephp-oauth-server`, or JWT access tokens of a third-party +authorization server) need cakedc/cakephp-mcp 2.x on CakePHP 5. Any other +value of `auth.mode` makes the plugin bootstrap throw, so the application (and +every `bin/cake` command, `mcp check` included) stops with that message, and an +endpoint that still sees such a value answers `500 Internal error`: a security +setting that cannot be honoured never opens anything. + +## Lists replace defaults + +Associative arrays merge with the defaults, but a list replaces the default +list. So this keeps `excludeDirs` and `cache` as they are and only swaps the +scan directories: + +```php +Configure::write('Mcp.discovery.scanDirs', ['src/Mcp', 'plugins/Shop/src/Mcp']); +``` + +The default `src/Mcp` is not scanned any more unless you list it again. + +## Using the SDK builder + +`server.configure` gives you the SDK builder, for what the plugin does not +configure itself: tools registered in code instead of with attributes, resource +templates, a cache policy, request state for multi round-trip tools: + +```php +use Mcp\Server\Builder; + +Configure::write('Mcp.server.configure', function (Builder $builder): void { + $builder->addTool(fn (): string => date('c'), name: 'server_time', description: 'Current server time.'); +}); +``` + +The plugin applies its own settings after the callable, so these always win: +the server info (a `setServerInfo()` call in the callable is ignored; use the +`server.*` keys), container, logger, event dispatcher, session store, and +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. + +## Caches + +If the cache configs named in `discovery.cache` and `session.cache` do not +exist, the plugin creates file caches for them under `CACHE/mcp/` (one hour +default duration). Define your own configs with the same names (for example on +Redis) and the plugin leaves them alone. + +The discovery cache is always off in debug mode. The session cache must be +shared by every PHP worker; see [Troubleshooting](troubleshooting.md). + +## Logging + +The plugin logs through Cake's `Log` with the `mcp` scope. Route those messages +to their own file with a scoped log config: + +```php +use Cake\Log\Engine\FileLog; + +'Log' => [ + 'mcp' => [ + 'className' => FileLog::class, + 'path' => LOGS, + 'file' => 'mcp', + 'scopes' => ['mcp'], + ], +], +``` + +The `debug` and `error` engines of the CakePHP 4 application skeleton have +`'scopes' => false`: they only take messages without a scope, so the `mcp` +messages (and the `mcp_audit` lines of the [audit log](#audit-log)) reach only +the engines that list those scopes. An engine with no `scopes` key at all (or +`'scopes' => []` or `null`) takes every scope. + +## Audit log + +`Mcp.audit` records who called what: every audited call, allowed, denied or +failed, and the calls that authentication refuses. It is off by default. + +```php +'Mcp' => [ + 'audit' => [ + 'enabled' => true, + ], +], +``` + +- `audit.enabled`: record the calls. Default `false`. +- `audit.methods`: the methods recorded, among `tools/call`, `prompts/get` and `resources/read`. Default `['tools/call']`. Listing tools, `initialize`, `ping` and notifications are never recorded. +- `audit.log`: write one log line per call under the `mcp_audit` scope. Default `true`. With `false` only the `Mcp.audit` event is dispatched, for applications that store the records themselves. +- `audit.arguments`: record the call arguments. Default `true`. Arguments can hold personal data, depending on your tools: turn this off, or list the sensitive ones in `audit.redact`. +- `audit.redact`: argument names whose value becomes `"[redacted]"`, at any depth, ignoring case. Default `['password', 'token', 'secret']`. Like every list, yours replaces the default. +- `audit.maxLength`: longest string value kept, in characters; longer ones are cut and end with `...`. Default `200`. The arguments of a record are also capped at 2 KB of JSON, and replaced by `{"truncated": true}` above that. + +An invalid setting stops the endpoint (`500 Internal error`, with the setting +named in the `mcp` log) and makes `bin/cake mcp check` fail. + +### What a record holds + +| Field | Value | +|---|---| +| `method` | `tools/call`, `prompts/get` or `resources/read` | +| `name` | the tool or prompt, or the resource URI, cut to 255 characters | +| `outcome` | see below | +| `identity` | the identifier of the caller, `null` without one | +| `client` | the client of the access token (`client_id`, `azp`, or a single `aud`); always `null` over HTTP in host mode, the only mode of 1.x. Kept so the records have the same fields as in 2.x | +| `session` | the MCP session id | +| `request` | the JSON-RPC request id, cut to 255 characters | +| `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 | + +| 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` | +| `error` | the tool threw, or another JSON-RPC error | `warning` | +| `unauthorized` | `401` from authentication, before the server runs | `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. + +Limits: + +- A refused call (`unauthorized`) has no client, no session and no caller. +- A tool that waits for an answer from the client (elicitation, sampling): + over HTTP it finishes in a later request, so its `durationMs` is `null`; + over stdio it finishes in the same process, and `durationMs` includes the + 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`. +- The access token never appears in a record. +- Over stdio the identity is `stdio.identity`, and a trusted server + (`stdio.trusted`) denies nothing. + +### The log line + +``` +MCP tools/call find_order ok 34ms identity=12 client=62938fb0 session=0f3c... request=2 args={"number":"A-1042"} +``` + +Send it to a file of its own with a scoped log config: + +```php +use Cake\Log\Engine\FileLog; + +'Log' => [ + 'mcp_audit' => [ + 'className' => FileLog::class, + 'path' => LOGS, + 'file' => 'mcp_audit', + 'scopes' => ['mcp_audit'], + 'levels' => ['info', 'notice', 'warning'], + ], +], +``` + +The line also carries the `mcp` scope, so an `mcp` engine receives it too. +`bin/cake mcp check` warns when the audit is on and no engine takes its +lines. + +### The Mcp.audit event + +Each record is dispatched as the `Mcp.audit` event on the global event +manager, with the record as the event data. The event has no subject: read it +with `getData()` (Cake throws when you ask for the subject of an event that +has none). A listener that throws is logged under `mcp` and the call goes on. + +```php +use Cake\Event\EventInterface; +use Cake\Event\EventManager; + +EventManager::instance()->on('Mcp.audit', function (EventInterface $event): void { + $record = $event->getData(); // method, name, outcome, identity, client, ... +}); +``` + +### Storing records in the database + +Cake has no log engine that writes to a table, so store the records from the +event. A migration for the table (`Migrations\BaseMigration` is the base class +of cakephp/migrations 5.x and 4.5+; older 4.x versions use +`Migrations\AbstractMigration`): + +```php +use Migrations\BaseMigration; + +class CreateMcpAuditLogs extends BaseMigration +{ + public function change(): void + { + $this->table('mcp_audit_logs') + ->addColumn('method', 'string', ['limit' => 50]) + ->addColumn('name', 'string', ['limit' => 255, 'null' => true]) + ->addColumn('outcome', 'string', ['limit' => 20]) + ->addColumn('identity', 'string', ['limit' => 255, 'null' => true]) + ->addColumn('client', 'string', ['limit' => 255, 'null' => true]) + ->addColumn('session', 'string', ['limit' => 36, 'null' => true]) + ->addColumn('request', 'string', ['limit' => 255, 'null' => true]) + ->addColumn('arguments', 'text', ['null' => true]) + ->addColumn('error', 'string', ['limit' => 255, 'null' => true]) + ->addColumn('duration_ms', 'integer', ['null' => true]) + ->addColumn('created', 'datetime') + ->addIndex(['identity', 'created']) + ->addIndex(['created']) + ->create(); + } +} +``` + +A table class with the `Timestamp` behavior (it fills `created`): + +```php +namespace App\Model\Table; + +use Cake\ORM\Table; + +class McpAuditLogsTable extends Table +{ + public function initialize(array $config): void + { + parent::initialize($config); + $this->addBehavior('Timestamp'); + } +} +``` + +And a listener, registered in `Application::bootstrap()`: + +```php +use Cake\Event\EventInterface; +use Cake\Event\EventManager; +use Cake\ORM\TableRegistry; + +EventManager::instance()->on('Mcp.audit', function (EventInterface $event): void { + $record = (array)$event->getData(); + $logs = TableRegistry::getTableLocator()->get('McpAuditLogs'); + $logs->save($logs->newEntity([ + 'method' => $record['method'], + 'name' => $record['name'], + 'outcome' => $record['outcome'], + 'identity' => $record['identity'] === null ? null : (string)$record['identity'], + 'client' => $record['client'], + 'session' => $record['session'], + 'request' => $record['request'] === null ? null : (string)$record['request'], + 'arguments' => json_encode($record['arguments']), + 'error' => $record['error'] === null ? null : mb_substr($record['error'], 0, 255), + 'duration_ms' => $record['durationMs'], + ], ['accessibleFields' => ['*' => true]])); +}); +``` + +Set `audit.log` to `false` if the table is the only record you want. The save +runs in the request that served the call; on a busy server, a queue job or a +log shipper keeps it out of the way. diff --git a/docs/conformance.md b/docs/conformance.md new file mode 100644 index 0000000..690e258 --- /dev/null +++ b/docs/conformance.md @@ -0,0 +1,48 @@ +# Protocol conformance + +The plugin is checked against the official +[MCP conformance suite](https://github.com/modelcontextprotocol/conformance), +the same one the SDK runs. The SDK already passes it on its own; running it +again through the plugin checks what the plugin adds on top: the Cake route and +controller, the request and response conversion, sessions in Cake cache, +the identity middleware and the DNS-rebinding protection. + +The endpoint runs the way a real deployment does, with nginx in front of +php-fpm, so server-sent events also go through nginx. + +## Running it + +You need Docker, Node.js 22 and the Composer dependencies installed: + +```bash +composer install +tests/Conformance/run.sh # both protocol revisions +tests/Conformance/run.sh 2026-07-28 # one revision +``` + +`CONFORMANCE_PORT` changes the local port (8000 by default) and +`CONFORMANCE_PACKAGE` the suite version. By default the script runs the newest +published alpha of the suite (`@modelcontextprotocol/conformance@alpha`), so the +plugin is always checked against the latest scenarios: a new release that adds a +scenario the plugin fails turns the build red on purpose. Set +`CONFORMANCE_PACKAGE` to a fixed version to reproduce an older run. + +The CI workflow runs the suite on pushes to the main branches and on every +pull request. + +The container uses the PHP version of the host that runs the script (8.3 in +CI), because it runs the `vendor/` directory installed there. Set +`CONFORMANCE_PHP` to use another one. + +## How it is set up + +- `webroot/index.php` serves the test application with the plugin's `/mcp` + endpoint, open to anonymous callers, without discovery. +- `ConformanceFixture` registers, through `Mcp.server.configure`, the same + tools, resources and prompts as the SDK's own conformance server. They live in + `Sdk/`, copied from the SDK with their license. +- `baseline-.yml` lists the scenarios expected to fail at each + revision, with the reason. Both are empty: every scenario passes. + +Results are written to `tests/Conformance/results/` and the plugin log to +`tests/Conformance/tmp/logs/mcp.log`. diff --git a/docs/installation.md b/docs/installation.md new file mode 100644 index 0000000..e544dac --- /dev/null +++ b/docs/installation.md @@ -0,0 +1,92 @@ +# Installation + +## Composer + +```bash +composer require cakedc/cakephp-mcp:^1.1 +``` + +It installs `mcp/sdk` ^0.9, the official PHP SDK. Require `^1.1`: version 1.0.0 +on Packagist is the CakePHP 5 code of 2.0.0, tagged by mistake. + +The plugin needs PHP 8.2 or 8.3 and CakePHP 4.5+ (CakePHP 4 needs +`laminas/laminas-diactoros` 2.x, which stops at PHP 8.3). It builds on the official `mcp/sdk`. +The `php-http/discovery` Composer plugin is not needed: the plugin passes the +PSR-17 factories of `laminas/laminas-diactoros` (which CakePHP 4 already +requires) to the SDK, so nothing has to be discovered. + +## Load the plugin + +In `src/Application.php`: + +```php +public function bootstrap(): void +{ + parent::bootstrap(); + $this->addPlugin('CakeDC/Mcp'); +} +``` + +## Skip CSRF for the endpoint + +MCP clients are not browsers and do not send CSRF tokens. In +`Application::middleware()` let requests to the MCP path through: + +```php +use Cake\Http\Middleware\CsrfProtectionMiddleware; +use Cake\Http\ServerRequest; + +$csrf = new CsrfProtectionMiddleware(); +$csrf->skipCheckCallback(fn (ServerRequest $request): bool => $request->getPath() === '/mcp'); + +$middlewareQueue->add($csrf); +``` + +If you change `Mcp.route`, change the path here too. + +Or use the helper, which follows `Mcp.route`: + +```php +use CakeDC\Mcp\McpConfig; + +$csrf->skipCheckCallback(fn (ServerRequest $request): bool => McpConfig::isEndpoint($request)); +``` + +## The route + +The plugin connects `/mcp` (methods GET, POST, DELETE and OPTIONS) to its own +controller. GET is routed, but this SDK version answers it with 405 (there is +no standalone server-to-client stream). To use another path: + +```php +// config/app_local.php or config/bootstrap.php +Configure::write('Mcp.route', '/api/mcp'); +``` + +To not connect any route (for example when you only use stdio), set it to +`false`: + +```php +Configure::write('Mcp.route', false); +``` + +## Where tools live + +By default the plugin scans `src/Mcp/` in your application for classes with +`#[McpTool]`, `#[McpResource]` and `#[McpPrompt]` attributes. Change the +directories with `Mcp.discovery.scanDirs` (paths relative to `ROOT`). See +[Writing tools](tools.md). + +If the directory does not exist yet, the endpoint still works and returns an +empty tool list. + +## After deploying new tools + +Outside debug mode the discovery result is cached in the `_cake_mcp_` cache +config. After you deploy new or changed tools, clear it: + +```bash +bin/cake cache clear _cake_mcp_ +``` + +In debug mode the discovery cache is off, so new tools show up right away. diff --git a/docs/stdio.md b/docs/stdio.md new file mode 100644 index 0000000..f5daf59 --- /dev/null +++ b/docs/stdio.md @@ -0,0 +1,63 @@ +# stdio + +For MCP clients that run on the same machine as your project, the plugin +provides a command that speaks MCP over standard input and output: + +```bash +bin/cake mcp server +``` + +## Claude Code + +```bash +claude mcp add my-app -- bin/cake mcp server +``` + +Run it from the project directory, or give the full path to `bin/cake`. With +DDEV or Docker, wrap the command, for example +`claude mcp add my-app -- ddev exec bin/cake mcp server`. + +## Identity + +There is no HTTP request, so there is no authentication. By default tools see +no identity. To run tools as a particular user, give `Mcp.stdio.identity` a +closure that returns the identity: + +```php +Configure::write('Mcp.stdio.identity', function (): ArrayObject { + return new ArrayObject(['id' => 1, 'role' => 'admin']); +}); +``` + +`Mcp.stdio.identity` must be a callable. A plain array or `ArrayObject` there is +silently ignored (the command only calls it when it is callable), so tools +would see no identity. + +Return whatever shape your tools and authorizer expect (see +[Authentication](authentication.md)). The closure runs once when the command +starts. + +## Trusted mode + +`Mcp.stdio.trusted` defaults to `true`. A trusted stdio session skips +per-tool authorization: the developer who starts the command already has +access to the code and the database. Set it to `false` if you want the +configured authorizer applied to the identity from `stdio.identity`. + +Only authorization is skipped. Everything else, including tool discovery and +dependency injection, works as over HTTP. + +## Keep STDOUT clean + +The protocol uses STDOUT, so anything else written there corrupts the +conversation and the client disconnects. + +- The command removes Cake's default console loggers that mirror info logs to + STDOUT, keeping only the stderr one for errors and warnings. +- Tools must never `echo`, `print` or `var_dump`. +- No Log engine may write to `php://stdout`. Cake's `ConsoleLog` writes to + stderr by default, which is fine. If you configured a console log with + `'stream' => 'php://stdout'`, change it or scope it away from the `mcp` + scope for this command. +- Make sure PHP notices and deprecations are not printed to STDOUT + (`display_errors` off for the CLI, or sent to stderr). diff --git a/docs/testing.md b/docs/testing.md new file mode 100644 index 0000000..a4b9c1c --- /dev/null +++ b/docs/testing.md @@ -0,0 +1,115 @@ +# Testing your tools + +`CakeDC\Mcp\TestSuite\McpTestTrait` calls your tools from a regular Cake test +case, without HTTP. Each call builds your application (bootstrap and routes) +and its container, then the MCP server the same way the endpoint does: tool +discovery, constructor injection and your authorizer. So a test covers the +tool, its dependencies and who may call it. + +```php +namespace App\Test\TestCase\Mcp; + +use Authentication\Identity; +use Cake\TestSuite\TestCase; +use CakeDC\Mcp\TestSuite\McpTestTrait; + +class ArticleToolsTest extends TestCase +{ + use McpTestTrait; + + protected array $fixtures = ['app.Articles', 'app.Users']; + + public function testEditorsCreateDrafts(): void + { + $this->mcpActingAs(new Identity($this->fetchTable('Users')->get(1))); + + $this->mcpCallTool('create_draft', ['title' => 'Hello', 'body' => 'First post']); + + $this->assertMcpToolSucceeded(); + $this->assertMcpResultContains('id'); + } + + public function testInvalidDraftsExplainWhatToFix(): void + { + $this->mcpActingAs(new Identity($this->fetchTable('Users')->get(1))); + + $this->mcpCallTool('create_draft', ['title' => '', 'body' => 'No title']); + + $this->assertMcpToolError('- title:'); + } + + public function testReadersCannotCreateDrafts(): void + { + $this->mcpActingAs(new Identity($this->fetchTable('Users')->get(2))); + + $this->assertMcpToolNotListed('create_draft'); + $this->mcpCallTool('create_draft', ['title' => 'Hello', 'body' => 'Nope']); + $this->assertMcpToolDenied(); + } +} +``` + +## The identity + +`mcpActingAs()` sets who makes the next calls. Pass it in the shape your +middleware produces: `cakephp/authentication` wraps the user in +`Authentication\Identity`, and `cakephp/authorization` wraps that in +`Authorization\IdentityDecorator`. A raw entity works for tools and authorizers +that only read fields, but not for code that calls `can()` or +`getOriginalData()`. + +Tools see the identity through `CurrentIdentity`, and through the SDK access +token built as the endpoint builds it (identifier as subject, scopes from +`Mcp.identity.scopes`). Without `mcpActingAs()` the calls are anonymous. + +### Scopes + +`mcpActingAs($identity, $scopes = null, $claims = [])` also takes the scopes of +the access token and extra claims for it (they win over `sub`). With `$scopes` +given, `Mcp.identity.scopes` is not used and the token carries those scopes, +which tools read with `RequestContext::getAccessToken()?->getScopes()`. The 1.x +line has no scope policy (it comes with the `oauth` and `external` modes of +2.x), so scopes never refuse a call. + +The trait does not go through your HTTP authentication, so it does not check +tokens or `Mcp.identity.required`. Cover that with an integration test of the +endpoint (`IntegrationTestTrait`, a `POST` to `/mcp` with your +`Authorization` header). Both traits can be used in the same test case. + +## Calls and results + +| Method | Does | +| --- | --- | +| `mcpCallTool($name, $arguments)` | Calls a tool and keeps its response. Returns the raw JSON-RPC response. | +| `mcpListTools()` | Returns the definitions of the tools the current identity sees. | +| `mcpResultText()` | The text of the last result, one line per text item. | +| `mcpResponse()` | The raw JSON-RPC response of the last call. | + +## Assertions + +| Assertion | Passes when the last call | +| --- | --- | +| `assertMcpToolSucceeded()` | returned a result that is not a tool error. On failure it shows what the server logged, including the exception of a tool that threw. | +| `assertMcpToolError(?$contains)` | returned a tool error, the kind the model reads (`ToolCallException`, `ToolError::invalid()`). | +| `assertMcpJsonRpcError(?$code, ?$contains)` | was answered with a JSON-RPC error: `-32602` for arguments that do not match the input schema, `-32603` for an unexpected exception. | +| `assertMcpToolDenied()` | was rejected by your authorizer. It also checks that the tool exists, because a denied tool is answered like an unknown one and a typo would pass otherwise. | +| `assertMcpResultContains($text)` | returned text containing `$text`. | +| `assertMcpStructuredContent($expected)` | returned this `structuredContent`. Key order does not matter, value types do. | + +`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()`. + +## Replacing services + +The trait uses Cake's `ContainerStubTrait`, so `mockService()` replaces a +service for the tools: + +```php +$this->mockService(PaymentGateway::class, fn () => new FakePaymentGateway()); +$this->mcpCallTool('refund_order', ['number' => 'A-1042']); +``` + +To build the server from another application class, call +`configApplication()` as you would for an integration test. diff --git a/docs/tools.md b/docs/tools.md new file mode 100644 index 0000000..c9c0446 --- /dev/null +++ b/docs/tools.md @@ -0,0 +1,215 @@ +# Writing tools + +A tool is a method of a plain PHP class, marked with an attribute from the +official SDK. The plugin scans the directories in `Mcp.discovery.scanDirs` +(`src/Mcp` by default) and registers what it finds. + +## Attributes + +```php +use Mcp\Capability\Attribute\McpPrompt; +use Mcp\Capability\Attribute\McpResource; +use Mcp\Capability\Attribute\McpTool; +``` + +- `#[McpTool]` exposes a method clients can call. +- `#[McpResource]` exposes read-only content addressed by a URI. +- `#[McpPrompt]` exposes a reusable prompt template. + +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 + +```php +namespace App\Mcp; + +use Cake\ORM\Locator\LocatorAwareTrait; +use Mcp\Capability\Attribute\McpTool; + +class OrderTools +{ + use LocatorAwareTrait; + + /** + * Finds an order by its number. + * + * @param string $number The order number, for example "A-1042". + * @return array{number: string, status: string, total: float} + */ + #[McpTool(name: 'find_order')] + public function find(string $number): array + { + $order = $this->fetchTable('Orders')->find()->where(['number' => $number])->firstOrFail(); + + return [ + 'number' => $order->number, + 'status' => $order->status, + 'total' => (float)$order->total, + ]; + } +} +``` + +## Annotations + +Annotations tell the client how a tool behaves. Clients such as Claude use them +to decide when to ask the user before running a tool, so mark the tools that +only read as read-only and the ones that delete or overwrite as destructive: + +```php +use Mcp\Capability\Attribute\McpTool; +use Mcp\Schema\ToolAnnotations; + +#[McpTool(name: 'find_order', annotations: new ToolAnnotations(readOnlyHint: true))] +public function find(string $number): array + +#[McpTool(name: 'cancel_order', annotations: new ToolAnnotations(destructiveHint: true, idempotentHint: true))] +public function cancel(string $number): string +``` + +| Hint | Meaning | +| --- | --- | +| `title` | A human-readable name for the tool. | +| `readOnlyHint` | The tool does not change anything. | +| `destructiveHint` | The tool may delete or overwrite data. Only meaningful when it is not read-only. | +| `idempotentHint` | Calling it again with the same arguments changes nothing more. Only meaningful when it is not read-only. | +| `openWorldHint` | The tool reaches systems outside your application, such as a third-party API. | + +A hint you leave out means the worst case: not read-only, destructive, not +idempotent and open world. Annotations are hints for the client, not a security +boundary. Who may call a tool is decided by [authorization](authorization.md). + +## Constructor injection + +Tool classes are built through Cake's container, so constructor dependencies +are injected. Services you registered in `Application::services()` come first; +anything else is autowired when its own dependencies can be resolved. + +```php +class ReportTools +{ + public function __construct(private readonly ReportService $reports) + { + } + + #[McpTool(name: 'monthly_report')] + public function monthly(int $year, int $month): array + { + return $this->reports->forMonth($year, $month); + } +} +``` + +For ORM tables use `LocatorAwareTrait` and `fetchTable()`, as in the examples +above, instead of injecting a table. + +## Knowing who is calling + +Inject `CakeDC\Mcp\Identity\CurrentIdentity`: + +```php +use CakeDC\Mcp\Identity\CurrentIdentity; + +class WhoAmITools +{ + public function __construct(private readonly CurrentIdentity $identity) + { + } + + #[McpTool(name: 'whoami')] + public function whoami(): array + { + return ['id' => $this->identity->getIdentifier()]; + } +} +``` + +`get()` returns the host identity exactly as your authentication produced it, +`has()` tells whether there is one, and `getIdentifier()` returns its id. + +The SDK's own access token is also available. Add a `RequestContext` parameter +to the tool method and call `$context->getAccessToken()`: + +```php +use Mcp\Server\RequestContext; + +#[McpTool(name: 'token_scopes')] +public function scopes(RequestContext $context): array +{ + return $context->getAccessToken()?->getScopes() ?? []; +} +``` + +## Errors + +If a tool throws an unexpected exception, the client receives a JSON-RPC +`-32603` error with the message `Error while executing tool`. The original +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`: + +```php +use Mcp\Exception\ToolCallException; + +#[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)); + } + + return 'Cancelled.'; +} +``` + +Unhandled exceptions are logged through Cake's `Log` with the `mcp` scope. + +### Validation errors + +The SDK already rejects arguments that do not match the tool's input schema. +For the rules that live in your tables and validators, throw +`CakeDC\Mcp\Tool\ToolError::invalid()`. It turns Cake's validation errors into +a message with one line per field, so the model sees what to fix and can try +again: + +```php +use Cake\ORM\Locator\LocatorAwareTrait; +use CakeDC\Mcp\Tool\ToolError; +use Mcp\Capability\Attribute\McpTool; + +class ArticleTools +{ + use LocatorAwareTrait; + + #[McpTool(name: 'create_draft')] + public function createDraft(string $title, string $body): array + { + $articles = $this->fetchTable('Articles'); + $article = $articles->newEntity(['title' => $title, 'body' => $body]); + if (!$articles->save($article)) { + throw ToolError::invalid($article, 'The draft was not saved.'); + } + + return ['id' => $article->id]; + } +} +``` + +The client receives a tool error with this text: + +``` +The draft was not saved. +- title: This field cannot be left empty +- tags.0.name: This field is required +``` + +`invalid()` takes an entity (errors of associated entities included), the +array returned by `Validator::validate()` or `getErrors()`, or a simple +`['field' => 'message']` array. With `saveOrFail()`, +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. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md new file mode 100644 index 0000000..5a75a80 --- /dev/null +++ b/docs/troubleshooting.md @@ -0,0 +1,100 @@ +# Troubleshooting + +## 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: + +- 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 + nothing, so run `php -l` on the files in `src/Mcp/` and load the classes from + a script or test to see the real error. +- `Mcp.discovery.scanDirs` points to the wrong place. Paths are relative to + `ROOT`, and a directory that does not exist is ignored. +- The discovery cache is stale. Outside debug mode run + `bin/cake cache clear _cake_mcp_` after every deploy of new tools. + +## 403 Invalid Host header + +The `Host` of the request is not allowed. By default the host of +`App.fullBaseUrl` and localhost are, but only when `App.fullBaseUrl` is set +explicitly: the CakePHP 4 skeleton derives it from the request `Host` when it is +not set, and then every host is accepted. Set `Mcp.http.allowedHosts` yourself +(required for servers with `identity.required` set to `false`): + +```php +Configure::write('Mcp.http.allowedHosts', ['example.com', 'localhost']); +``` + +## 413 Request body too large + +The request body was larger than `Mcp.http.maxBodyBytes` (4 MiB by default). +The endpoint answers before authentication, with a JSON-RPC error whose +message and `data.maxBodyBytes` name the limit. Send less per call (a smaller +file, fewer items), or raise the limit: + +```php +Configure::write('Mcp.http.maxBodyBytes', 8 * 1024 * 1024); +``` + +## 403 or a redirect to the login page (cakedc/users) + +On a `cakedc/users` host, `RequestAuthorizationMiddleware` authorizes the +route before the plugin runs, so an anonymous or unlisted request gets a 403 or +a redirect to the login page instead of the plugin's 401. Add the `bypassAuth` +permission rule for `CakeDC/Mcp` `Mcp::handle` +that `McpConfig::rbacPermissions()` returns; see +[Authentication](authentication.md#cakedcauth-and-cakedcusers). If tokens are +sent but ignored, the default `Token` authenticator reads `api_key` from the +query string, not the header. + +## 403 from CSRF + +Cake's CSRF middleware is rejecting the POST. Add the `skipCheckCallback` shown +in [Installation](installation.md), and make sure it matches your +`Mcp.route`. + +## 401 on every request + +The authenticator is not reading the header. Check that the client sends +`Authorization: Bearer `, that `tokenPrefix` matches (`Bearer`), and +that your web server passes the `Authorization` header to PHP (Apache needs +`SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1` in some setups). Also +confirm the `AuthenticationMiddleware` runs before the request reaches the MCP +route. + +## AuthorizationRequiredException from cakephp/authorization + +This should not happen: the MCP controller marks the request as authorized +because authorization is done per tool. If you see it, check that you run the +latest version of this plugin and that no other middleware calls the +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. + +## The session is lost between requests + +With the 2025 handshake protocol, the `Mcp-Session-Id` returned by +`initialize` must work on the next request, which may be handled by another PHP +worker. The `mcp_sessions` cache therefore has to be shared by all workers. Do +not point it at the Array engine. The default file cache works on one server; +use Redis or Memcached when you run several. + +## A tool failed and the client only says "Error while executing tool" + +That is intentional: exception messages are not sent to clients. Check your +logs (the `mcp` scope), or throw `Mcp\Exception\ToolCallException` when you +want the client to see a message. See [Writing tools](tools.md). + +## HTTP 500 with "Internal error" + +Something failed outside the SDK, for example the server could not be built +because the configuration is invalid. The response is always the JSON body +`{"jsonrpc":"2.0","id":null,"error":{"code":-32603,"message":"Internal error"}}`, +never an HTML page, even in debug mode. The full error is in your log under the +`mcp` scope. diff --git a/phpcs.xml b/phpcs.xml new file mode 100644 index 0000000..ea48954 --- /dev/null +++ b/phpcs.xml @@ -0,0 +1,13 @@ + + + + + src/ + tests/ + + tests/test_app/tmp/* + + tests/Conformance/Sdk/* + tests/Conformance/tmp/* + tests/Conformance/results/* + diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 0000000..37c6968 --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,8 @@ +parameters: + level: 8 + paths: + - src/ + # Analyses McpTestTrait, which PHPStan only checks through a class using it. + - tests/TestCase/TestSuite/McpTestTraitTest.php + bootstrapFiles: + - tests/bootstrap.php diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..8985296 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,17 @@ + + + + + tests/TestCase/ + + + + + src/ + + + diff --git a/src/Audit/AuditRecord.php b/src/Audit/AuditRecord.php new file mode 100644 index 0000000..0fe6555 --- /dev/null +++ b/src/Audit/AuditRecord.php @@ -0,0 +1,85 @@ + $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. + */ + public function __construct( + public readonly string $method, + public readonly ?string $name, + public readonly string $outcome, + public readonly string|int|null $identity, + public readonly ?string $client, + public readonly ?string $session, + public readonly string|int|null $request, + public readonly array $arguments, + public readonly ?string $error, + public readonly ?int $durationMs, + ) { + } + + /** + * $value cut to MAX_TEXT characters; integers and null as they are. + * + * @param string|int|null $value A name or request id from the client. + * @return string|int|null + */ + public static function cap(string|int|null $value): string|int|null + { + return is_string($value) ? mb_substr($value, 0, self::MAX_TEXT) : $value; + } + + /** + * @return array{method: string, name: string|null, outcome: string, identity: string|int|null, client: string|null, session: string|null, request: string|int|null, arguments: array, error: string|null, durationMs: int|null} + */ + public function toArray(): array + { + return [ + 'method' => $this->method, + 'name' => $this->name, + 'outcome' => $this->outcome, + 'identity' => $this->identity, + 'client' => $this->client, + 'session' => $this->session, + 'request' => $this->request, + 'arguments' => $this->arguments, + 'error' => $this->error, + 'durationMs' => $this->durationMs, + ]; + } +} diff --git a/src/Audit/AuditSettings.php b/src/Audit/AuditSettings.php new file mode 100644 index 0000000..7d68006 --- /dev/null +++ b/src/Audit/AuditSettings.php @@ -0,0 +1,108 @@ + + */ + public const METHODS = ['tools/call', 'prompts/get', 'resources/read']; + + /** + * @param bool $enabled Whether calls are recorded. + * @param list $methods Audited JSON-RPC methods. + * @param bool $log Write the log line (the `Mcp.audit` event fires either way). + * @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. + */ + private function __construct( + public readonly bool $enabled, + public readonly array $methods, + public readonly bool $log, + public readonly bool $arguments, + public readonly array $redact, + public readonly int $maxLength, + ) { + } + + /** + * Reads and validates `Mcp.audit`. + * + * @return self + * @throws \InvalidArgumentException For an invalid setting, named in the message. + */ + public static function fromConfig(): self + { + $audit = McpConfig::get('audit'); + if (!is_array($audit)) { + throw new InvalidArgumentException('"Mcp.audit" must be an array.'); + } + foreach (array_keys($audit) as $key) { + if (!array_key_exists($key, McpConfig::DEFAULTS['audit'])) { + throw new InvalidArgumentException(sprintf('"Mcp.audit.%s" is not a setting.', $key)); + } + } + + $methods = $audit['methods']; + if (!is_array($methods) || !array_is_list($methods) || array_diff($methods, self::METHODS) !== []) { + throw new InvalidArgumentException(sprintf( + '"Mcp.audit.methods" must be a list of %s.', + implode(', ', self::METHODS), + )); + } + $redact = $audit['redact']; + if (!is_array($redact) || !array_is_list($redact) || array_filter($redact, 'is_string') !== $redact) { + throw new InvalidArgumentException('"Mcp.audit.redact" must be a list of argument names.'); + } + $maxLength = $audit['maxLength']; + if (!is_int($maxLength) || $maxLength < 1) { + throw new InvalidArgumentException('"Mcp.audit.maxLength" must be a positive integer.'); + } + + /** @var list $methods */ + /** @var list $redact */ + return new self( + self::flag($audit['enabled'], 'enabled'), + $methods, + self::flag($audit['log'], 'log'), + self::flag($audit['arguments'], 'arguments'), + array_map('strtolower', $redact), + $maxLength, + ); + } + + /** + * @param string $method A JSON-RPC method. + * @return bool Whether calls of $method are recorded. + */ + public function audits(string $method): bool + { + return in_array($method, $this->methods, true); + } + + /** + * @param mixed $value The setting. + * @param string $key Its key inside `Mcp.audit`. + * @return bool + */ + private static function flag(mixed $value, string $key): bool + { + if (!is_bool($value)) { + throw new InvalidArgumentException(sprintf('"Mcp.audit.%s" must be true or false.', $key)); + } + + return $value; + } +} diff --git a/src/Audit/AuditWriter.php b/src/Audit/AuditWriter.php new file mode 100644 index 0000000..da9fa23 --- /dev/null +++ b/src/Audit/AuditWriter.php @@ -0,0 +1,198 @@ + 'info', + AuditRecord::TOOL_ERROR => 'notice', + AuditRecord::INVALID => 'notice', + AuditRecord::DENIED => 'warning', + AuditRecord::ERROR => 'warning', + AuditRecord::UNAUTHORIZED => 'warning', + AuditRecord::INSUFFICIENT_SCOPE => 'warning', + ]; + + /** + * @param \CakeDC\Mcp\Audit\AuditSettings $settings The audit settings. + */ + public function __construct(private readonly AuditSettings $settings) + { + } + + /** + * The arguments as they go in a record: redacted, long strings cut, deep + * arrays cut, and replaced by `{"truncated": true}` when still too large. + * Empty when arguments are not recorded or are not a JSON object. + * + * @param mixed $arguments The call arguments. + * @return array + */ + public function arguments(mixed $arguments): array + { + if (!$this->settings->arguments || !is_array($arguments) || ($arguments !== [] && array_is_list($arguments))) { + return []; + } + $clean = $this->clean($arguments, 1); + if (!is_array($clean)) { + return []; + } + if (strlen((string)json_encode($clean, self::JSON_FLAGS)) > self::MAX_ARGUMENTS_BYTES) { + return ['truncated' => true]; + } + + return $clean; + } + + /** + * Writes the log line (unless `log` is false) and dispatches `Mcp.audit`. + * + * @param \CakeDC\Mcp\Audit\AuditRecord $record The record. + * @return void + */ + public function write(AuditRecord $record): void + { + if ($this->settings->log) { + try { + // The line is the value of one placeholder: Cake replaces it in a single pass, so `{...}` in + // client text is never interpolated. + (new McpLogger())->log( + self::LEVELS[$record->outcome] ?? 'warning', + '{audit}', + ['audit' => $this->line($record), 'scope' => [self::SCOPE]], + ); + } catch (Throwable $exception) { + $this->report('could not write the log line', $exception); + } + } + try { + EventManager::instance()->dispatch(new Event(self::EVENT, null, $record->toArray())); + } catch (Throwable $exception) { + $this->report('a listener of the Mcp.audit event failed', $exception); + } + } + + /** + * @param \CakeDC\Mcp\Audit\AuditRecord $record The record. + * @return string + */ + private function line(AuditRecord $record): string + { + $line = sprintf( + 'MCP %s %s %s %sms identity=%s client=%s session=%s request=%s', + $this->field($record->method), + $this->field($record->name), + $this->field($record->outcome), + $record->durationMs ?? '-', + $this->field($record->identity), + $this->field($record->client), + $this->field($record->session), + $this->field($record->request), + ); + if ($this->settings->arguments) { + $line .= ' args=' . json_encode((object)$record->arguments, self::JSON_FLAGS); + } + if ($record->error !== null) { + $line .= ' error=' . json_encode($record->error, self::JSON_FLAGS); + } + + return $line; + } + + /** + * A value of the line: as is when it is a plain token, else a JSON string, so client text + * (a tool name, a request id) cannot add spaces, quotes or line breaks to the line. + * + * @param string|int|null $value The value. + * @return string + */ + private function field(string|int|null $value): string + { + if ($value === null) { + return '-'; + } + $value = (string)$value; + + if (preg_match('~^[A-Za-z0-9_.:/@-]+$~D', $value) === 1) { + return $value; + } + + return (string)json_encode($value, self::JSON_FLAGS); + } + + /** + * @param mixed $value A value of the arguments. + * @param int $depth Depth of $value, 1 for the arguments themselves. + * @return mixed + */ + private function clean(mixed $value, int $depth): mixed + { + if (is_string($value)) { + return mb_strlen($value) > $this->settings->maxLength + ? mb_substr($value, 0, $this->settings->maxLength) . '...' + : $value; + } + if (is_object($value)) { + return $this->clean(get_object_vars($value), $depth); + } + if (!is_array($value)) { + return $value; + } + if ($depth > self::MAX_DEPTH) { + return '[...]'; + } + $clean = []; + foreach ($value as $key => $item) { + $clean[$key] = is_string($key) && in_array(strtolower($key), $this->settings->redact, true) + ? '[redacted]' + : $this->clean($item, $depth + 1); + } + + return $clean; + } + + /** + * Logs a failure of the audit itself under the `mcp` scope, quietly. + * + * @param string $what What failed. + * @param \Throwable $exception The failure. + * @return void + */ + private function report(string $what, Throwable $exception): void + { + try { + Log::error(sprintf('MCP audit: %s: %s', $what, $exception->getMessage()), ['scope' => [McpLogger::SCOPE]]); + } catch (Throwable) { + // Nothing left to tell: the call goes on. + } + } +} diff --git a/src/Authorization/AllowAllToolAuthorizer.php b/src/Authorization/AllowAllToolAuthorizer.php new file mode 100644 index 0000000..fb27ae7 --- /dev/null +++ b/src/Authorization/AllowAllToolAuthorizer.php @@ -0,0 +1,21 @@ + 'editor', 'plugin' => 'CakeDC/Mcp', 'controller' => 'Tools', 'action' => ['create_draft']] + * + * Requires `cakedc/auth`. + */ +final class RbacToolAuthorizer implements ToolAuthorizerInterface +{ + public const PLUGIN = 'CakeDC/Mcp'; + public const CONTROLLER = 'Tools'; + + private RbacInterface $rbac; + + /** + * @param \CakeDC\Auth\Rbac\RbacInterface|array $rbac An Rbac instance, or the config for one. + */ + public function __construct(RbacInterface|array $rbac = []) + { + $this->rbac = $rbac instanceof RbacInterface ? $rbac : new Rbac($rbac); + } + + /** + * The rules the Rbac loaded (from `permissions`, or from config/permissions.php when it has none). + * + * @internal Used by `bin/cake mcp check`; not part of the public API. + * @return array + */ + public function permissions(): array + { + return $this->rbac->getPermissions(); + } + + /** + * @inheritDoc + */ + public function canCall(mixed $identity, string $tool): bool + { + if (!is_array($identity) && !$identity instanceof ArrayAccess) { + return false; + } + + $request = (new ServerRequest(['url' => '/mcp']))->withAttribute('params', [ + 'plugin' => self::PLUGIN, + 'prefix' => null, + 'controller' => self::CONTROLLER, + 'action' => $tool, + '_ext' => null, + 'pass' => [], + ]); + + return $this->rbac->checkPermissions($identity, $request); + } +} diff --git a/src/Authorization/ToolAuthorizerInterface.php b/src/Authorization/ToolAuthorizerInterface.php new file mode 100644 index 0000000..434a078 --- /dev/null +++ b/src/Authorization/ToolAuthorizerInterface.php @@ -0,0 +1,17 @@ + + */ +final class ToolCallGuard implements RequestHandlerInterface +{ + /** + * @param \CakeDC\Mcp\Authorization\ToolGate $gate The gate. + */ + public function __construct(private readonly ToolGate $gate) + { + } + + /** + * @inheritDoc + */ + public function supports(Request $request): bool + { + return $request instanceof CallToolRequest && !$this->gate->allows($request->name); + } + + /** + * @inheritDoc + */ + public function handle(Request $request, SessionInterface $session): Error + { + $name = $request instanceof CallToolRequest ? $request->name : ''; + + return Error::forInvalidParams(sprintf('Tool not found: "%s".', $name), $request->getId()); + } +} diff --git a/src/Authorization/ToolGate.php b/src/Authorization/ToolGate.php new file mode 100644 index 0000000..ffeb88c --- /dev/null +++ b/src/Authorization/ToolGate.php @@ -0,0 +1,34 @@ +trusted || $this->authorizer->canCall($this->identity->get(), $tool); + } +} diff --git a/src/Command/McpCheckCommand.php b/src/Command/McpCheckCommand.php new file mode 100644 index 0000000..89ddc4d --- /dev/null +++ b/src/Command/McpCheckCommand.php @@ -0,0 +1,403 @@ +|null + */ + private ?array $tools = null; + + /** + * @param \CakeDC\Mcp\Server\ServerFactory|null $serverFactory Builds the server, as the endpoint does. + */ + public function __construct(private readonly ?ServerFactory $serverFactory = null) + { + parent::__construct(); + } + + /** + * @inheritDoc + */ + public static function defaultName(): string + { + return 'mcp check'; + } + + /** + * @inheritDoc + */ + public static function getDescription(): string + { + return 'Check the MCP endpoint configuration (authentication, hosts, CSRF, tools) without network calls.'; + } + + /** + * @inheritDoc + */ + public function execute(Arguments $args, ConsoleIo $io): int + { + $failed = false; + foreach ($this->checks() as $name => $probe) { + try { + [$status, $message] = $probe(); + } catch (Throwable $e) { + [$status, $message] = ['fail', $e->getMessage()]; + } + $tag = ['pass' => 'success', 'warn' => 'warning', 'fail' => 'error'][$status]; + $io->out(sprintf('<%s>[%s] %s: %s', $tag, strtoupper($status), $name, $message, $tag)); + $failed = $failed || $status === 'fail'; + } + + return $failed ? static::CODE_ERROR : static::CODE_SUCCESS; + } + + /** + * The checks, in order. + * + * @return array + */ + protected function checks(): array + { + return [ + 'Endpoint' => fn(): array => $this->endpoint(), + 'Authentication' => fn(): array => $this->authentication(), + 'Allowed hosts' => fn(): array => $this->hosts(), + 'CSRF' => fn(): array => $this->csrf(), + 'Tools' => fn(): array => $this->toolsCheck(), + 'Authorizer' => fn(): array => $this->authorizerCheck(), + 'Logging' => fn(): array => $this->logging(), + 'Audit' => fn(): array => $this->audit(), + ]; + } + + /** + * @return \CakeDC\Mcp\Server\ServerFactory + */ + private function factory(): ServerFactory + { + return $this->serverFactory ?? new ServerFactory(new Container(), new CurrentIdentity()); + } + + /** + * The tools the server offers, listed once per run. + * + * @return list + */ + private function toolNames(): array + { + return $this->tools ??= $this->factory()->toolNames(); + } + + /** + * @return array{0: 'pass'|'warn'|'fail', 1: string} + */ + private function toolsCheck(): array + { + $tools = $this->toolNames(); + if ($tools !== []) { + return ['pass', sprintf('%d tools: %s', count($tools), self::names($tools))]; + } + $dirs = array_filter((array)McpConfig::get('discovery.scanDirs'), 'is_string'); + + return ['warn', sprintf( + 'no tool found in %s (Mcp.discovery.scanDirs). A tool is a public method with #[McpTool] in a class ' + . 'with a namespace, inside those directories; other classes are skipped without an error. See %s', + $dirs === [] ? 'no directory' : implode(', ', $dirs), + self::DOCS . 'tools.md', + )]; + } + + /** + * @return array{0: 'pass'|'warn'|'fail', 1: string} + */ + private function authorizerCheck(): array + { + $authorizer = $this->factory()->authorizer(); + if ($authorizer instanceof AllowAllToolAuthorizer) { + return ['pass', 'AllowAllToolAuthorizer: every identified caller may call every tool']; + } + if (!$authorizer instanceof RbacToolAuthorizer) { + return ['pass', $authorizer::class]; + } + $docs = self::DOCS . 'authorization.md#rbactoolauthorizer-cakedcauth'; + $rules = $authorizer->permissions(); + if ($rules === []) { + return ['warn', sprintf( + "RbacToolAuthorizer has no rules, so no one can call a tool. Add rules for plugin '%s', " + . "controller '%s' and the tool as action, see %s", + RbacToolAuthorizer::PLUGIN, + RbacToolAuthorizer::CONTROLLER, + $docs, + )]; + } + $forTools = count(array_filter($rules, fn(mixed $rule): bool => is_array($rule) && self::allowsTools($rule))); + if ($forTools === 0) { + return ['warn', sprintf( + "none of the %d rules of RbacToolAuthorizer allows plugin '%s', controller '%s', so no one can " + . 'call a tool, see %s', + count($rules), + RbacToolAuthorizer::PLUGIN, + RbacToolAuthorizer::CONTROLLER, + $docs, + )]; + } + + return ['pass', sprintf('RbacToolAuthorizer, %d of %d rules for the tools', $forTools, count($rules))]; + } + + /** + * Whether an Rbac rule can allow a tool call: it allows, names a controller and an action, and its + * plugin, controller and prefix match those of a tool (`*`, a list, a missing key). A rule this + * cannot judge (an inverted key, a callable) counts. + * + * @param array $rule An Rbac rule. + * @return bool + */ + private static function allowsTools(array $rule): bool + { + if (($rule['allowed'] ?? true) === false) { + return false; + } + $has = fn(string $key): bool => array_key_exists($key, $rule) || array_key_exists('*' . $key, $rule); + if (!$has('controller') || !$has('action')) { + return false; + } + $expected = ['plugin' => RbacToolAuthorizer::PLUGIN, 'controller' => RbacToolAuthorizer::CONTROLLER]; + foreach ($expected as $key => $value) { + if (array_key_exists($key, $rule) && !self::matches($rule[$key], $value)) { + return false; + } + } + $prefix = $rule['prefix'] ?? null; + + return !is_string($prefix) || $prefix === '' || $prefix === '*'; + } + + /** + * @param mixed $value A rule value. + * @param string $param The request value. + * @return bool + */ + private static function matches(mixed $value, string $param): bool + { + if (!is_string($value) && is_callable($value)) { + return true; + } + if (is_array($value)) { + return in_array($param, $value, true) || in_array('*', $value, true); + } + + return $value === '*' || $value === $param; + } + + /** + * @param list $names Tool names. + * @return string The first ones, and how many more. + */ + private static function names(array $names): string + { + $listed = implode(', ', array_slice($names, 0, self::LISTED_TOOLS)); + $more = count($names) - self::LISTED_TOOLS; + + return $more > 0 ? sprintf('%s and %d more', $listed, $more) : $listed; + } + + /** + * @return array{0: 'pass'|'warn'|'fail', 1: string} + */ + private function logging(): array + { + $engines = self::enginesFor('error', [McpLogger::SCOPE]); + if ($engines !== []) { + return ['pass', sprintf('the %s scope goes to %s', McpLogger::SCOPE, implode(', ', $engines))]; + } + + return ['warn', sprintf( + 'no Log engine takes the errors of the %1$s scope, so a failing tool only answers "Error while ' + . 'executing tool" and its error is not kept anywhere (the debug and error engines of the ' + . "application skeleton have 'scopes' => false). Add a FileLog with 'scopes' => ['%1\$s'], see %2\$s", + McpLogger::SCOPE, + self::DOCS . 'configuration.md#logging', + )]; + } + + /** + * @return array{0: 'pass'|'warn'|'fail', 1: string} + */ + private function audit(): array + { + $settings = AuditSettings::fromConfig(); + if (!$settings->enabled) { + return ['pass', 'off']; + } + if (!$settings->log) { + return ['pass', sprintf('%s to the %s event only', implode(', ', $settings->methods), AuditWriter::EVENT)]; + } + if (self::enginesFor('info', [AuditWriter::SCOPE, McpLogger::SCOPE]) !== []) { + $methods = implode(', ', $settings->methods); + + return ['pass', sprintf('%s to the %s log scope', $methods, AuditWriter::SCOPE)]; + } + + return ['warn', sprintf( + 'on, but no Log engine takes its lines (scopes %1$s and %2$s, level info), so they are lost. ' + . "Add a FileLog with 'scopes' => ['%1\$s'], see %3\$s", + AuditWriter::SCOPE, + McpLogger::SCOPE, + self::DOCS . 'configuration.md#audit-log', + )]; + } + + /** + * The Log engines that write a message of $level with $scopes, decided as Log::write() does: an engine + * given as an object counts with its own settings, and a logger that is not a Cake engine takes + * everything. Console engines do not count. + * + * @param string $level A log level. + * @param list $scopes The scopes of the message. + * @return list Names of the engines. + */ + private static function enginesFor(string $level, array $scopes): array + { + $engines = []; + foreach (Log::configured() as $name) { + $logger = Log::engine((string)$name); + // The console engines (stdout, stderr) only exist while a command runs, not for web requests. + if ($logger instanceof ConsoleLog) { + continue; + } + $levels = $logger instanceof BaseLog ? $logger->levels() : null; + $listens = $logger instanceof BaseLog ? $logger->scopes() : []; + $inScope = $listens === [] || (is_array($listens) && array_intersect($scopes, $listens) !== []); + if (($levels === null || $levels === [] || in_array($level, $levels, true)) && $inScope) { + $engines[] = (string)$name; + } + } + + return $engines; + } + + /** + * @return array{0: 'pass'|'warn'|'fail', 1: string} + */ + private function endpoint(): array + { + $route = McpConfig::get('route'); + 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]; + } + + /** + * @return array{0: 'pass'|'warn'|'fail', 1: string} + */ + private function authentication(): array + { + // Throws for the oauth and external modes of 2.x, which execute() reports as a failure. + McpConfig::assertHostAuthMode(); + + return ['pass', sprintf( + 'host mode: the identity your authentication puts in the "%s" request attribute', + (string)McpConfig::get('identity.attribute'), + )]; + } + + /** + * @return array{0: 'pass'|'warn'|'fail', 1: string} + */ + private function hosts(): array + { + return ['pass', implode(', ', McpConfig::allowedHosts())]; + } + + /** + * Whether the application's CSRF middleware skips POST requests to the MCP route. + * + * @return array{0: 'pass'|'warn'|'fail', 1: string} + */ + private function csrf(): array + { + $route = McpConfig::get('route'); + if (!is_string($route) || $route === '') { + return ['pass', 'no HTTP endpoint']; + } + $app = $this->application(); + if (is_string($app)) { + return ['warn', $app . '; its middleware was not inspected']; + } + foreach ($app->middleware(new MiddlewareQueue()) as $middleware) { + if (!$middleware instanceof CsrfProtectionMiddleware) { + continue; + } + $callback = (new ReflectionProperty(CsrfProtectionMiddleware::class, 'skipCheckCallback')) + ->getValue($middleware); + $request = new ServerRequest(['url' => $route, 'environment' => ['REQUEST_METHOD' => 'POST']]); + + return is_callable($callback) && $callback($request) === true + ? ['pass', 'the MCP route is skipped'] + : ['fail', 'add McpConfig::isEndpoint($request) to the CsrfProtectionMiddleware skipCheckCallback']; + } + + return ['pass', 'no CsrfProtectionMiddleware in the queue']; + } + + /** + * The host application, without replacing the running plugin collection; or why it cannot be built. + * + * @return \Cake\Http\BaseApplication|string + */ + private function application(): BaseApplication|string + { + $class = Configure::read('App.namespace') . '\\Application'; + if (!class_exists($class)) { + return 'could not find the application class to inspect it'; + } + // CakePHP 4 applications share the running plugin collection (Plugin::getCollection()), + // so building one replaces nothing. + $app = new $class(CONFIG); + + return $app instanceof BaseApplication ? $app : 'the application class is not a BaseApplication'; + } +} diff --git a/src/Command/McpInspectorCommand.php b/src/Command/McpInspectorCommand.php new file mode 100644 index 0000000..c0b016c --- /dev/null +++ b/src/Command/McpInspectorCommand.php @@ -0,0 +1,387 @@ +setDescription(static::getDescription()) + ->addOption('http', [ + 'boolean' => true, + 'help' => 'Inspect the HTTP endpoint instead of starting `bin/cake mcp server`.', + ]) + ->addOption('url', [ + 'help' => 'URL of the HTTP endpoint (implies --http). Defaults to App.fullBaseUrl plus Mcp.route.', + ]) + ->addOption('header', [ + 'multiple' => true, + 'help' => 'Header sent to the HTTP endpoint, as "Name: Value". Repeat it for more headers.', + ]) + ->addOption('env', [ + 'multiple' => true, + '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('dry-run', [ + 'boolean' => true, + 'help' => 'Print the Inspector configuration and command without starting it.', + ]); + } + + /** + * @inheritDoc + */ + public function execute(Arguments $args, ConsoleIo $io): int + { + $url = $args->getOption('url'); + $headers = $this->listOption($args, 'header'); + $env = $this->listOption($args, 'env'); + $http = $args->getOption('http') === true || is_string($url); + if ($headers !== [] && !$http) { + $io->error('Headers are only sent over HTTP. Add --http or --url.'); + + return static::CODE_ERROR; + } + if ($env !== [] && $http) { + $io->error('Environment variables only reach the stdio server. Drop --http and --url.'); + + return static::CODE_ERROR; + } + + $server = $http + ? $this->httpServer(is_string($url) ? $url : null, $headers, $io) + : $this->stdioServer($env, $io); + if ($server === null) { + return static::CODE_ERROR; + } + $config = ['mcpServers' => [$this->serverName() => $server]]; + + if ($args->getOption('dry-run') === true) { + $io->out((string)json_encode($this->redact($config), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); + $io->out(implode(' ', $this->command(''))); + + return static::CODE_SUCCESS; + } + + $file = $this->writeConfig($config); + if ($file === null) { + $io->error('Could not write the Inspector configuration file.'); + + return static::CODE_ERROR; + } + $io->out(sprintf('Opening the MCP Inspector on %s. Stop it with Ctrl+C.', $server['url'] ?? 'stdio')); + if (!self::interruptsHandled() && (isset($server['headers']) || isset($server['env']))) { + $io->warning(sprintf( + 'Without the pcntl extension, stopping with Ctrl+C leaves `%s` behind. Delete it afterwards.', + $file, + )); + } + + try { + $code = $this->launch($this->command($file), $io); + } finally { + unlink($file); + } + if ($code === 127) { + $io->error('Could not run npx. The Inspector needs Node.js 22.19 or later.'); + } + + return $code; + } + + /** + * Runs the Inspector in the foreground, attached to this terminal. + * + * @param list $command The command and its arguments. + * @param \Cake\Console\ConsoleIo $io The console. + * @return int The exit code of the Inspector. + */ + protected function launch(array $command, ConsoleIo $io): int + { + $process = null; + $restore = $this->outliveInterrupts($process); + try { + $process = proc_open($command, [STDIN, STDOUT, STDERR], $pipes, rtrim(ROOT, DS)); + if ($process === false) { + $io->error('Could not start the Inspector. It needs Node.js 22.19 or later, with npx.'); + + return static::CODE_ERROR; + } + + // Polled rather than waited for in proc_close(): PHP only runs signal + // handlers between calls, so this lets SIGTERM and SIGHUP be passed on. + do { + $status = proc_get_status($process); + if ($status['running']) { + usleep(100000); + } + } while ($status['running']); + proc_close($process); + + return $status['signaled'] ? 128 + $status['termsig'] : $status['exitcode']; + } finally { + $restore(); + } + } + + /** + * Whether `launch()` can keep PHP alive through Ctrl+C to delete the + * configuration file: it needs the pcntl extension, or PHP on Windows. + * + * @return bool + */ + private static function interruptsHandled(): bool + { + return (function_exists('pcntl_async_signals') && function_exists('pcntl_signal')) + || function_exists('sapi_windows_set_ctrl_handler'); + } + + /** + * Ctrl+C reaches PHP as well as the Inspector, both being in the terminal's + * process group. Left alone, PHP would die at once and leave the + * configuration file, and any token in it, on disk. These handlers keep PHP + * waiting for the Inspector to exit so the file is deleted; SIGTERM and + * SIGHUP are passed on to the Inspector. They are handlers and not + * `SIG_IGN`, which the Inspector would inherit and then ignore Ctrl+C. + * + * @param resource|false|null $process The Inspector process, once started. + * @return \Closure Restores the previous behavior. + */ + private function outliveInterrupts(mixed &$process): Closure + { + if (!self::interruptsHandled()) { + return static function (): void { + }; + } + if (function_exists('pcntl_async_signals') && function_exists('pcntl_signal')) { + $async = pcntl_async_signals(true); + $forward = static function (int $signal) use (&$process): void { + if (is_resource($process)) { + proc_terminate($process, $signal); + } + }; + $handlers = [SIGINT => static function (): void { + }, SIGTERM => $forward, SIGHUP => $forward]; + $previous = []; + foreach ($handlers as $signal => $handler) { + $previous[$signal] = pcntl_signal_get_handler($signal); + pcntl_signal($signal, $handler); + } + + return static function () use ($previous, $async): void { + foreach ($previous as $signal => $handler) { + pcntl_signal($signal, $handler); + } + pcntl_async_signals($async); + }; + } + $handler = static function (int $event): void { + }; + sapi_windows_set_ctrl_handler($handler); + + return static function () use ($handler): void { + sapi_windows_set_ctrl_handler($handler, false); + }; + } + + /** + * @param string $configFile Path of the configuration file. + * @return list + */ + private function command(string $configFile): array + { + // On Windows npm installs npx as a batch file, which proc_open() only finds by its full name. + $npx = PHP_OS_FAMILY === 'Windows' ? 'npx.cmd' : 'npx'; + + return [$npx, '--yes', self::PACKAGE, '--config', $configFile]; + } + + /** + * The values of a multiple option. CakePHP 4 parses a `multiple` option into a list, but + * `Arguments::getOptions()` documents scalar values only, so the raw value is checked here. + * + * @param \Cake\Console\Arguments $args The arguments. + * @param string $name The option. + * @return list + */ + private function listOption(Arguments $args, string $name): array + { + return self::stringList($args->getOptions()[$name] ?? null); + } + + /** + * @param mixed $values A raw option value. + * @return list Its string items, nothing when it is not a list. + */ + private static function stringList(mixed $values): array + { + return is_array($values) ? array_values(array_filter($values, 'is_string')) : []; + } + + /** + * @param list $env Names of the environment variables to pass on. + * @param \Cake\Console\ConsoleIo $io The console. + * @return array|null + */ + private function stdioServer(array $env, ConsoleIo $io): ?array + { + // ROOT has no trailing separator in the app skeleton. + $cake = rtrim(ROOT, DS) . DS . 'bin' . DS . 'cake.php'; + if (!is_file($cake)) { + $io->error(sprintf('`%s` does not exist, so the Inspector cannot start the stdio server.', $cake)); + + return null; + } + + $server = [ + 'type' => 'stdio', + 'command' => PHP_BINARY, + 'args' => [$cake, 'mcp', 'server'], + 'cwd' => rtrim(ROOT, DS), + ]; + foreach ($env as $name) { + $value = getenv($name); + if ($value === false) { + $io->error(sprintf('The environment variable `%s` is not set.', $name)); + + return null; + } + $server['env'][$name] = $value; + } + $server['protocolEra'] = 'auto'; + + return $server; + } + + /** + * @param string|null $url The --url option. + * @param list $headers The --header options. + * @param \Cake\Console\ConsoleIo $io The console. + * @return array|null + */ + private function httpServer(?string $url, array $headers, ConsoleIo $io): ?array + { + if ($url === null) { + $route = McpConfig::get('route'); + if (!is_string($route) || $route === '') { + $io->error('The HTTP endpoint is disabled (`Mcp.route`). Pass --url to inspect another server.'); + + return null; + } + $base = Configure::read('App.fullBaseUrl'); + if (!is_string($base) || $base === '') { + $io->error('`App.fullBaseUrl` is not set, so the endpoint URL is unknown. Pass it with --url.'); + + return null; + } + $url = rtrim($base, '/') . $route; + } + + $server = ['type' => 'http', 'url' => $url]; + foreach ($headers as $header) { + $parts = explode(':', $header, 2); + if (count($parts) !== 2 || trim($parts[0]) === '') { + $io->error(sprintf('Header `%s` is not in the "Name: Value" form.', $header)); + + return null; + } + $server['headers'][trim($parts[0])] = trim($parts[1]); + } + $server['protocolEra'] = 'auto'; + + return $server; + } + + /** + * @return string The key of the server in the Inspector configuration. + */ + private function serverName(): string + { + return strtolower(Text::slug((string)McpConfig::get('server.name'))) ?: 'cakephp'; + } + + /** + * @param array $config The Inspector configuration. + * @return array The same, with header and environment values hidden. + */ + private function redact(array $config): array + { + foreach ($config['mcpServers'] as $name => $server) { + foreach (['headers', 'env'] as $secrets) { + foreach (array_keys($server[$secrets] ?? []) as $key) { + $config['mcpServers'][$name][$secrets][$key] = '***'; + } + } + } + + return $config; + } + + /** + * Writes the configuration to a file only the current user can read, since + * headers and environment variables may carry secrets. + * + * @param array $config The Inspector configuration. + * @return string|null The path, or null on failure. + */ + private function writeConfig(array $config): ?string + { + $temp = tempnam(sys_get_temp_dir(), 'mcp-inspector-'); + if ($temp === false) { + return null; + } + $file = $temp . '.json'; + if (!rename($temp, $file)) { + unlink($temp); + + return null; + } + chmod($file, 0600); + file_put_contents($file, (string)json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); + + return $file; + } +} diff --git a/src/Command/McpServerCommand.php b/src/Command/McpServerCommand.php new file mode 100644 index 0000000..5080b30 --- /dev/null +++ b/src/Command/McpServerCommand.php @@ -0,0 +1,75 @@ +out()`. + */ +class McpServerCommand extends Command +{ + /** + * @param \CakeDC\Mcp\Server\ServerFactory $serverFactory Builds the server. + * @param \CakeDC\Mcp\Identity\CurrentIdentity $identity Shared with the tools. + */ + public function __construct( + private readonly ServerFactory $serverFactory, + private readonly CurrentIdentity $identity, + ) { + } + + /** + * @inheritDoc + */ + public static function defaultName(): string + { + return 'mcp server'; + } + + /** + * @inheritDoc + */ + public static function getDescription(): string + { + return 'Serve MCP over stdio, for MCP clients running on this machine.'; + } + + /** + * @inheritDoc + */ + public function execute(Arguments $args, ConsoleIo $io): int + { + // The console framework mirrors info logs to STDOUT, which would corrupt the protocol. + // QUIET keeps only the stderr logger for errors and warnings. + $io->setLoggers(ConsoleIo::QUIET); + + $resolver = McpConfig::get('stdio.identity'); + $this->identity->set(is_callable($resolver) ? $resolver() : null); + + $this->serverFactory->create((bool)McpConfig::get('stdio.trusted'))->run($this->createTransport()); + + return static::CODE_SUCCESS; + } + + /** + * @return \Mcp\Server\Transport\TransportInterface + */ + protected function createTransport(): TransportInterface + { + return new StdioTransport(logger: new McpLogger()); + } +} diff --git a/src/Container/ContainerBridge.php b/src/Container/ContainerBridge.php new file mode 100644 index 0000000..8d2b741 --- /dev/null +++ b/src/Container/ContainerBridge.php @@ -0,0 +1,130 @@ + + */ + private array $instances = []; + + /** + * @var array + */ + private array $building = []; + + /** + * @param \Psr\Container\ContainerInterface $container The host container. + */ + public function __construct(private readonly ContainerInterface $container) + { + } + + /** + * @inheritDoc + */ + public function has(string $id): bool + { + return $this->container->has($id) || class_exists($id); + } + + /** + * @inheritDoc + */ + public function get(string $id): mixed + { + if ($this->container->has($id)) { + return $this->container->get($id); + } + if (isset($this->instances[$id])) { + return $this->instances[$id]; + } + if (!class_exists($id)) { + throw new NotFoundException(sprintf('`%s` is not registered in the container and is not a class.', $id)); + } + + return $this->instances[$id] = $this->build($id); + } + + /** + * @param class-string $class The class to build. + * @return object + */ + private function build(string $class): object + { + if (isset($this->building[$class])) { + throw new ContainerException(sprintf('Circular dependency while resolving `%s`.', $class)); + } + $reflection = new ReflectionClass($class); + if (!$reflection->isInstantiable()) { + throw new ContainerException(sprintf('`%s` is not instantiable.', $class)); + } + + $this->building[$class] = true; + try { + $constructor = $reflection->getConstructor(); + if ($constructor === null) { + return $reflection->newInstance(); + } + $arguments = []; + foreach ($constructor->getParameters() as $parameter) { + $arguments[] = $this->resolveParameter($parameter, $class); + } + + return $reflection->newInstanceArgs($arguments); + } finally { + unset($this->building[$class]); + } + } + + /** + * @param \ReflectionParameter $parameter The constructor parameter. + * @param string $class The class being built (for error messages). + * @return mixed + */ + private function resolveParameter(ReflectionParameter $parameter, string $class): mixed + { + $type = $parameter->getType(); + if ($type instanceof ReflectionNamedType && !$type->isBuiltin()) { + $name = $type->getName(); + if ($this->container->has($name) || isset($this->building[$name]) || $this->isInstantiable($name)) { + return $this->get($name); + } + } + if ($parameter->isDefaultValueAvailable()) { + return $parameter->getDefaultValue(); + } + if ($parameter->allowsNull()) { + return null; + } + + throw new ContainerException(sprintf( + 'Cannot resolve parameter `$%s` of `%s`.', + $parameter->getName(), + $class, + )); + } + + /** + * @param string $name A class or interface name. + * @return bool + */ + private function isInstantiable(string $name): bool + { + return class_exists($name) && (new ReflectionClass($name))->isInstantiable(); + } +} diff --git a/src/Container/ContainerException.php b/src/Container/ContainerException.php new file mode 100644 index 0000000..27d8a44 --- /dev/null +++ b/src/Container/ContainerException.php @@ -0,0 +1,11 @@ +skipHostAuthorization(); + // A long-running worker reuses the container: no request starts with the previous one's identity. + $identity->set(null); + $responseFactory = new ResponseFactory(); + $streamFactory = new StreamFactory(); + + try { + $maxBodyBytes = McpConfig::maxBodyBytes(); + $origins = array_values(array_filter((array)McpConfig::get('http.allowedOrigins'), 'is_string')); + $middleware = [ + new CorsMiddleware($origins), + new DnsRebindingProtectionMiddleware( + McpConfig::allowedHosts(), + $origins, + $responseFactory, + $streamFactory, + ), + // Before authentication: an oversized body gets a 413 that names the limit, never a + // Bearer challenge. + new BodyLimitMiddleware($maxBodyBytes, $responseFactory, $streamFactory), + ]; + $audit = AuditSettings::fromConfig(); + if ($audit->enabled) { + // Right before authentication, to record the calls it refuses. + $middleware[] = new AuditRefusalMiddleware($audit, new AuditWriter($audit), $identity); + } + $middleware[] = $this->authentication($identity, $responseFactory, $streamFactory); + $transport = new StreamableHttpTransport( + $this->request, + $responseFactory, + $streamFactory, + new McpLogger(), + $middleware, + $maxBodyBytes, + ); + $response = $factory->create()->run($transport); + } catch (Throwable $exception) { + Log::error(sprintf("MCP request failed.\n%s", $exception), ['scope' => [McpLogger::SCOPE]]); + + return $this->internalError(); + } + + return $this->toCakeResponse($response); + } + + /** + * The middleware that identifies the caller from the host's identity. An `auth.mode` other than + * `host` throws, so the endpoint fails closed. + * + * @param \CakeDC\Mcp\Identity\CurrentIdentity $identity Shared with the tools. + * @param \Psr\Http\Message\ResponseFactoryInterface $responseFactory For its responses. + * @param \Psr\Http\Message\StreamFactoryInterface $streamFactory For their bodies. + * @return \Psr\Http\Server\MiddlewareInterface + */ + private function authentication( + CurrentIdentity $identity, + ResponseFactoryInterface $responseFactory, + StreamFactoryInterface $streamFactory, + ): MiddlewareInterface { + McpConfig::assertHostAuthMode(); + $scopes = McpConfig::get('identity.scopes'); + + return new IdentityMiddleware( + $identity, + $responseFactory, + $streamFactory, + McpConfig::get('identity.required') !== false, + (string)McpConfig::get('identity.attribute'), + is_callable($scopes) ? Closure::fromCallable($scopes) : null, + ); + } + + /** + * @param mixed $response What the transport returned. + * @return \Cake\Http\Response + */ + private function toCakeResponse(mixed $response): Response + { + if (!$response instanceof ResponseInterface) { + return $this->internalError(); + } + if (!$response instanceof Response) { + $converted = (new Response()) + ->withStatus($response->getStatusCode(), $response->getReasonPhrase()) + ->withBody($response->getBody()); + foreach ($response->getHeaders() as $name => $values) { + $converted = $converted->withHeader($name, $values); + } + $response = $converted; + } + if (str_starts_with($response->getHeaderLine('Content-Type'), 'text/event-stream')) { + $response = $response->withHeader('X-Accel-Buffering', 'no'); + } + + return $response; + } + + /** + * Never Cake's HTML error page, never a stack trace, even in debug mode. + * + * @return \Cake\Http\Response + */ + private function internalError(): Response + { + return $this->response + ->withStatus(500) + ->withType('application/json') + ->withStringBody((string)json_encode([ + 'jsonrpc' => '2.0', + 'id' => null, + 'error' => ['code' => -32603, 'message' => 'Internal error'], + ])); + } +} diff --git a/src/Controller/SkipsHostAuthorizationTrait.php b/src/Controller/SkipsHostAuthorizationTrait.php new file mode 100644 index 0000000..3900f91 --- /dev/null +++ b/src/Controller/SkipsHostAuthorizationTrait.php @@ -0,0 +1,22 @@ +request->getAttribute('authorization'); + if (is_object($authorization) && method_exists($authorization, 'skipAuthorization')) { + $authorization->skipAuthorization(); + } + } +} diff --git a/src/Event/AuditListener.php b/src/Event/AuditListener.php new file mode 100644 index 0000000..df9d384 --- /dev/null +++ b/src/Event/AuditListener.php @@ -0,0 +1,273 @@ + + */ + private array $started = []; + + private Closure $clock; + + private ?Closure $toolExists; + + /** + * @param \CakeDC\Mcp\Audit\AuditSettings $settings The audit settings. + * @param \CakeDC\Mcp\Audit\AuditWriter $writer Writes the records. + * @param \CakeDC\Mcp\Authorization\ToolGate $gate The gate of the tool call guard. + * @param \CakeDC\Mcp\Identity\CurrentIdentity $identity The caller. + * @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. + */ + public function __construct( + private readonly AuditSettings $settings, + private readonly AuditWriter $writer, + private readonly ToolGate $gate, + private readonly CurrentIdentity $identity, + ?Closure $clock = null, + ?Closure $toolExists = null, + ) { + $this->clock = $clock ?? fn(): float => microtime(true); + $this->toolExists = $toolExists; + } + + /** + * The OAuth client of an access token: `client_id`, `azp`, or a single `aud`. + * + * @param \Mcp\Server\Authorization\AccessToken|null $token The token. + * @return string|null + */ + public static function clientOf(?AccessToken $token): ?string + { + if ($token === null) { + return null; + } + $client = $token->getClientId(); + if ($client !== null) { + return $client; + } + $audience = $token->getClaim('aud'); + if (is_array($audience) && count($audience) === 1) { + $audience = reset($audience); + } + + return is_string($audience) && $audience !== '' ? $audience : null; + } + + /** + * @param \Mcp\Event\RequestEvent $event The event. + * @return void + */ + public function onRequest(RequestEvent $event): void + { + $this->safely(fn() => $this->started($event)); + } + + /** + * @param \Mcp\Event\ResponseEvent $event The event. + * @return void + */ + public function onResponse(ResponseEvent $event): void + { + $this->safely(fn() => $this->responded($event)); + } + + /** + * @param \Mcp\Event\ErrorEvent $event The event. + * @return void + */ + public function onError(ErrorEvent $event): void + { + $this->safely(fn() => $this->failed($event)); + } + + /** + * Runs $work, and logs under `mcp` what it throws: the answer to the client must not depend on the + * record (the stateless era dispatches these events outside any try block). + * + * @param \Closure $work The work. + * @return void + */ + private function safely(Closure $work): void + { + try { + $work(); + } catch (Throwable $exception) { + try { + Log::error(sprintf('MCP audit: could not record a call: %s', $exception->getMessage()), [ + 'scope' => [McpLogger::SCOPE], + ]); + } catch (Throwable) { + // Nothing left to tell: the call goes on. + } + } + } + + /** + * @param \Mcp\Event\RequestEvent $event The event. + * @return void + */ + private function started(RequestEvent $event): void + { + $request = $event->getRequest(); + if ($this->settings->audits($request::getMethod())) { + $this->started[$this->key($request, $event->getSession())] = ($this->clock)(); + } + } + + /** + * @param \Mcp\Event\ResponseEvent $event The event. + * @return void + */ + private function responded(ResponseEvent $event): void + { + $request = $event->getRequest(); + $result = $event->getResponse()->result; + // A tool waiting for the user's input has not finished: the round that finishes it is recorded. + if (!$this->settings->audits($request::getMethod()) || $result instanceof InputRequiredResult) { + return; + } + $failed = $result instanceof CallToolResult && $result->isError; + + $this->record( + $request, + $event->getSession(), + $failed ? AuditRecord::TOOL_ERROR : AuditRecord::OK, + $failed ? $this->firstText($result) : null, + ); + } + + /** + * @param \Mcp\Event\ErrorEvent $event The event. + * @return void + */ + private function failed(ErrorEvent $event): void + { + $request = $event->getRequest(); + if (!$this->settings->audits($request::getMethod())) { + return; + } + $error = $event->getError(); + $outcome = match (true) { + $request instanceof CallToolRequest && $this->isDenied($request->name) => AuditRecord::DENIED, + $error->code === Error::INVALID_PARAMS => AuditRecord::INVALID, + default => AuditRecord::ERROR, + }; + + $this->record($request, $event->getSession(), $outcome, $error->message); + } + + /** + * @param \Mcp\Schema\JsonRpc\Request $request The audited request. + * @param \Mcp\Server\Session\SessionInterface $session Its session. + * @param string $outcome The outcome. + * @param string|null $error The error text. + * @return void + */ + private function record(Request $request, SessionInterface $session, string $outcome, ?string $error): void + { + $key = $this->key($request, $session); + $start = $this->started[$key] ?? null; + unset($this->started[$key]); + $token = $session->get(AccessToken::class); + + [$name, $arguments] = match (true) { + $request instanceof CallToolRequest => [$request->name, $request->arguments], + $request instanceof GetPromptRequest => [$request->name, $request->arguments], + $request instanceof ReadResourceRequest => [$request->uri, []], + default => [null, []], + }; + + $this->writer->write(new AuditRecord( + $request::getMethod(), + $name === null ? null : (string)AuditRecord::cap($name), + $outcome, + $this->identity->getIdentifier(), + self::clientOf($token instanceof AccessToken ? $token : null), + $session->getId()->toRfc4122(), + AuditRecord::cap($request->getId()), + $this->writer->arguments($arguments), + $error === null ? null : mb_substr($error, 0, self::MAX_ERROR_LENGTH), + $start === null ? null : (int)round((($this->clock)() - $start) * 1000), + )); + } + + /** + * Whether the gate refused an existing tool (an unknown tool is not a denial). + * + * @param string $name The tool. + * @return bool + */ + private function isDenied(string $name): bool + { + if ($this->gate->allows($name)) { + return false; + } + + return ($this->toolExists === null ? null : ($this->toolExists)($name)) !== false; + } + + /** + * @param \Mcp\Schema\Result\CallToolResult $result A tool error. + * @return string|null Its first text. + */ + private function firstText(CallToolResult $result): ?string + { + foreach ($result->content as $content) { + if ($content instanceof TextContent && is_string($content->text)) { + return $content->text; + } + } + + return null; + } + + /** + * @param \Mcp\Schema\JsonRpc\Request $request A request. + * @param \Mcp\Server\Session\SessionInterface $session Its session. + * @return string + */ + private function key(Request $request, SessionInterface $session): string + { + return $session->getId()->toRfc4122() . '|' . $request->getId(); + } +} diff --git a/src/Event/EventDispatcher.php b/src/Event/EventDispatcher.php new file mode 100644 index 0000000..696f433 --- /dev/null +++ b/src/Event/EventDispatcher.php @@ -0,0 +1,60 @@ +> + */ + private array $listeners = []; + + /** + * @param string $eventClass Class or interface name. + * @param callable $listener Receives the event. + * @return void + */ + public function listen(string $eventClass, callable $listener): void + { + $this->listeners[$eventClass][] = $listener; + } + + /** + * Yields the listeners whose registered class matches the event. + * + * @param object $event The event being dispatched. + * @return iterable + */ + public function getListenersForEvent(object $event): iterable + { + foreach ($this->listeners as $class => $listeners) { + if ($event instanceof $class) { + yield from $listeners; + } + } + } + + /** + * @inheritDoc + */ + public function dispatch(object $event): object + { + foreach ($this->getListenersForEvent($event) as $listener) { + if ($event instanceof StoppableEventInterface && $event->isPropagationStopped()) { + break; + } + $listener($event); + } + + return $event; + } +} diff --git a/src/Event/ToolListFilter.php b/src/Event/ToolListFilter.php new file mode 100644 index 0000000..9b601d9 --- /dev/null +++ b/src/Event/ToolListFilter.php @@ -0,0 +1,42 @@ +getResponse(); + $result = $response->result; + if (!$result instanceof ListToolsResult) { + 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))); + } +} diff --git a/src/Identity/CurrentIdentity.php b/src/Identity/CurrentIdentity.php new file mode 100644 index 0000000..a6681f1 --- /dev/null +++ b/src/Identity/CurrentIdentity.php @@ -0,0 +1,68 @@ +identity = $identity; + } + + /** + * @return mixed + */ + public function get(): mixed + { + return $this->identity; + } + + /** + * @return bool + */ + public function has(): bool + { + return $this->identity !== null; + } + + /** + * @return string|int|null + */ + public function getIdentifier(): string|int|null + { + return self::identifierOf($this->identity); + } + + /** + * The identifier of any identity shape: objects with `getIdentifier()` + * (cakephp/authentication), then arrays and `ArrayAccess` (entities, + * `ArrayObject`) through their `id`. + * + * @param mixed $identity The identity. + * @return string|int|null + */ + public static function identifierOf(mixed $identity): string|int|null + { + $id = null; + if (is_object($identity) && method_exists($identity, 'getIdentifier')) { + $id = $identity->getIdentifier(); + } elseif (is_array($identity) || $identity instanceof ArrayAccess) { + $id = $identity['id'] ?? null; + } + + return is_int($id) || is_string($id) ? $id : null; + } +} diff --git a/src/Log/McpLogger.php b/src/Log/McpLogger.php new file mode 100644 index 0000000..9366c6e --- /dev/null +++ b/src/Log/McpLogger.php @@ -0,0 +1,48 @@ + $context Context; `scope` is extended with `mcp`. + * @return void + */ + public function log(mixed $level, string|Stringable $message, array $context = []): void + { + $context['scope'] = array_merge((array)($context['scope'] ?? []), [self::SCOPE]); + $message = (string)$message; + + // Cake log engines only interpolate {placeholders}, so anything else in the + // context (the SDK passes the exception and the tool name) would be lost. + $extra = []; + foreach ($context as $key => $value) { + if ($key === 'scope' || str_contains($message, '{' . $key . '}')) { + continue; + } + if ($value instanceof Throwable) { + $extra[] = "\n" . (string)$value; + } elseif (is_scalar($value) || $value instanceof Stringable) { + $extra[] = ' ' . $key . '=' . $value; + } + } + // 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); + } +} diff --git a/src/McpConfig.php b/src/McpConfig.php new file mode 100644 index 0000000..1239a11 --- /dev/null +++ b/src/McpConfig.php @@ -0,0 +1,218 @@ + []` cannot disable authentication. + */ +final class McpConfig +{ + /** + * The only `auth.mode` of the 1.x line. The `oauth` and `external` modes need 2.x on CakePHP 5. + */ + public const AUTH_MODE_HOST = 'host'; + + /** + * @var array + */ + public const DEFAULTS = [ + 'route' => '/mcp', + 'server' => [ + 'name' => 'CakePHP MCP Server', + 'version' => '1.0.0', + 'title' => null, + 'description' => null, + 'websiteUrl' => null, + 'instructions' => null, + 'configure' => null, + ], + 'discovery' => ['scanDirs' => ['src/Mcp'], 'excludeDirs' => [], 'cache' => '_cake_mcp_'], + 'session' => ['cache' => 'mcp_sessions', 'ttl' => 3600], + 'http' => ['allowedHosts' => null, 'allowedOrigins' => [], 'maxBodyBytes' => 4 * 1024 * 1024], + 'identity' => ['required' => true, 'attribute' => 'identity', 'scopes' => null], + 'authorization' => ['authorizer' => AllowAllToolAuthorizer::class, 'rbac' => []], + 'auth' => ['mode' => self::AUTH_MODE_HOST], + 'stdio' => ['identity' => null, 'trusted' => true], + 'audit' => [ + 'enabled' => false, + 'methods' => ['tools/call'], + 'log' => true, + 'arguments' => true, + 'redact' => ['password', 'token', 'secret'], + 'maxLength' => 200, + ], + ]; + + /** + * @param string|null $path Dot path inside the `Mcp` config, or null for all of it. + * @return mixed + */ + public static function get(?string $path = null): mixed + { + $config = self::merge(self::DEFAULTS, (array)Configure::read('Mcp')); + + return $path === null ? $config : Hash::get($config, $path); + } + + /** + * 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. + * + * @return string|null + */ + public static function discoveryCache(): ?string + { + $name = self::get('discovery.cache'); + if (Configure::read('debug') || !is_string($name) || $name === '') { + return null; + } + + return $name; + } + + /** + * The largest request body the endpoint reads, in bytes (`http.maxBodyBytes`, 4 MiB by default, the + * 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. + * + * @return int + * @throws \InvalidArgumentException When the setting is not a positive integer, so the endpoint fails closed. + */ + public static function maxBodyBytes(): int + { + $value = self::get('http.maxBodyBytes'); + if (!is_int($value) || $value < 1) { + throw new InvalidArgumentException('`Mcp.http.maxBodyBytes` must be a positive integer (bytes).'); + } + + return $value; + } + + /** + * Hosts the DNS-rebinding protection accepts. Defaults to the host of + * `App.fullBaseUrl` plus localhost; the SDK default (localhost only) would + * reject every request to a real domain. + * + * @return list + */ + public static function allowedHosts(): array + { + $hosts = self::get('http.allowedHosts'); + if (is_array($hosts)) { + return array_values(array_map(fn(mixed $host): string => strtolower((string)$host), $hosts)); + } + + $allowed = ['localhost', '127.0.0.1', '[::1]']; + $host = parse_url((string)Configure::read('App.fullBaseUrl'), PHP_URL_HOST); + if (is_string($host) && $host !== '') { + array_unshift($allowed, strtolower($host)); + } + + return array_values(array_unique($allowed)); + } + + /** + * Fails when `auth.mode` is not `host`: the oauth and external modes of 2.x are not in this line, + * and running without the authentication they promise would open the endpoint. + * + * @return void + * @throws \InvalidArgumentException When another mode is configured. + */ + public static function assertHostAuthMode(): void + { + $mode = self::get('auth.mode'); + if ($mode === self::AUTH_MODE_HOST) { + return; + } + + throw new InvalidArgumentException(sprintf( + '"Mcp.auth.mode" %s is not available in cakedc/cakephp-mcp 1.x (CakePHP 4): only "host" is. ' + . 'The oauth and external modes need cakedc/cakephp-mcp 2.x on CakePHP 5.', + json_encode($mode), + )); + } + + /** + * Recursive merge where associative arrays merge and lists are replaced. + * + * @param array $base The defaults. + * @param array $override The host values. + * @return array + */ + private static function merge(array $base, array $override): array + { + foreach ($override as $key => $value) { + if ( + $value === [] && isset($base[$key]) && is_array($base[$key]) + && $base[$key] !== [] && !array_is_list($base[$key]) + ) { + // An empty array over an associative default is a misconfiguration, not an intent to clear it. + continue; + } + if ( + is_array($value) && isset($base[$key]) && is_array($base[$key]) + && !array_is_list($value) && !array_is_list($base[$key]) + ) { + $base[$key] = self::merge($base[$key], $value); + + continue; + } + $base[$key] = $value; + } + + return $base; + } + + /** + * The RBAC rule (cakedc/auth, `config/permissions.php`) that lets every request reach the MCP endpoint. + * cakedc/users authorizes the route before the controller runs, so without it an anonymous request is + * redirected to the login page instead of receiving the plugin's 401. The plugin decides access itself + * (authentication, then the tool authorizer). + * + * @return list> + */ + public static function rbacPermissions(): array + { + return [ + [ + 'role' => '*', + 'plugin' => 'CakeDC/Mcp', + 'controller' => 'Mcp', + 'action' => 'handle', + 'bypassAuth' => true, + ], + ]; + } + + /** + * Whether $request is for the MCP endpoint. 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. + * @return bool + */ + 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; + } +} diff --git a/src/McpPlugin.php b/src/McpPlugin.php index 2652e2b..f647ecd 100644 --- a/src/McpPlugin.php +++ b/src/McpPlugin.php @@ -3,86 +3,94 @@ namespace CakeDC\Mcp; +use Cake\Cache\Cache; +use Cake\Cache\Engine\FileEngine; use Cake\Console\CommandCollection; use Cake\Core\BasePlugin; use Cake\Core\ContainerInterface; use Cake\Core\PluginApplicationInterface; -use Cake\Http\MiddlewareQueue; use Cake\Routing\RouteBuilder; +use CakeDC\Mcp\Command\McpCheckCommand; +use CakeDC\Mcp\Command\McpInspectorCommand; +use CakeDC\Mcp\Command\McpServerCommand; +use CakeDC\Mcp\Identity\CurrentIdentity; +use CakeDC\Mcp\Server\ServerFactory; /** - * Plugin for Mcp + * Exposes an MCP (Model Context Protocol) server from a CakePHP application. */ class McpPlugin extends BasePlugin { /** - * Load all the plugin configuration and bootstrap logic. + * Checks `Mcp.auth.mode` and defines the discovery and session cache configs when the host did not. * - * The host application is provided as an argument. This allows you to load - * additional plugin dependencies, or attach events. - * - * @param \Cake\Core\PluginApplicationInterface $app The host application + * @param \Cake\Core\PluginApplicationInterface $app The host application. * @return void */ public function bootstrap(PluginApplicationInterface $app): void { - // remove this method hook if you don't need it + parent::bootstrap($app); + McpConfig::assertHostAuthMode(); + + $caches = [McpConfig::get('discovery.cache'), McpConfig::get('session.cache')]; + foreach ($caches as $name) { + if (!is_string($name) || $name === '' || Cache::getConfig($name) !== null) { + continue; + } + Cache::setConfig($name, [ + 'className' => FileEngine::class, + 'path' => CACHE . 'mcp' . DS, + 'prefix' => $name . '_', + 'duration' => '+1 hours', + ]); + } } /** - * Add routes for the plugin. - * - * If your plugin has many routes and you would like to isolate them into a separate file, - * you can create `$plugin/config/routes.php` and delete this method. + * Connects the MCP endpoint at `Mcp.route` (nothing when it is false). * - * @param \Cake\Routing\RouteBuilder $routes The route builder to update. + * @param \Cake\Routing\RouteBuilder $routes The route builder. * @return void */ public function routes(RouteBuilder $routes): void { - parent::routes($routes); - } - - /** - * Add middleware for the plugin. - * - * @param \Cake\Http\MiddlewareQueue $middlewareQueue The middleware queue to update. - * @return \Cake\Http\MiddlewareQueue - */ - public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue - { - // Add your middlewares here - // remove this method hook if you don't need it + $path = McpConfig::get('route'); + if (!is_string($path) || $path === '') { + return; + } - return $middlewareQueue; + $routes->connect($path, ['plugin' => 'CakeDC/Mcp', 'controller' => 'Mcp', 'action' => 'handle']) + ->setMethods(['GET', 'POST', 'DELETE', 'OPTIONS']); } /** - * Add commands for the plugin. + * Registers `bin/cake mcp server`, the stdio transport, `bin/cake mcp inspector` and `bin/cake mcp check`. * - * @param \Cake\Console\CommandCollection $commands The command collection to update. + * @param \Cake\Console\CommandCollection $commands The collection. * @return \Cake\Console\CommandCollection */ public function console(CommandCollection $commands): CommandCollection { - // Add your commands here - // remove this method hook if you don't need it - - $commands = parent::console($commands); - - return $commands; + return $commands + ->add('mcp server', McpServerCommand::class) + ->add('mcp inspector', McpInspectorCommand::class) + ->add('mcp check', McpCheckCommand::class); } /** - * Register application container services. - * - * @param \Cake\Core\ContainerInterface $container The Container to update. + * @param \Cake\Core\ContainerInterface $container The host container. * @return void - * @link https://book.cakephp.org/5/en/development/dependency-injection.html#dependency-injection */ public function services(ContainerInterface $container): void { - // Add your services here - // remove this method hook if you don't need it + $container->addShared(CurrentIdentity::class); + $container->addShared(ServerFactory::class) + ->addArgument($container) + ->addArgument(CurrentIdentity::class); + $container->add(McpServerCommand::class) + ->addArgument(ServerFactory::class) + ->addArgument(CurrentIdentity::class); + $container->add(McpCheckCommand::class) + ->addArgument(ServerFactory::class); } } diff --git a/src/Middleware/AuditRefusalMiddleware.php b/src/Middleware/AuditRefusalMiddleware.php new file mode 100644 index 0000000..9b39847 --- /dev/null +++ b/src/Middleware/AuditRefusalMiddleware.php @@ -0,0 +1,101 @@ +handle($request); + $status = $response->getStatusCode(); + $outcome = match (true) { + $status === 401 => AuditRecord::UNAUTHORIZED, + $status === 403 && str_contains($response->getHeaderLine('WWW-Authenticate'), 'error="insufficient_scope"') + => AuditRecord::INSUFFICIENT_SCOPE, + default => null, + }; + if ($outcome === null) { + return $response; + } + $message = $this->message($request); + if ($message === null) { + return $response; + } + $params = is_array($message['params'] ?? null) ? $message['params'] : []; + $name = $params['name'] ?? $params['uri'] ?? null; + $id = $message['id'] ?? null; + + $this->writer->write(new AuditRecord( + $message['method'], + is_string($name) ? (string)AuditRecord::cap($name) : null, + $outcome, + $outcome === AuditRecord::INSUFFICIENT_SCOPE ? $this->identity->getIdentifier() : null, + null, + null, + is_string($id) || is_int($id) ? AuditRecord::cap($id) : null, + $message['method'] === 'resources/read' ? [] : $this->writer->arguments($params['arguments'] ?? null), + $outcome === AuditRecord::UNAUTHORIZED ? 'Unauthorized' : 'insufficient_scope', + null, + )); + + return $response; + } + + /** + * The JSON-RPC request in the body, when it is one request of an audited method. + * + * @param \Psr\Http\Message\ServerRequestInterface $request The HTTP request. + * @return array{method: string, id?: mixed, params?: mixed}|null + */ + private function message(ServerRequestInterface $request): ?array + { + $body = $request->getBody(); + if ($body->isSeekable()) { + $body->rewind(); + } + $message = json_decode($body->getContents(), true); + if ( + !is_array($message) + || array_is_list($message) + || !is_string($message['method'] ?? null) + || !$this->settings->audits($message['method']) + ) { + return null; + } + + /** @var array{method: string, id?: mixed, params?: mixed} $message */ + return $message; + } +} diff --git a/src/Middleware/BodyLimitMiddleware.php b/src/Middleware/BodyLimitMiddleware.php new file mode 100644 index 0000000..e16d0f3 --- /dev/null +++ b/src/Middleware/BodyLimitMiddleware.php @@ -0,0 +1,115 @@ +getMethod() !== 'POST') { + return $handler->handle($request); + } + + $length = $request->getHeaderLine('Content-Length'); + if ($length !== '' && ctype_digit($length) && (int)$length > $this->maxBytes) { + return $this->tooLarge(); + } + + $body = $this->read($request->getBody()); + if ($body === null) { + return $this->tooLarge(); + } + + return $handler->handle($request->withBody($this->streamFactory->createStream($body))); + } + + /** + * @param \Psr\Http\Message\StreamInterface $stream The request body. + * @return string|null The body, or null when it is larger than the limit. + */ + private function read(StreamInterface $stream): ?string + { + if ($stream->isSeekable()) { + $stream->rewind(); + } + $size = $stream->getSize(); + if ($size !== null && $size > $this->maxBytes) { + return null; + } + + $contents = ''; + while (!$stream->eof()) { + // Never more than one byte past the limit is read, which is enough to know the body is too large. + $chunk = $stream->read(min(self::CHUNK, $this->maxBytes + 1 - strlen($contents))); + if ($chunk === '') { + break; + } + $contents .= $chunk; + if (strlen($contents) > $this->maxBytes) { + return null; + } + } + + return $contents; + } + + /** + * @return \Psr\Http\Message\ResponseInterface + */ + private function tooLarge(): ResponseInterface + { + $payload = json_encode([ + 'jsonrpc' => '2.0', + 'id' => null, + 'error' => [ + 'code' => -32600, + 'message' => sprintf( + 'Request body too large: the limit is %d bytes (Mcp.http.maxBodyBytes). Send a smaller payload, ' + . 'for example a smaller file or fewer items per call.', + $this->maxBytes, + ), + 'data' => ['maxBodyBytes' => $this->maxBytes], + ], + ], JSON_THROW_ON_ERROR); + + return $this->responseFactory->createResponse(413) + ->withHeader('Content-Type', 'application/json') + ->withBody($this->streamFactory->createStream($payload)); + } +} diff --git a/src/Middleware/IdentityMiddleware.php b/src/Middleware/IdentityMiddleware.php new file mode 100644 index 0000000..1ec68f3 --- /dev/null +++ b/src/Middleware/IdentityMiddleware.php @@ -0,0 +1,103 @@ +current->set(null); + + if ($request->getMethod() === 'OPTIONS') { + return $handler->handle($request); + } + + $identity = $request->getAttribute($this->attribute); + if ($identity === null) { + return $this->required ? $this->unauthorized() : $handler->handle($request); + } + + $this->current->set($identity); + + return $handler->handle($request->withAttribute( + AccessToken::class, + self::accessTokenFor($identity, $this->scopes), + )); + } + + /** + * The SDK access token for a host identity: its identifier as the `sub` + * claim, and the scopes returned by `$scopes`. + * + * @param mixed $identity The identity. + * @param \Closure|null $scopes `fn(mixed $identity): array` returning scope strings. + * @return \Mcp\Server\Authorization\AccessToken + */ + public static function accessTokenFor(mixed $identity, ?Closure $scopes = null): AccessToken + { + $claims = []; + $identifier = CurrentIdentity::identifierOf($identity); + if ($identifier !== null) { + $claims['sub'] = (string)$identifier; + } + $granted = $scopes === null ? [] : $scopes($identity); + $granted = is_array($granted) ? array_values(array_filter($granted, 'is_string')) : []; + + return new AccessToken($granted, $claims); + } + + /** + * @return \Psr\Http\Message\ResponseInterface + */ + private function unauthorized(): ResponseInterface + { + $body = (string)json_encode([ + 'error' => 'unauthorized', + 'error_description' => 'Authentication required.', + ]); + + return $this->responseFactory->createResponse(401) + ->withHeader('WWW-Authenticate', 'Bearer') + ->withHeader('Content-Type', 'application/json') + ->withBody($this->streamFactory->createStream($body)); + } +} diff --git a/src/Server/CakeServer.php b/src/Server/CakeServer.php deleted file mode 100644 index 7290a4d..0000000 --- a/src/Server/CakeServer.php +++ /dev/null @@ -1,50 +0,0 @@ -bootstrap(); - - if (!Configure::read('App.base')) { - Configure::write('App.base', ''); - } - - self::$application->pluginBootstrap(); - } - - public static function builder(BaseApplication $application): Builder - { - self::$application = $application; - self::bootstrap(); - - return Server::builder(); - } - - public function connect(TransportInterface $transport): void - { - $this->server->connect($transport); - } -} diff --git a/src/Server/ServerFactory.php b/src/Server/ServerFactory.php new file mode 100644 index 0000000..e7b4830 --- /dev/null +++ b/src/Server/ServerFactory.php @@ -0,0 +1,280 @@ +identity; + } + + /** + * @param bool $trusted Skip per-tool authorization (stdio started by the developer). + * @return \Mcp\Server + */ + public function create(bool $trusted = false): Server + { + return $this->build($trusted, new McpLogger()); + } + + /** + * @param bool $trusted Skip per-tool authorization. + * @param \Psr\Log\LoggerInterface $logger What the SDK logs. + * @return \Mcp\Server + */ + private function build(bool $trusted, LoggerInterface $logger): Server + { + $gate = new ToolGate($this->authorizer(), $this->identity, $trusted); + $events = new EventDispatcher(); + $events->listen(ResponseEvent::class, new ToolListFilter($gate)); + // The guard goes first: the SDK asks request handlers in the order they were added. + $builder = Server::builder()->addRequestHandler(new ToolCallGuard($gate)); + $audit = AuditSettings::fromConfig(); + 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, + ); + $events->listen(RequestEvent::class, $listener->onRequest(...)); + $events->listen(ResponseEvent::class, $listener->onResponse(...)); + $events->listen(ErrorEvent::class, $listener->onError(...)); + } + $this->configure($builder); + // 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'), + $this->optionalString('server.description'), + websiteUrl: $this->optionalString('server.websiteUrl'), + title: $this->optionalString('server.title'), + ) + ->setContainer(new ContainerBridge($this->container)) + ->setLogger($logger) + ->setEventDispatcher($events) + ->setSession(new Psr16SessionStore( + Cache::pool((string)McpConfig::get('session.cache')), + 'mcp-', + (int)McpConfig::get('session.ttl'), + )); + + $instructions = McpConfig::get('server.instructions'); + if (is_string($instructions) && $instructions !== '') { + $builder->setInstructions($instructions); + } + + $scanDirs = $this->existingDirs((array)McpConfig::get('discovery.scanDirs')); + 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, + ); + } + + return $builder->build(); + } + + /** + * Runs the `Mcp.server.configure` hook, which may use anything the SDK + * builder offers (tools added in code, request state, cache policy...). + * + * @param \Mcp\Server\Builder $builder The SDK builder. + * @return void + */ + private function configure(Builder $builder): void + { + $configure = McpConfig::get('server.configure'); + if ($configure === null) { + return; + } + if (!is_callable($configure)) { + throw new InvalidArgumentException(sprintf( + '`Mcp.server.configure` must be a callable that receives the SDK `%s`.', + Builder::class, + )); + } + $configure($builder); + } + + /** + * @param string $path Dot path inside the `Mcp` config. + * @return string|null The value, or null when it is not a non-empty string. + */ + private function optionalString(string $path): ?string + { + $value = McpConfig::get($path); + + return is_string($value) && $value !== '' ? $value : null; + } + + /** + * Keeps only the scan directories that exist, so a host that has not + * created its tools directory yet gets an empty tool list, not an error. + * + * @param array $dirs Directories relative to ROOT. + * @return list + */ + private function existingDirs(array $dirs): array + { + $existing = []; + foreach ($dirs as $dir) { + if (is_string($dir) && is_dir(rtrim(ROOT, DS) . DS . $dir)) { + $existing[] = $dir; + } + } + + return $existing; + } + + /** + * 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 + * @throws \RuntimeException When the server cannot list its tools. + */ + public function toolNames(): array + { + $names = []; + $cursor = null; + for ($page = 0; $page < 100; $page++) { + $list = ['jsonrpc' => '2.0', 'id' => 2, 'method' => 'tools/list']; + if ($cursor !== null) { + $list['params'] = ['cursor' => $cursor]; + } + $transport = new RecordingTransport([ + (string)json_encode(['jsonrpc' => '2.0', 'id' => 1, 'method' => 'initialize', 'params' => [ + 'protocolVersion' => ProtocolVersion::latestHandshake()->value, + 'capabilities' => new stdClass(), + 'clientInfo' => ['name' => 'cakephp-mcp', 'version' => '1.0'], + ]]), + (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 { + /** + * @param mixed $level PSR-3 level. + * @param \Stringable|string $message The message. + * @param array $context Context. + * @return void + */ + 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); + $result = $transport->responseFor(2)['result'] ?? null; + if (!is_array($result) || !is_array($result['tools'] ?? null)) { + throw new RuntimeException( + 'The server could not list its tools: ' . json_encode($transport->responseFor(2)), + ); + } + foreach ($result['tools'] as $tool) { + if (is_array($tool) && is_string($tool['name'] ?? null)) { + $names[] = $tool['name']; + } + } + $cursor = $result['nextCursor'] ?? null; + if (!is_string($cursor)) { + break; + } + } + + return $names; + } + + /** + * The configured tool authorizer (`Mcp.authorization.authorizer`), built as the server builds it. + * + * @internal Used by `bin/cake mcp check`; not part of the public API. + * @return \CakeDC\Mcp\Authorization\ToolAuthorizerInterface + */ + public function authorizer(): ToolAuthorizerInterface + { + $authorizer = McpConfig::get('authorization.authorizer'); + if ($authorizer instanceof ToolAuthorizerInterface) { + return $authorizer; + } + if ($authorizer === RbacToolAuthorizer::class) { + return new RbacToolAuthorizer((array)McpConfig::get('authorization.rbac')); + } + if (is_string($authorizer) && is_subclass_of($authorizer, ToolAuthorizerInterface::class)) { + $instance = (new ContainerBridge($this->container))->get($authorizer); + if ($instance instanceof ToolAuthorizerInterface) { + return $instance; + } + } + + throw new InvalidArgumentException(sprintf( + '`Mcp.authorization.authorizer` must be an instance or class name of `%s`.', + ToolAuthorizerInterface::class, + )); + } +} diff --git a/src/TestSuite/McpTestTrait.php b/src/TestSuite/McpTestTrait.php new file mode 100644 index 0000000..a84b4bf --- /dev/null +++ b/src/TestSuite/McpTestTrait.php @@ -0,0 +1,476 @@ +|null + */ + protected ?array $_mcpScopes = null; + + /** + * Claims added to the access token. + * + * @var array + */ + protected array $_mcpClaims = []; + + /** + * The JSON-RPC response to the last `mcpCallTool()`. + * + * @var array|null + */ + protected ?array $_mcpResponse = null; + + /** + * The name of the tool of the last `mcpCallTool()`. + */ + protected ?string $_mcpTool = null; + + /** + * What the server logged in the `mcp` scope during the last `mcpCallTool()`, + * warnings and worse. Shown when an assertion fails. + * + * @var list + */ + protected array $_mcpLog = []; + + /** + * Makes the next calls as this identity, in the shape your authentication + * produces (an entity, an `ArrayObject`, an array...). Null makes them anonymous. + * + * With $scopes the access token carries them instead of the scopes returned by the + * `identity.scopes` callable. + * + * @param mixed $identity The identity. + * @param list|null $scopes The token's scopes; null keeps the `identity.scopes` callable. + * @param array $claims Claims added to the token (they win over `sub`). + * @return void + */ + public function mcpActingAs(mixed $identity, ?array $scopes = null, array $claims = []): void + { + $this->_mcpIdentity = $identity; + $this->_mcpScopes = $scopes === null ? null : array_values(array_filter($scopes, 'is_string')); + $this->_mcpClaims = $claims; + } + + /** + * Calls a tool and keeps the response for the `assertMcp*()` methods. + * + * @param string $name The tool name. + * @param array $arguments The tool arguments. + * @return array The JSON-RPC response. + */ + public function mcpCallTool(string $name, array $arguments = []): array + { + $this->_mcpTool = $name; + $this->_mcpResponse = $this->mcpRequest('tools/call', [ + 'name' => $name, + 'arguments' => $arguments === [] ? new stdClass() : $arguments, + ], log: $this->_mcpLog); + + return $this->_mcpResponse; + } + + /** + * 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()`. + */ + public function mcpResponse(): array + { + if ($this->_mcpResponse === null) { + Assert::fail('No tool was called yet. Call mcpCallTool() first.'); + } + + 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, + array_column($this->mcpToolDefinitions(true), 'name'), + $message ?: sprintf('Tool "%s" is not registered, so its rejection proves nothing. Check the name.', $tool), + ); + } + + /** + * 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 that the current identity sees a tool in `tools/list`. + * + * @param string $name The tool name. + * @param string $message The failure message. + * @return void + */ + public function assertMcpToolListed(string $name, string $message = ''): void + { + Assert::assertContains( + $name, + array_column($this->mcpListTools(), 'name'), + $message ?: sprintf('Tool "%s" is not listed for the current identity.', $name), + ); + } + + /** + * Asserts that the current identity does not see a tool in `tools/list`. It + * also checks that the tool exists, so a typo cannot pass as hidden. + * + * @param string $name The tool name. + * @param string $message The failure message. + * @return void + */ + public function assertMcpToolNotListed(string $name, string $message = ''): void + { + Assert::assertNotContains( + $name, + array_column($this->mcpListTools(), 'name'), + $message ?: sprintf('Tool "%s" is listed for the current identity.', $name), + ); + Assert::assertContains( + $name, + array_column($this->mcpToolDefinitions(true), 'name'), + $message ?: sprintf('Tool "%s" is not registered, so its absence proves nothing. Check the name.', $name), + ); + } + + /** + * The container the server is built from: the application's, after its + * bootstrap, with the services replaced through `mockService()`. + * + * @return \Cake\Core\ContainerInterface + */ + protected function mcpContainer(): ContainerInterface + { + $app = $this->createApp(); + $app->bootstrap(); + if ($app instanceof PluginApplicationInterface) { + $app->pluginBootstrap(); + } + // createApp() resets the routes. Load them as the HTTP and console runners do, + // so tools that build URLs work as in production. + if ($app instanceof RoutingApplicationInterface) { + $builder = Router::createRouteBuilder('/'); + $app->routes($builder); + if ($app instanceof PluginApplicationInterface) { + $app->pluginRoutes($builder); + } + } + if (!$app instanceof ContainerApplicationInterface) { + Assert::fail(sprintf('`%s` has no container to build the MCP server from.', $app::class)); + } + + return $app->getContainer(); + } + + /** + * Sends one request after the initialize handshake. + * + * @param string $method The JSON-RPC method. + * @param array|null $params Its params. + * @param bool $trusted Skip the authorizer. + * @param list $log Receives what the server logged, warnings and worse. + * @return array + */ + private function mcpRequest(string $method, ?array $params, bool $trusted = false, array &$log = []): array + { + $request = ['jsonrpc' => '2.0', 'id' => 2, 'method' => $method]; + if ($params !== null) { + $request['params'] = $params; + } + + $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->identity()->set($this->_mcpIdentity); + + $scopes = McpConfig::get('identity.scopes'); + $token = null; + if ($this->_mcpIdentity !== null) { + $token = IdentityMiddleware::accessTokenFor( + $this->_mcpIdentity, + is_callable($scopes) ? Closure::fromCallable($scopes) : null, + ); + if ($this->_mcpScopes !== null || $this->_mcpClaims !== []) { + $token = new AccessToken( + $this->_mcpScopes ?? $token->getScopes(), + $this->_mcpClaims + $token->getClaims(), + ); + } + } + $transport = new RecordingTransport( + [ + (string)json_encode(['jsonrpc' => '2.0', 'id' => 1, 'method' => 'initialize', 'params' => [ + 'protocolVersion' => ProtocolVersion::latestHandshake()->value, + 'capabilities' => new stdClass(), + 'clientInfo' => ['name' => 'McpTestTrait', 'version' => '1.0'], + ]]), + (string)json_encode(['jsonrpc' => '2.0', 'method' => 'notifications/initialized']), + (string)json_encode($request), + ], + $token, + ); + // The real exception of a failing tool only reaches the log, rarely configured in tests. + $logConfig = '_mcp_test_trait'; + Log::setConfig($logConfig, [ + 'className' => ArrayLog::class, + 'scopes' => [McpLogger::SCOPE], + 'levels' => ['warning', 'error', 'critical', 'alert', 'emergency'], + ]); + try { + $factory->create($trusted)->run($transport); + } finally { + $engine = Log::engine($logConfig); + $log = $engine instanceof ArrayLog ? array_values(array_map('strval', $engine->read())) : []; + Log::drop($logConfig); + } + + $response = $transport->responseFor(2); + if ($response === null) { + Assert::fail(sprintf('The server sent no response to `%s`.', $method)); + } + + return $response; + } + + /** + * @param bool $trusted Skip the authorizer, to see every registered tool. + * @return list> + */ + private function mcpToolDefinitions(bool $trusted): array + { + $tools = []; + $cursor = null; + for ($page = 0; $page < 100; $page++) { + $response = $this->mcpRequest('tools/list', $cursor === null ? null : ['cursor' => $cursor], $trusted); + $result = $response['result'] ?? null; + if (!is_array($result) || !is_array($result['tools'] ?? null)) { + Assert::fail('tools/list failed: ' . $this->mcpJson($response)); + } + foreach ($result['tools'] as $tool) { + if (is_array($tool)) { + $tools[] = $tool; + } + } + $cursor = $result['nextCursor'] ?? null; + if (!is_string($cursor)) { + break; + } + } + + return $tools; + } + + /** + * @return array The `result` of the last tool call, or an empty array. + */ + private function mcpResult(): array + { + $result = $this->mcpResponse()['result'] ?? null; + + return is_array($result) ? $result : []; + } + + /** + * @param mixed $value A decoded JSON value. + * @return mixed The value with the keys of its objects sorted, recursively. + */ + private function mcpSortKeys(mixed $value): mixed + { + if (!is_array($value)) { + return $value; + } + $value = array_map($this->mcpSortKeys(...), $value); + if (!array_is_list($value)) { + ksort($value); + } + + return $value; + } + + /** + * @return string The server log of the last call, for failure messages, or an empty string. + */ + private function mcpLogText(): string + { + return $this->_mcpLog === [] ? '' : "\nServer log:\n" . implode("\n", $this->_mcpLog); + } + + /** + * @param array $value A decoded JSON value. + * @return string + */ + private function mcpJson(array $value): string + { + return (string)json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + } +} diff --git a/src/TestSuite/RecordingTransport.php b/src/TestSuite/RecordingTransport.php new file mode 100644 index 0000000..706d22e --- /dev/null +++ b/src/TestSuite/RecordingTransport.php @@ -0,0 +1,67 @@ +> + */ + public array $sent = []; + + /** + * @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. + */ + public function __construct(array $messages = [], private readonly ?AccessToken $accessToken = null) + { + parent::__construct($messages); + } + + /** + * @inheritDoc + */ + protected function handleMessage(string $payload, ?Uuid $sessionId, ?AccessToken $accessToken = null): void + { + parent::handleMessage($payload, $sessionId, $accessToken ?? $this->accessToken); + } + + /** + * @inheritDoc + */ + public function send(string $data, array $context): void + { + $decoded = json_decode($data, true); + if (is_array($decoded)) { + $this->sent[] = $decoded; + } + parent::send($data, $context); + } + + /** + * @param string|int $id The id of the request. + * @return array|null The response to that request. + */ + public function responseFor(string|int $id): ?array + { + foreach ($this->sent as $message) { + if (($message['id'] ?? null) === $id) { + return $message; + } + } + + return null; + } +} diff --git a/src/Tool/ToolError.php b/src/Tool/ToolError.php new file mode 100644 index 0000000..44f1b88 --- /dev/null +++ b/src/Tool/ToolError.php @@ -0,0 +1,74 @@ + $errors The entity or its errors. + * @param string $message The first line of the message. + * @return \Mcp\Exception\ToolCallException + */ + public static function invalid( + EntityInterface|array $errors, + string $message = 'The data is invalid.', + ): ToolCallException { + $lines = [$message]; + $fields = self::flatten($errors instanceof EntityInterface ? $errors->getErrors() : $errors); + foreach ($fields as $field => $messages) { + $text = implode('; ', $messages); + $lines[] = $field === '' ? '- ' . $text : sprintf('- %s: %s', $field, $text); + } + + return new ToolCallException(implode("\n", $lines)); + } + + /** + * Turns Cake's nested errors into messages keyed by dotted field path. A + * string is a message, and its key is the name of the rule that failed. At + * the top level, where Cake never puts a message, a string under a named key + * is a hand-written `field => message`. + * + * @param array $errors Nested errors. + * @param string $path The path of $errors. + * @return array> + */ + private static function flatten(array $errors, string $path = ''): array + { + $flat = []; + foreach ($errors as $key => $value) { + if (is_string($value)) { + $field = $path === '' && is_string($key) ? $key : $path; + $flat[$field][] = $value; + + continue; + } + if (!is_array($value)) { + continue; + } + $child = $path === '' ? (string)$key : $path . '.' . $key; + foreach (self::flatten($value, $child) as $field => $messages) { + $flat[$field] = array_merge($flat[$field] ?? [], $messages); + } + } + + return $flat; + } +} diff --git a/tests/Conformance/ConformanceFixture.php b/tests/Conformance/ConformanceFixture.php new file mode 100644 index 0000000..4688fba --- /dev/null +++ b/tests/Conformance/ConformanceFixture.php @@ -0,0 +1,313 @@ +setRegistry($registry) + ->addTool( + static fn() => 'This is a simple text response for testing.', + name: 'test_simple_text', + description: 'Tests simple text content response', + ) + ->addTool( + static fn() => new ImageContent(Elements::TEST_IMAGE_BASE64, 'image/png'), + name: 'test_image_content', + description: 'Tests image content response', + ) + ->addTool( + static fn() => new AudioContent(Elements::TEST_AUDIO_BASE64, 'audio/wav'), + name: 'test_audio_content', + description: 'Tests audio content response', + ) + ->addTool( + static fn() => EmbeddedResource::fromText( + 'test://embedded-resource', + 'This is an embedded resource content.', + ), + name: 'test_embedded_resource', + description: 'Tests embedded resource content response', + ) + ->addTool( + [Elements::class, 'toolMultipleTypes'], + name: 'test_multiple_content_types', + description: 'Tests response with multiple content types', + ) + ->addTool( + static fn() => CallToolResult::error([ + new TextContent('This tool intentionally returns an error for testing'), + ]), + name: 'test_error_handling', + description: 'Tests error response handling', + ) + ->addTool( + static fn() => 'ok', + name: 'json_schema_2020_12_tool', + description: 'Tool with JSON Schema 2020-12 features', + inputSchema: Elements::jsonSchema2020_12Fixture(), + ) + ->addTool( + static function (): never { + throw new MissingRequiredClientCapabilityException( + new ClientCapabilities(roots: false, sampling: true), + 'test_missing_capability requires the sampling capability.', + ); + }, + name: 'test_missing_capability', + description: 'Always reports a missing client capability, for testing -32021 handling', + ) + ->addTool( + static fn(): InputRequiredResult => new InputRequiredResult( + [ + 'conformance_probe' => new ElicitRequest( + 'Please provide a value for the conformance probe.', + new ElicitationSchema(['value' => new StringSchemaDefinition('Value')], ['value']), + ), + ], + requestState: base64_encode( + json_encode(['tool' => 'test_streaming_elicitation'], JSON_THROW_ON_ERROR), + ), + ), + name: 'test_streaming_elicitation', + description: 'Returns an InputRequiredResult asking for elicitation input', + ) + ->addTool( + static function () use ($logger): string { + $logger->info('test_logging_tool executed'); + + return 'Logged.'; + }, + name: 'test_logging_tool', + description: 'Emits a server-side log message while returning normally', + ) + ->addTool( + static fn(string $region = '', int $retries = 0): string => sprintf( + 'region=%s retries=%d', + $region, + $retries, + ), + name: 'test_custom_headers', + description: 'Tests custom header mirroring via x-mcp-header', + inputSchema: [ + 'type' => 'object', + 'properties' => [ + 'region' => ['type' => 'string', 'x-mcp-header' => 'Region'], + 'retries' => ['type' => 'integer', 'x-mcp-header' => 'Retries'], + ], + 'required' => ['region'], + ], + ) + ->addTool( + [Elements::class, 'toolWithProgress'], + name: 'test_tool_with_progress', + description: 'Tests tool that reports progress notifications', + ) + ->addTool( + [Elements::class, 'toolWithLogging'], + name: 'test_tool_with_logging', + description: 'Tests tool that emits log messages', + ) + ->addTool( + [Elements::class, 'toolWithSampling'], + name: 'test_sampling', + description: 'Tests server-initiated sampling', + ) + ->addTool( + [Elements::class, 'toolWithElicitation'], + name: 'test_elicitation', + description: 'Tests server-initiated elicitation', + ) + ->addTool( + [Elements::class, 'toolWithElicitationDefaults'], + name: 'test_elicitation_sep1034_defaults', + description: 'Tests elicitation with default values', + ) + ->addTool( + [Elements::class, 'toolWithElicitationEnums'], + name: 'test_elicitation_sep1330_enums', + description: 'Tests elicitation with enum schemas', + ) + ->addTool( + static function () use ($registry): string { + $registry->registerTool( + new Tool( + name: 'test_ephemeral_tool_' . bin2hex(random_bytes(4)), + title: null, + inputSchema: ['type' => 'object', 'properties' => new stdClass(), 'required' => null], + description: 'Registered to trigger a list change', + annotations: null, + ), + static fn(): string => 'ephemeral', + ); + + return 'Tool list mutated.'; + }, + name: 'test_trigger_tool_change', + description: 'Registers a tool so the tool list changes', + ) + ->addTool( + static function () use ($registry): string { + $registry->registerPrompt( + new Prompt( + 'test_ephemeral_prompt_' . bin2hex(random_bytes(4)), + null, + 'Registered to trigger a list change', + ), + static fn(): array => [['role' => 'user', 'content' => 'ephemeral']], + ); + + return 'Prompt list mutated.'; + }, + name: 'test_trigger_prompt_change', + description: 'Registers a prompt so the prompt list changes', + ) + ->addTool( + [MrtrElements::class, 'elicitation'], + name: 'test_input_required_result_elicitation', + description: 'MRTR: asks for a name via elicitation', + ) + ->addTool( + [MrtrElements::class, 'sampling'], + name: 'test_input_required_result_sampling', + description: 'MRTR: asks for a sampling completion', + ) + ->addTool( + [MrtrElements::class, 'listRoots'], + name: 'test_input_required_result_list_roots', + description: 'MRTR: asks for the client roots', + ) + ->addTool( + [MrtrElements::class, 'elicitation'], + name: 'test_input_required_result_request_state', + description: 'MRTR: exercises requestState round-tripping', + ) + ->addTool( + [MrtrElements::class, 'multipleInputs'], + name: 'test_input_required_result_multiple_inputs', + description: 'MRTR: asks for two inputs at once', + ) + ->addTool( + [MrtrElements::class, 'multiRound'], + name: 'test_input_required_result_multi_round', + description: 'MRTR: asks across two sequential rounds', + ) + ->addTool( + [MrtrElements::class, 'capabilities'], + name: 'test_input_required_result_capabilities', + description: 'MRTR: asks only for capabilities the client declared', + ) + ->addTool( + [MrtrElements::class, 'tamperedState'], + name: 'test_input_required_result_tampered_state', + description: 'MRTR: completes only when the echoed state verifies', + ) + ->addResource( + static fn() => 'This is the content of the static text resource.', + 'test://static-text', + 'static-text', + 'A static text resource for testing', + ) + ->addResource( + static fn() => fopen('data://image/png;base64,' . Elements::TEST_IMAGE_BASE64, 'r'), + 'test://static-binary', + 'static-binary', + 'A static binary resource (image) for testing', + ) + ->addResourceTemplate( + [Elements::class, 'resourceTemplate'], + 'test://template/{id}/data', + 'template', + 'A resource template with parameter substitution', + 'application/json', + ) + ->addResource( + static fn() => 'Watched resource content', + 'test://watched-resource', + 'watched-resource', + 'A resource that can be watched', + ) + ->addPrompt( + static fn() => [['role' => 'user', 'content' => 'This is a simple prompt for testing.']], + name: 'test_simple_prompt', + description: 'A simple prompt without arguments', + ) + ->addPrompt( + [Elements::class, 'promptWithArguments'], + name: 'test_prompt_with_arguments', + description: 'A prompt with required arguments', + ) + ->addPrompt( + [Elements::class, 'promptWithEmbeddedResource'], + name: 'test_prompt_with_embedded_resource', + description: 'A prompt that includes an embedded resource', + ) + ->addPrompt( + [Elements::class, 'promptWithImage'], + name: 'test_prompt_with_image', + description: 'A prompt that includes image content', + ) + ->addPrompt( + [MrtrElements::class, 'prompt'], + name: 'test_input_required_result_prompt', + description: 'MRTR: a prompt that asks for input first', + ) + // Fixed, so a retry served by another worker still verifies. + ->setRequestState(str_repeat('conformance-fixture-key-', 2)) + ->setNotificationBus($bus) + // Short, so a listen stream does not hold a php-fpm worker for the whole run. + ->setSubscriptionLifetime(5.0) + ->setCachePolicy( + CachePolicy::default(60_000) + ->withMethod('tools/list', 3_600_000, CacheScope::Public) + ->withMethod('prompts/list', 3_600_000, CacheScope::Public) + ->withMethod('resources/list', 3_600_000, CacheScope::Public) + ->withMethod('resources/templates/list', 3_600_000, CacheScope::Public) + ->withMethod('server/discover', 3_600_000, CacheScope::Public), + ); + } +} diff --git a/tests/Conformance/Dockerfile b/tests/Conformance/Dockerfile new file mode 100644 index 0000000..9ef7c23 --- /dev/null +++ b/tests/Conformance/Dockerfile @@ -0,0 +1,8 @@ +# php-fpm with intl, which CakePHP needs. PHP_VERSION follows the host that +# installed vendor/ (see run.sh), so Composer's platform check passes. +ARG PHP_VERSION=8.3 +FROM mirror.gcr.io/library/php:${PHP_VERSION}-fpm-alpine +RUN apk add --no-cache icu-libs \ + && apk add --no-cache --virtual .build-deps icu-dev $PHPIZE_DEPS \ + && docker-php-ext-install intl \ + && apk del .build-deps diff --git a/tests/Conformance/Sdk/Elements.php b/tests/Conformance/Sdk/Elements.php new file mode 100644 index 0000000..89b5b2f --- /dev/null +++ b/tests/Conformance/Sdk/Elements.php @@ -0,0 +1,247 @@ + + */ + public static function jsonSchema2020_12Fixture(): array + { + return [ + '$schema' => 'https://json-schema.org/draft/2020-12/schema', + 'type' => 'object', + '$defs' => [ + 'address' => [ + '$anchor' => 'addressDef', + 'type' => 'object', + 'properties' => [ + 'street' => ['type' => 'string'], + 'city' => ['type' => 'string'], + ], + ], + ], + 'properties' => [ + 'name' => ['type' => 'string'], + 'address' => ['$ref' => '#/$defs/address'], + 'contactMethod' => ['type' => 'string', 'enum' => ['phone', 'email']], + 'phone' => ['type' => 'string'], + 'email' => ['type' => 'string'], + ], + 'allOf' => [['anyOf' => [['required' => ['phone']], ['required' => ['email']]]]], + 'if' => [ + 'properties' => ['contactMethod' => ['const' => 'phone']], + 'required' => ['contactMethod'], + ], + 'then' => ['required' => ['phone']], + 'else' => ['required' => ['email']], + 'additionalProperties' => false, + ]; + } + + public function toolMultipleTypes(): CallToolResult + { + return new CallToolResult([ + new TextContent('Multiple content types test:'), + new ImageContent(self::TEST_IMAGE_BASE64, 'image/png'), + EmbeddedResource::fromText( + 'test://mixed-content-resource', + '{ "test" = "data", "value" = 123 }', + 'application/json', + ), + ]); + } + + public function toolWithLogging(RequestContext $context): string + { + $logger = $context->getClientLogger(); + + $logger->info('Tool execution started'); + $logger->info('Tool processing data'); + $logger->info('Tool execution completed'); + + return 'Tool with logging executed successfully'; + } + + public function toolWithProgress(RequestContext $context): ?string + { + $client = $context->getClientGateway(); + + $client->progress(0, 100, 'Completed step 0 of 100'); + $client->progress(50, 100, 'Completed step 50 of 100'); + $client->progress(100, 100, 'Completed step 100 of 100'); + + $meta = $context->getSession()->get(Protocol::SESSION_ACTIVE_REQUEST_META, []); + + return $meta['progressToken'] ?? null; + } + + /** + * @param string $prompt The prompt to send to the LLM + */ + public function toolWithSampling(RequestContext $context, string $prompt): string + { + $result = $context->getClientGateway()->sample($prompt, 100); + + return \sprintf( + 'LLM response: %s', + $result->content instanceof TextContent ? trim((string) $result->content->text) : '' + ); + } + + /** + * @param string $message The message to display to the user + */ + public function toolWithElicitation(RequestContext $context, string $message): string + { + $schema = new ElicitationSchema( + properties: [ + 'username' => new StringSchemaDefinition('Username'), + 'email' => new StringSchemaDefinition('Email'), + ], + ); + + $context->getClientGateway()->elicit($message, $schema); + + return 'ok'; + } + + public function toolWithElicitationDefaults(RequestContext $context): string + { + $schema = new ElicitationSchema( + properties: [ + 'name' => new StringSchemaDefinition('Name', default: 'John Doe'), + 'age' => new NumberSchemaDefinition('Age', integerOnly: true, default: 30), + 'score' => new NumberSchemaDefinition('Score', default: 95.5), + 'status' => new EnumSchemaDefinition('Status', enum: ['active', 'inactive', 'pending'], default: 'active'), + 'verified' => new BooleanSchemaDefinition('Verified', default: true), + ], + ); + + $context->getClientGateway()->elicit('Provide profile information', $schema); + + return 'ok'; + } + + public function toolWithElicitationEnums(RequestContext $context): string + { + $schema = new ElicitationSchema( + properties: [ + 'untitledSingle' => new EnumSchemaDefinition('Untitled Single', enum: ['option1', 'option2', 'option3']), + 'titledSingle' => new TitledEnumSchemaDefinition('Titled Single', oneOf: [ + ['const' => 'value1', 'title' => 'Label 1'], + ['const' => 'value2', 'title' => 'Label 2'], + ['const' => 'value3', 'title' => 'Label 3'], + ]), + 'legacyEnum' => new EnumSchemaDefinition('Legacy Enum', enum: ['opt1', 'opt2', 'opt3'], enumNames: ['Option 1', 'Option 2', 'Option 3']), + 'untitledMulti' => new MultiSelectEnumSchemaDefinition('Untitled Multi', enum: ['option1', 'option2', 'option3']), + 'titledMulti' => new TitledMultiSelectEnumSchemaDefinition('Titled Multi', anyOf: [ + ['const' => 'value1', 'title' => 'Label 1'], + ['const' => 'value2', 'title' => 'Label 2'], + ['const' => 'value3', 'title' => 'Label 3'], + ]), + ], + ); + + $context->getClientGateway()->elicit('Select options', $schema); + + return 'ok'; + } + + public function resourceTemplate(string $id): TextResourceContents + { + return new TextResourceContents( + uri: \sprintf('test://template/%s/data', $id), + mimeType: 'application/json', + text: json_encode([ + 'id' => $id, + 'templateTest' => true, + 'data' => \sprintf('Data for ID: %s', $id), + ], \JSON_THROW_ON_ERROR), + ); + } + + /** + * @param string $arg1 First test argument + * @param string $arg2 Second test argument + * + * @return PromptMessage[] + */ + public function promptWithArguments(string $arg1, string $arg2): array + { + return [ + new PromptMessage(Role::User, new TextContent(\sprintf('Prompt with arguments: arg1="%s", arg2="%s"', $arg1, $arg2))), + ]; + } + + /** + * @param string $resourceUri URI of the resource to embed + * + * @return PromptMessage[] + */ + public function promptWithEmbeddedResource(string $resourceUri): array + { + return [ + new PromptMessage(Role::User, EmbeddedResource::fromText($resourceUri, 'Embedded resource content for testing.')), + new PromptMessage(Role::User, new TextContent('Please process the embedded resource above.')), + ]; + } + + /** + * @return PromptMessage[] + */ + public function promptWithImage(): array + { + return [ + new PromptMessage(Role::User, new ImageContent(self::TEST_IMAGE_BASE64, 'image/png')), + new PromptMessage(Role::User, new TextContent('Please analyze the image above.')), + ]; + } +} diff --git a/tests/Conformance/Sdk/LICENSE b/tests/Conformance/Sdk/LICENSE new file mode 100644 index 0000000..4a93985 --- /dev/null +++ b/tests/Conformance/Sdk/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/tests/Conformance/Sdk/MrtrElements.php b/tests/Conformance/Sdk/MrtrElements.php new file mode 100644 index 0000000..7fd94ca --- /dev/null +++ b/tests/Conformance/Sdk/MrtrElements.php @@ -0,0 +1,216 @@ +getInputContext(); + + if (null === $input || !$input->has(self::ELICIT_KEY)) { + return new InputRequiredResult([ + self::ELICIT_KEY => new ElicitRequest( + 'What is your name?', + new ElicitationSchema(['name' => new StringSchemaDefinition('Name')], ['name']), + ), + ], requestState: $context->mintRequestState(['stage' => 'awaiting-input'])); + } + + return new CallToolResult([new TextContent(\sprintf('Hello, %s!', self::nameFrom($input->elicitResult(self::ELICIT_KEY))))]); + } + + public static function sampling(RequestContext $context): CallToolResult|InputRequiredResult + { + $input = $context->getInputContext(); + + if (null === $input || !$input->has('capital')) { + return new InputRequiredResult([ + 'capital' => new CreateSamplingMessageRequest( + [new SamplingMessage(Role::User, new TextContent('What is the capital of France?'))], + maxTokens: 100, + ), + ], requestState: $context->mintRequestState(['stage' => 'awaiting-input'])); + } + + return new CallToolResult([new TextContent('Sampling complete.')]); + } + + public static function listRoots(RequestContext $context): CallToolResult|InputRequiredResult + { + $input = $context->getInputContext(); + + if (null === $input || !$input->has('roots')) { + return new InputRequiredResult(['roots' => new ListRootsRequest()], requestState: $context->mintRequestState(['stage' => 'awaiting-input'])); + } + + return new CallToolResult([new TextContent('Roots received.')]); + } + + /** Asks for everything in one result, so the client retries once. */ + public static function multipleInputs(RequestContext $context): CallToolResult|InputRequiredResult + { + $input = $context->getInputContext(); + + if (null === $input || !$input->has('user_name')) { + return new InputRequiredResult([ + 'user_name' => new ElicitRequest( + 'What is your name?', + new ElicitationSchema(['name' => new StringSchemaDefinition('Name')], ['name']), + ), + 'greeting' => new CreateSamplingMessageRequest( + [new SamplingMessage(Role::User, new TextContent('Generate a greeting'))], + maxTokens: 50, + ), + 'client_roots' => new ListRootsRequest(), + ], requestState: $context->mintRequestState(['stage' => 'awaiting-input'])); + } + + return new CallToolResult([new TextContent('All inputs received.')]); + } + + /** + * Reads the round out of the state, not the answers: a client retrying + * round two sends only round two's answer, so counting answers would read + * that as a fresh start and loop forever. + */ + public static function multiRound(RequestContext $context): CallToolResult|InputRequiredResult + { + $round = $context->getInputContext()?->requestState()['round'] ?? 0; + + if ($round < 1) { + return new InputRequiredResult([ + 'step_one' => new ElicitRequest( + 'Step one: what is your name?', + new ElicitationSchema(['name' => new StringSchemaDefinition('Name')], ['name']), + ), + ], requestState: $context->mintRequestState(['round' => 1])); + } + + if ($round < 2) { + return new InputRequiredResult([ + 'step_two' => new ElicitRequest( + 'Step two: what is your favourite colour?', + new ElicitationSchema(['color' => new StringSchemaDefinition('Colour')], ['color']), + ), + ], requestState: $context->mintRequestState(['round' => 2])); + } + + return new CallToolResult([new TextContent('All steps complete.')]); + } + + /** Reaches the second round only when the echoed state verified. */ + public static function tamperedState(RequestContext $context): CallToolResult|InputRequiredResult + { + $input = $context->getInputContext(); + + if (null === $input || !$input->has('confirm')) { + return new InputRequiredResult([ + 'confirm' => new ElicitRequest( + 'Confirm?', + new ElicitationSchema(['ok' => new StringSchemaDefinition('Ok')], ['ok']), + ), + ], requestState: $context->mintRequestState(['stage' => 'awaiting-confirmation'])); + } + + return new CallToolResult([new TextContent('State verified.')]); + } + + /** + * Assembles the ask from the declared capabilities: a server MUST NOT + * request input the client never said it could supply. + */ + public static function capabilities(RequestContext $context): CallToolResult|InputRequiredResult + { + $input = $context->getInputContext(); + + if (null !== $input && [] !== $input->all()) { + return new CallToolResult([new TextContent('Input received.')]); + } + + $capabilities = $context->getClientCapabilities(); + $requests = []; + + if (true === $capabilities?->elicitation) { + $requests['user_name'] = new ElicitRequest( + 'What is your name?', + new ElicitationSchema(['name' => new StringSchemaDefinition('Name')], ['name']), + ); + } + + if (true === $capabilities?->sampling) { + $requests['greeting'] = new CreateSamplingMessageRequest( + [new SamplingMessage(Role::User, new TextContent('Generate a greeting'))], + maxTokens: 50, + ); + } + + // Nothing the client can service; asking would never come back. + if ([] === $requests) { + return new CallToolResult([new TextContent('No supported input capabilities.')]); + } + + return new InputRequiredResult($requests, requestState: $context->mintRequestState(['stage' => 'awaiting-input'])); + } + + /** + * @return array>|InputRequiredResult + */ + public static function prompt(RequestContext $context): array|InputRequiredResult + { + $input = $context->getInputContext(); + + if (null === $input || !$input->has(self::ELICIT_KEY)) { + return new InputRequiredResult([ + self::ELICIT_KEY => new ElicitRequest( + 'What is your name?', + new ElicitationSchema(['name' => new StringSchemaDefinition('Name')], ['name']), + ), + ], requestState: $context->mintRequestState(['stage' => 'awaiting-input'])); + } + + return [['role' => 'user', 'content' => \sprintf('Hello, %s!', self::nameFrom($input->elicitResult(self::ELICIT_KEY)))]]; + } + + /** A declined or cancelled answer has no content, so the greeting falls back. */ + private static function nameFrom(?ElicitResult $result): string + { + $name = $result?->content['name'] ?? null; + + return \is_string($name) ? $name : 'friend'; + } +} diff --git a/tests/Conformance/baseline-2025-11-25.yml b/tests/Conformance/baseline-2025-11-25.yml new file mode 100644 index 0000000..e7aa6dd --- /dev/null +++ b/tests/Conformance/baseline-2025-11-25.yml @@ -0,0 +1,3 @@ +# Server scenarios expected to fail at this revision, each with the reason. +# Empty: every scenario must pass. +server: [] diff --git a/tests/Conformance/baseline-2026-07-28.yml b/tests/Conformance/baseline-2026-07-28.yml new file mode 100644 index 0000000..e7aa6dd --- /dev/null +++ b/tests/Conformance/baseline-2026-07-28.yml @@ -0,0 +1,3 @@ +# Server scenarios expected to fail at this revision, each with the reason. +# Empty: every scenario must pass. +server: [] diff --git a/tests/Conformance/docker-compose.yml b/tests/Conformance/docker-compose.yml new file mode 100644 index 0000000..81da7a5 --- /dev/null +++ b/tests/Conformance/docker-compose.yml @@ -0,0 +1,22 @@ +# nginx in front of php-fpm, like a production deployment, so the suite also +# covers SSE responses going through nginx. +services: + nginx: + image: mirror.gcr.io/library/nginx:1.26-alpine + ports: + - "${CONFORMANCE_PORT:-8000}:80" + volumes: + - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro + - ../..:/app:ro + depends_on: + - php-fpm + + php-fpm: + build: + context: . + args: + PHP_VERSION: "${CONFORMANCE_PHP:-8.3}" + volumes: + - ../..:/app:ro + - ./tmp:/app/tests/Conformance/tmp + working_dir: /app diff --git a/tests/Conformance/nginx.conf b/tests/Conformance/nginx.conf new file mode 100644 index 0000000..387c5a5 --- /dev/null +++ b/tests/Conformance/nginx.conf @@ -0,0 +1,15 @@ +server { + listen 80; + server_name localhost; + root /app/tests/Conformance/webroot; + + location / { + try_files $uri /index.php$is_args$args; + } + + location ~ \.php$ { + fastcgi_pass php-fpm:9000; + fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; + include fastcgi_params; + } +} diff --git a/tests/Conformance/run.sh b/tests/Conformance/run.sh new file mode 100755 index 0000000..68d08ba --- /dev/null +++ b/tests/Conformance/run.sh @@ -0,0 +1,72 @@ +#!/usr/bin/env bash +# +# Runs the official MCP conformance suite against the plugin's /mcp endpoint, +# served by nginx and php-fpm in Docker. Needs Docker, Node 22 and the +# Composer dependencies installed. +# +# tests/Conformance/run.sh both protocol revisions +# tests/Conformance/run.sh 2026-07-28 one revision + +set -uo pipefail + +cd "$(dirname "$0")" + +# The newest published alpha of the official suite: a new release that adds failing +# scenarios or checks turns this run red on purpose. +PACKAGE="${CONFORMANCE_PACKAGE:-@modelcontextprotocol/conformance@alpha}" +export CONFORMANCE_PORT="${CONFORMANCE_PORT:-8000}" +# The container runs the vendor/ installed by this PHP, so it uses the same version. +export CONFORMANCE_PHP="${CONFORMANCE_PHP:-$(php -r 'echo PHP_MAJOR_VERSION . "." . PHP_MINOR_VERSION;')}" +URL="http://localhost:${CONFORMANCE_PORT}/mcp" +if [ $# -gt 0 ]; then + SPECS=("$@") +else + SPECS=(2025-11-25 2026-07-28) +fi + +if ! rm -rf results tmp 2>/dev/null; then + # On Linux php-fpm created some of these files as its own user; remove them from inside. + docker compose run --rm --no-deps --entrypoint sh php-fpm -c 'rm -rf /app/tests/Conformance/tmp/*' || exit 1 + rm -rf results tmp || exit 1 +fi +mkdir -p tmp/cache tmp/logs +chmod -R 777 tmp + +docker compose up -d --build --quiet-pull || exit 1 +trap 'docker compose down >/dev/null 2>&1' EXIT + +# Ready once php-fpm answers: no connection (000) or nginx's 502 mean not yet. +ready=0 +for _ in $(seq 1 60); do + code=$(curl -s -o /dev/null -w '%{http_code}' "$URL") + if [ "$code" != "000" ] && [ "$code" != "502" ]; then + ready=1 + break + fi + sleep 1 +done +if [ $ready -ne 1 ]; then + echo "The endpoint at ${URL} did not come up." + docker compose logs --tail 100 + exit 1 +fi + +status=0 +for spec in "${SPECS[@]}"; do + echo "== Conformance: server, ${spec} ==" + npx --yes "$PACKAGE" server \ + --url "$URL" \ + --suite all \ + --spec-version "$spec" \ + --expected-failures "baseline-${spec}.yml" \ + --output-dir "results/${spec}" || status=1 +done + +if [ $status -ne 0 ]; then + echo "== Plugin log ==" + cat tmp/logs/*.log 2>/dev/null || echo "(empty)" + echo "== Containers ==" + docker compose logs --tail 100 +fi + +exit $status diff --git a/tests/Conformance/webroot/index.php b/tests/Conformance/webroot/index.php new file mode 100644 index 0000000..96dbbb7 --- /dev/null +++ b/tests/Conformance/webroot/index.php @@ -0,0 +1,47 @@ + FileEngine::class, 'path' => CACHE . 'sessions' . DS]); +Cache::setConfig('mcp_conformance_bus', ['className' => FileEngine::class, 'path' => CACHE . 'bus' . DS]); +Log::setConfig('mcp', ['className' => FileLog::class, 'path' => LOGS, 'file' => 'mcp', 'scopes' => ['mcp']]); + +Configure::write('Mcp', [ + 'server' => [ + 'name' => 'mcp-conformance-test-server', + 'version' => '1.0.0', + 'configure' => [ConformanceFixture::class, 'configure'], + ], + 'discovery' => ['scanDirs' => [], 'cache' => null], + 'session' => ['cache' => 'mcp_conformance'], + 'identity' => ['required' => false], + 'http' => ['allowedHosts' => ['localhost', '127.0.0.1']], +]); + +$server = new Server(new Application(CONFIG)); +$server->emit($server->run()); diff --git a/tests/Support/McpHttpTrait.php b/tests/Support/McpHttpTrait.php new file mode 100644 index 0000000..a308b1a --- /dev/null +++ b/tests/Support/McpHttpTrait.php @@ -0,0 +1,123 @@ + $_request + * @property \Psr\Http\Message\ResponseInterface|null $_response + */ +trait McpHttpTrait +{ + private const MCP_REVISION = '2026-07-28'; + + /** + * Posts $message to /mcp. No Authorization header unless $headers has one. + * + * @param array $message The JSON-RPC message. + * @param array $headers Extra or replacing headers. + * @return void + */ + protected function postMcp(array $message, array $headers = []): void + { + $this->_request['headers'] = $headers + [ + 'Host' => 'localhost', + 'Accept' => 'application/json, text/event-stream', + 'Content-Type' => 'application/json', + ]; + $this->post('/mcp', (string)json_encode($message)); + } + + /** + * @param int $id The JSON-RPC id. + * @param string $method The method. + * @param array $params Its params. + * @return array + */ + protected function mcpMessage(int $id, string $method, array $params = []): array + { + $params['_meta'] = [ + 'io.modelcontextprotocol/protocolVersion' => self::MCP_REVISION, + 'io.modelcontextprotocol/clientCapabilities' => new stdClass(), + ]; + + return ['jsonrpc' => '2.0', 'id' => $id, 'method' => $method, 'params' => $params]; + } + + /** + * @param string $method The JSON-RPC method. + * @param string|null $name The tool name, for tools/call. + * @param string|null $token A bearer token. + * @return array + */ + protected function mcpHeaders(string $method, ?string $name = null, ?string $token = null): array + { + $headers = ['MCP-Protocol-Version' => self::MCP_REVISION, 'Mcp-Method' => $method]; + if ($name !== null) { + $headers['Mcp-Name'] = $name; + } + if ($token !== null) { + $headers['Authorization'] = 'Bearer ' . $token; + } + + return $headers; + } + + /** + * @param string $name The tool. + * @param array $arguments Its arguments. + * @param string|null $token A bearer token. + * @return void + */ + protected function callTool(string $name, array $arguments = [], ?string $token = null): void + { + $this->postMcp( + $this->mcpMessage(1, 'tools/call', [ + 'name' => $name, + 'arguments' => $arguments === [] ? new stdClass() : $arguments, + ]), + $this->mcpHeaders('tools/call', $name, $token), + ); + } + + /** + * @param string|null $token A bearer token. + * @return void + */ + protected function listTools(?string $token = null): void + { + $this->postMcp($this->mcpMessage(1, 'tools/list'), $this->mcpHeaders('tools/list', null, $token)); + } + + /** + * @return array + */ + protected function responseJson(): array + { + $decoded = json_decode((string)$this->_response?->getBody(), true); + + return is_array($decoded) ? $decoded : []; + } + + /** + * The quoted parameters of the response's WWW-Authenticate challenge. + * + * @return array + */ + protected function challenge(): array + { + $header = (string)$this->_response?->getHeaderLine('WWW-Authenticate'); + preg_match_all('/(\w+)="((?:[^"\\\\]|\\\\.)*)"/', $header, $matches, PREG_SET_ORDER); + $params = []; + foreach ($matches as $match) { + $params[$match[1]] = stripslashes($match[2]); + } + + return $params; + } +} diff --git a/tests/TestCase/Audit/AuditRecordTest.php b/tests/TestCase/Audit/AuditRecordTest.php new file mode 100644 index 0000000..9a40fd9 --- /dev/null +++ b/tests/TestCase/Audit/AuditRecordTest.php @@ -0,0 +1,32 @@ + 'hi'], + null, + 12, + ); + + $this->assertSame( + ['method', 'name', 'outcome', 'identity', 'client', 'session', 'request', 'arguments', 'error', 'durationMs'], + array_keys($record->toArray()), + ); + $this->assertSame('echo', $record->toArray()['name']); + } +} diff --git a/tests/TestCase/Audit/AuditSettingsTest.php b/tests/TestCase/Audit/AuditSettingsTest.php new file mode 100644 index 0000000..c38ccc1 --- /dev/null +++ b/tests/TestCase/Audit/AuditSettingsTest.php @@ -0,0 +1,70 @@ +assertFalse($settings->enabled); + $this->assertSame(['tools/call'], $settings->methods); + $this->assertTrue($settings->log); + $this->assertTrue($settings->arguments); + $this->assertSame(['password', 'token', 'secret'], $settings->redact); + $this->assertSame(200, $settings->maxLength); + } + + public function testRedactIsLowerCasedAndReplacesTheDefault(): void + { + Configure::write('Mcp.audit.redact', ['ApiKey']); + + $this->assertSame(['apikey'], AuditSettings::fromConfig()->redact); + } + + public function testAudits(): void + { + Configure::delete('Mcp'); + $settings = AuditSettings::fromConfig(); + + $this->assertTrue($settings->audits('tools/call')); + $this->assertFalse($settings->audits('tools/list')); + } + + /** + * @return array, 1: string}> + */ + public static function invalidSettings(): array + { + return [ + 'unknown key' => [['foo' => true], 'Mcp.audit.foo'], + 'enabled not a bool' => [['enabled' => 'yes'], 'Mcp.audit.enabled'], + 'method not audited' => [['methods' => ['tools/list']], 'Mcp.audit.methods'], + 'methods not a list' => [['methods' => 'tools/call'], 'Mcp.audit.methods'], + 'maxLength zero' => [['maxLength' => 0], 'Mcp.audit.maxLength'], + 'redact not strings' => [['redact' => [1]], 'Mcp.audit.redact'], + ]; + } + + /** + * @param array $audit + * @dataProvider invalidSettings + */ + public function testInvalidSettingsNameTheKey(array $audit, string $key): void + { + Configure::write('Mcp.audit', $audit); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('"' . $key . '"'); + AuditSettings::fromConfig(); + } +} diff --git a/tests/TestCase/Audit/AuditWriterTest.php b/tests/TestCase/Audit/AuditWriterTest.php new file mode 100644 index 0000000..fdd7034 --- /dev/null +++ b/tests/TestCase/Audit/AuditWriterTest.php @@ -0,0 +1,296 @@ +> + */ + private array $events = []; + + /** + * @var callable + */ + private $listener; + + protected function setUp(): void + { + parent::setUp(); + Configure::delete('Mcp'); + Log::setConfig('audit_test', ['className' => ArrayLog::class, 'scopes' => ['mcp_audit']]); + Log::setConfig('mcp_test', ['className' => ArrayLog::class, 'scopes' => ['mcp'], 'levels' => ['error']]); + $this->events = []; + $this->listener = function (EventInterface $event): void { + $this->events[] = $event; + }; + EventManager::instance()->on('Mcp.audit', $this->listener); + } + + protected function tearDown(): void + { + EventManager::instance()->off('Mcp.audit', $this->listener); + Log::drop('audit_test'); + Log::drop('mcp_test'); + if (in_array('failing', Log::configured(), true)) { + Log::drop('failing'); + } + parent::tearDown(); + } + + private function writer(): AuditWriter + { + return new AuditWriter(AuditSettings::fromConfig()); + } + + /** + * @param array $overrides + */ + private function record(array $overrides = []): AuditRecord + { + $fields = $overrides + [ + 'method' => 'tools/call', + 'name' => 'find_order', + 'outcome' => AuditRecord::OK, + 'identity' => 12, + 'client' => '62938fb0', + 'session' => 's-1', + 'request' => 2, + 'arguments' => ['number' => 'A-1042'], + 'error' => null, + 'durationMs' => 34, + ]; + + return new AuditRecord(...$fields); + } + + /** + * @return list + */ + private function lines(string $config = 'audit_test'): array + { + $engine = Log::engine($config); + $this->assertInstanceOf(ArrayLog::class, $engine); + + return array_values(array_map('strval', $engine->read())); + } + + public function testWritesOneLineWithTheRecord(): void + { + $this->writer()->write($this->record()); + + $this->assertSame( + ['info: MCP tools/call find_order ok 34ms identity=12 client=62938fb0 session=s-1 request=2 args={"number":"A-1042"}'], + $this->lines(), + ); + } + + public function testClientTextCannotForgeLinesOrPlaceholders(): void + { + $writer = $this->writer(); + $writer->write($this->record([ + 'name' => "echo ok 1ms\ninfo: MCP tools/call delete_all ok 3ms identity=1 {scope}", + 'request' => "r\n1 {scope}", + 'outcome' => AuditRecord::INVALID, + 'arguments' => $writer->arguments(['text' => '{scope}', 'q' => "a\nb"]), + 'error' => "Tool not found: \"x\\\"\ninfo: forged", + ])); + + $lines = $this->lines(); + $this->assertCount(1, $lines); + $this->assertStringNotContainsString("\n", $lines[0]); + $this->assertStringNotContainsString('mcp_audit', $lines[0]); + // The name is quoted and escaped, so the forged record stays inside it. + $this->assertStringStartsWith('notice: MCP tools/call "echo ok 1ms\\ninfo: MCP', $lines[0]); + preg_match('/ args=(\{.*\}) error=/', $lines[0], $match); + $this->assertSame(['text' => '{scope}', 'q' => "a\nb"], json_decode($match[1] ?? '', true)); + } + + public function testNullsAreDashes(): void + { + $this->writer()->write($this->record(['identity' => null, 'client' => null, 'session' => null, 'durationMs' => null])); + + $this->assertStringContainsString('ok -ms identity=- client=- session=- request=2', $this->lines()[0]); + } + + public function testErrorIsAppended(): void + { + $this->writer()->write($this->record(['outcome' => AuditRecord::TOOL_ERROR, 'error' => 'Course 9 does not exist.'])); + + $line = $this->lines()[0]; + $this->assertStringStartsWith('notice: ', $line); + $this->assertStringEndsWith(' error="Course 9 does not exist."', $line); + } + + /** + * @return array + */ + public static function levels(): array + { + return [ + 'ok' => [AuditRecord::OK, 'info'], + 'tool error' => [AuditRecord::TOOL_ERROR, 'notice'], + 'invalid' => [AuditRecord::INVALID, 'notice'], + 'denied' => [AuditRecord::DENIED, 'warning'], + 'error' => [AuditRecord::ERROR, 'warning'], + 'unauthorized' => [AuditRecord::UNAUTHORIZED, 'warning'], + 'insufficient scope' => [AuditRecord::INSUFFICIENT_SCOPE, 'warning'], + ]; + } + + /** + * @dataProvider levels + */ + public function testLevels(string $outcome, string $level): void + { + $this->writer()->write($this->record(['outcome' => $outcome])); + + $this->assertStringStartsWith($level . ': ', $this->lines()[0]); + } + + public function testDispatchesTheCakeEvent(): void + { + $record = $this->record(); + $this->writer()->write($record); + + $this->assertCount(1, $this->events); + $this->assertSame('Mcp.audit', $this->events[0]->getName()); + $this->assertSame($record->toArray(), $this->events[0]->getData()); + } + + public function testLogFalseKeepsOnlyTheEvent(): void + { + Configure::write('Mcp.audit.log', false); + $this->writer()->write($this->record()); + + $this->assertSame([], $this->lines()); + $this->assertCount(1, $this->events); + } + + public function testAFailingListenerDoesNotThrow(): void + { + $failing = function (): void { + throw new RuntimeException('listener exploded'); + }; + EventManager::instance()->on('Mcp.audit', $failing); + try { + $this->writer()->write($this->record()); + } finally { + EventManager::instance()->off('Mcp.audit', $failing); + } + + $this->assertCount(1, $this->lines()); + $this->assertStringContainsString('listener exploded', implode("\n", $this->lines('mcp_test'))); + } + + public function testAFailingLogEngineDoesNotThrow(): void + { + Log::setConfig('failing', new class extends AbstractLogger { + public function log(mixed $level, string|Stringable $message, array $context = []): void + { + throw new RuntimeException('disk full'); + } + }); + + $this->writer()->write($this->record()); + + $this->assertCount(1, $this->events); + } + + public function testRedactsAtAnyDepthIgnoringCase(): void + { + $arguments = $this->writer()->arguments(['user' => ['Password' => 'x', 'name' => 'Ann'], 'token' => 'y']); + + $this->assertSame(['user' => ['Password' => '[redacted]', 'name' => 'Ann'], 'token' => '[redacted]'], $arguments); + } + + public function testLongStringsAreCut(): void + { + $arguments = $this->writer()->arguments(['q' => str_repeat('a', 250)]); + + $this->assertSame(str_repeat('a', 200) . '...', $arguments['q']); + } + + public function testOversizedArgumentsAreReplaced(): void + { + $big = []; + for ($i = 0; $i < 30; $i++) { + $big['k' . $i] = str_repeat('b', 199); + } + + $this->assertSame(['truncated' => true], $this->writer()->arguments($big)); + } + + public function testArgumentsFalseGivesNone(): void + { + Configure::write('Mcp.audit.arguments', false); + $writer = $this->writer(); + + $this->assertSame([], $writer->arguments(['q' => 'x'])); + $writer->write($this->record(['arguments' => []])); + $this->assertStringNotContainsString('args=', $this->lines()[0]); + } + + /** + * @return array + */ + public static function notObjects(): array + { + return ['null' => [null], 'list' => [['a', 'b']], 'string' => ['text']]; + } + + /** + * @dataProvider notObjects + */ + public function testNonObjectArgumentsBecomeEmpty(mixed $arguments): void + { + $this->assertSame([], $this->writer()->arguments($arguments)); + } + + public function testInvalidUtf8IsSubstituted(): void + { + $writer = $this->writer(); + $writer->write($this->record(['arguments' => $writer->arguments(['q' => "\xB1\x31"])])); + + $this->assertStringContainsString('args={"q":', $this->lines()[0]); + } + + public function testDeepNestingIsCut(): void + { + $nested = 'bottom'; + for ($i = 0; $i < 12; $i++) { + $nested = ['n' => $nested]; + } + + $arguments = $this->writer()->arguments($nested); + + $value = $arguments; + for ($depth = 1; $depth < 9; $depth++) { + $this->assertIsArray($value); + $value = $value['n']; + } + $this->assertSame(['n' => '[...]'], $value); + } + + public function testMultibyteCutKeepsCharacters(): void + { + $arguments = $this->writer()->arguments(['q' => str_repeat('ñ', 250)]); + + $this->assertSame(str_repeat('ñ', 200) . '...', $arguments['q']); + $this->assertTrue(mb_check_encoding($arguments['q'], 'UTF-8')); + } +} diff --git a/tests/TestCase/Authorization/RbacToolAuthorizerTest.php b/tests/TestCase/Authorization/RbacToolAuthorizerTest.php new file mode 100644 index 0000000..43375a9 --- /dev/null +++ b/tests/TestCase/Authorization/RbacToolAuthorizerTest.php @@ -0,0 +1,86 @@ +> + */ + private function permissions(): array + { + return [ + [ + 'role' => 'editor', + 'plugin' => 'CakeDC/Mcp', + 'controller' => 'Tools', + 'action' => ['echo', 'whoami'], + ], + [ + 'role' => 'admin', + 'plugin' => 'CakeDC/Mcp', + 'controller' => 'Tools', + 'action' => '*', + ], + [ + 'role' => '*', + 'plugin' => 'CakeDC/Mcp', + 'controller' => 'Tools', + 'action' => 'own_profile', + 'allowed' => fn($user, $role, $request): bool => ($user['id'] ?? null) === 1, + ], + ]; + } + + private function authorizer(): RbacToolAuthorizer + { + return new RbacToolAuthorizer(['permissions' => $this->permissions(), 'log' => false]); + } + + public function testRolesAllowTheirTools(): void + { + $editor = ['id' => 1, 'role' => 'editor']; + + $this->assertTrue($this->authorizer()->canCall($editor, 'echo')); + $this->assertFalse($this->authorizer()->canCall($editor, 'admin_only')); + $this->assertTrue($this->authorizer()->canCall(['id' => 2, 'role' => 'admin'], 'admin_only')); + } + + public function testCallableRulesSeeTheIdentity(): void + { + $this->assertTrue($this->authorizer()->canCall(['id' => 1, 'role' => 'viewer'], 'own_profile')); + $this->assertFalse($this->authorizer()->canCall(['id' => 2, 'role' => 'viewer'], 'own_profile')); + } + + public function testWorksWithAuthenticationIdentities(): void + { + $identity = new Identity(new ArrayObject(['id' => 1, 'role' => 'editor'])); + + $this->assertTrue($this->authorizer()->canCall($identity, 'whoami')); + } + + public function testNoIdentityIsDenied(): void + { + $this->assertFalse($this->authorizer()->canCall(null, 'echo')); + } + + public function testAcceptsAPreparedRbacInstanceAndCustomRoleField(): void + { + $rbac = new Rbac([ + 'role_field' => 'group', + 'log' => false, + 'permissions' => [ + ['role' => 'staff', 'plugin' => 'CakeDC/Mcp', 'controller' => 'Tools', 'action' => 'echo'], + ], + ]); + + $this->assertTrue((new RbacToolAuthorizer($rbac))->canCall(['id' => 3, 'group' => 'staff'], 'echo')); + } +} diff --git a/tests/TestCase/Authorization/ToolCallGuardTest.php b/tests/TestCase/Authorization/ToolCallGuardTest.php new file mode 100644 index 0000000..679f8df --- /dev/null +++ b/tests/TestCase/Authorization/ToolCallGuardTest.php @@ -0,0 +1,50 @@ +guard = new ToolCallGuard(new ToolGate($onlyEcho, new CurrentIdentity())); + } + + public function testStepsAsideForAllowedCallsAndOtherMethods(): void + { + $this->assertFalse($this->guard->supports((new CallToolRequest('echo', []))->withId(1))); + $this->assertFalse($this->guard->supports((new ListToolsRequest())->withId(2))); + } + + public function testAnswersDeniedCallsLikeAnUnknownTool(): void + { + $request = (new CallToolRequest('admin_only', []))->withId(7); + + $this->assertTrue($this->guard->supports($request)); + $error = $this->guard->handle($request, $this->createStub(SessionInterface::class)); + + $this->assertInstanceOf(Error::class, $error); + $this->assertSame(Error::INVALID_PARAMS, $error->code); + $this->assertSame('Tool not found: "admin_only".', $error->message); + $this->assertSame(7, $error->id); + } +} diff --git a/tests/TestCase/Authorization/ToolGateTest.php b/tests/TestCase/Authorization/ToolGateTest.php new file mode 100644 index 0000000..4e6abe0 --- /dev/null +++ b/tests/TestCase/Authorization/ToolGateTest.php @@ -0,0 +1,40 @@ +set(['id' => 1, 'role' => 'editor']); + $authorizer = new class implements ToolAuthorizerInterface { + public function canCall(mixed $identity, string $tool): bool + { + return $identity['role'] === 'editor' && $tool === 'echo'; + } + }; + $gate = new ToolGate($authorizer, $identity); + + $this->assertTrue($gate->allows('echo')); + $this->assertFalse($gate->allows('admin_only')); + } + + public function testTrustedGateAllowsEverything(): void + { + $denyAll = new class implements ToolAuthorizerInterface { + public function canCall(mixed $identity, string $tool): bool + { + return false; + } + }; + + $this->assertTrue((new ToolGate($denyAll, new CurrentIdentity(), true))->allows('anything')); + } +} diff --git a/tests/TestCase/Command/McpCheckCommandTest.php b/tests/TestCase/Command/McpCheckCommandTest.php new file mode 100644 index 0000000..08d64bf --- /dev/null +++ b/tests/TestCase/Command/McpCheckCommandTest.php @@ -0,0 +1,280 @@ +useCommandRunner(); + } + + protected function tearDown(): void + { + Router::reload(); + foreach (['skeleton_debug', 'skeleton_error', 'mcp_test', 'audit_check', 'object_log', 'psr_log'] as $name) { + if (in_array($name, Log::configured(), true)) { + Log::drop($name); + } + } + parent::tearDown(); + } + + public function testHostMode(): void + { + $this->exec('mcp check'); + + $this->assertExitSuccess(); + $this->assertOutputContains('[PASS] Endpoint: http://localhost/mcp'); + $this->assertOutputContains('[PASS] Authentication: host mode'); + $this->assertOutputContains('[PASS] CSRF'); + } + + public function testAuditOff(): void + { + $this->exec('mcp check'); + + $this->assertOutputContains('[PASS] Audit: off'); + } + + public function testAuditOnWithItsLogScope(): void + { + Configure::write('Mcp.audit.enabled', true); + Log::setConfig('audit_check', ['className' => ArrayLog::class, 'scopes' => ['mcp_audit']]); + try { + $this->exec('mcp check'); + } finally { + Log::drop('audit_check'); + } + + $this->assertOutputContains('[PASS] Audit: tools/call to the mcp_audit log scope'); + } + + /** + * The debug and error engines of the current cakephp/app skeleton. + */ + private function skeletonLogs(): void + { + // The CakePHP 4 skeleton: `false` takes only messages without a scope. + Log::setConfig('skeleton_debug', ['className' => ArrayLog::class, 'scopes' => false, 'levels' => ['notice', 'info', 'debug']]); + Log::setConfig('skeleton_error', ['className' => ArrayLog::class, 'scopes' => false, 'levels' => ['warning', 'error', 'critical', 'alert', 'emergency']]); + } + + public function testLoggingWarnsWhenNoEngineTakesTheMcpScope(): void + { + $this->skeletonLogs(); + + $this->exec('mcp check'); + + $this->assertExitSuccess(); + $this->assertOutputContains('[WARN] Logging: no Log engine takes the errors of the mcp scope'); + $this->assertOutputContains("'scopes' => ['mcp']"); + $this->assertOutputContains('docs/configuration.md#logging'); + } + + public function testLoggingPassesWithAnEngineForTheMcpScope(): void + { + $this->skeletonLogs(); + Log::setConfig('mcp_test', ['className' => ArrayLog::class, 'scopes' => ['mcp']]); + + $this->exec('mcp check'); + + $this->assertOutputContains('[PASS] Logging: the mcp scope goes to mcp_test'); + } + + public function testAnEngineWithEmptyScopesTakesEverything(): void + { + Log::setConfig('mcp_test', ['className' => ArrayLog::class, 'scopes' => []]); + + $this->exec('mcp check'); + + $this->assertOutputContains('[PASS] Logging: the mcp scope goes to mcp_test'); + } + + public function testAnEngineWithoutTheErrorLevelDoesNotCount(): void + { + Log::setConfig('mcp_test', ['className' => ArrayLog::class, 'scopes' => ['mcp'], 'levels' => ['info']]); + + $this->exec('mcp check'); + + $this->assertOutputContains('[WARN] Logging'); + } + + public function testEnginesGivenAsObjectsCount(): void + { + Log::setConfig('object_log', new ArrayLog(['scopes' => ['mcp']])); + + $this->exec('mcp check'); + + $this->assertOutputContains('[PASS] Logging: the mcp scope goes to object_log'); + } + + public function testAPlainPsrLoggerTakesEverything(): void + { + Log::setConfig('psr_log', new NullLogger()); + + $this->exec('mcp check'); + + $this->assertOutputContains('[PASS] Logging: the mcp scope goes to psr_log'); + } + + public function testAuditLinesReachAnEngineOfTheMcpScope(): void + { + Configure::write('Mcp.audit.enabled', true); + Log::setConfig('mcp_test', ['className' => ArrayLog::class, 'scopes' => ['mcp']]); + + $this->exec('mcp check'); + + $this->assertOutputContains('[PASS] Audit: tools/call to the mcp_audit log scope'); + } + + public function testAuditOnWithoutAnEngineForItsScope(): void + { + Configure::write('Mcp.audit.enabled', true); + + $this->exec('mcp check'); + + $this->assertOutputContains('[WARN] Audit: on, but no Log engine takes its lines'); + $this->assertOutputContains("'scopes' => ['mcp_audit']"); + } + + public function testInvalidAuditSettingFails(): void + { + Configure::write('Mcp.audit.maxLength', 0); + + $this->exec('mcp check'); + + $this->assertExitError(); + $this->assertOutputContains('[FAIL] Audit: "Mcp.audit.maxLength"'); + } + + public function testListingTheToolsPrintsNoServerLogLines(): void + { + $this->exec('mcp check'); + + $this->assertOutputNotContains('Running server'); + $this->assertOutputNotContains('Handling request'); + $this->assertOutputNotContains('Attribute discovery finished'); + } + + public function testToolsAreListed(): void + { + $this->exec('mcp check'); + + $this->assertOutputRegExp('/\\[PASS\\] Tools: \\d+ tools: .*echo/'); + } + + public function testNoToolFoundWarns(): void + { + Configure::write('Mcp.discovery.scanDirs', ['src/NoTools']); + + $this->exec('mcp check'); + + $this->assertExitSuccess(); + $this->assertOutputContains('[WARN] Tools: no tool found in src/NoTools'); + $this->assertOutputContains('namespace'); + } + + public function testTheDefaultAuthorizerPasses(): void + { + $this->exec('mcp check'); + + $this->assertOutputContains('[PASS] Authorizer: AllowAllToolAuthorizer'); + } + + /** + * @param list> $permissions + */ + private function rbac(array $permissions): void + { + Configure::write('Mcp.authorization', [ + 'authorizer' => RbacToolAuthorizer::class, + 'rbac' => ['log' => false, 'permissions' => $permissions], + ]); + } + + public function testRbacWithoutRulesWarns(): void + { + $this->rbac([]); + + $this->exec('mcp check'); + + $this->assertOutputContains('[WARN] Authorizer: RbacToolAuthorizer has no rules, so no one can call a tool'); + } + + public function testRbacWithoutRulesForTheToolsWarns(): void + { + $this->rbac([ + ['role' => 'admin', 'plugin' => null, 'controller' => 'Articles', 'action' => '*'], + ['role' => 'admin', 'plugin' => 'CakeDC/Mcp', 'controller' => 'Tools', 'action' => '*', 'allowed' => false], + ]); + + $this->exec('mcp check'); + + $this->assertOutputContains("[WARN] Authorizer: none of the 2 rules of RbacToolAuthorizer allows plugin 'CakeDC/Mcp', controller 'Tools'"); + } + + /** + * @return array}> + */ + public static function toolRules(): array + { + return [ + 'exact' => [['role' => 'editor', 'plugin' => 'CakeDC/Mcp', 'controller' => 'Tools', 'action' => ['echo']]], + 'wildcards' => [['role' => 'admin', 'plugin' => '*', 'controller' => '*', 'action' => '*']], + 'no plugin key' => [['role' => 'admin', 'controller' => ['Tools', 'Articles'], 'action' => '*']], + ]; + } + + /** + * @param array $rule + * @dataProvider toolRules + */ + public function testRbacWithARuleForTheToolsPasses(array $rule): void + { + $this->rbac([$rule]); + + $this->exec('mcp check'); + + $this->assertOutputContains('[PASS] Authorizer: RbacToolAuthorizer, 1 of 1 rules for the tools'); + } + + /** + * The oauth and external modes of 2.x are not in the 1.x line: the plugin bootstrap refuses them, + * so `mcp check` (as every command) stops with the reason instead of reporting an endpoint that + * would run without the authentication they promise. + * + * @return array + */ + public static function unavailableModes(): array + { + return ['oauth' => ['oauth'], 'external' => ['external']]; + } + + /** + * @dataProvider unavailableModes + */ + public function testUnavailableAuthModeStopsTheCommand(string $mode): void + { + Configure::write('Mcp.auth.mode', $mode); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage(sprintf('"Mcp.auth.mode" "%s" is not available', $mode)); + $this->exec('mcp check'); + } +} diff --git a/tests/TestCase/Command/McpInspectorCommandTest.php b/tests/TestCase/Command/McpInspectorCommandTest.php new file mode 100644 index 0000000..d6e6536 --- /dev/null +++ b/tests/TestCase/Command/McpInspectorCommandTest.php @@ -0,0 +1,212 @@ +, config: array}> + */ + private array $launched = []; + + public function testIsRegisteredAsMcpInspector(): void + { + $commands = (new McpPlugin())->console(new CommandCollection()); + + $this->assertSame(McpInspectorCommand::class, $commands->get('mcp inspector')); + } + + public function testStdioStartsTheServerCommand(): void + { + $this->assertSame(0, $this->runCommand([])); + + $this->assertCount(1, $this->launched); + $command = $this->launched[0]['command']; + $this->assertSame(['npx', '--yes', '@modelcontextprotocol/inspector@2', '--config'], array_slice($command, 0, 4)); + $this->assertSame([ + 'type' => 'stdio', + 'command' => PHP_BINARY, + 'args' => [rtrim(ROOT, DS) . DS . 'bin' . DS . 'cake.php', 'mcp', 'server'], + 'cwd' => rtrim(ROOT, DS), + 'protocolEra' => 'auto', + ], $this->launched[0]['config']['mcpServers']['cakephp-mcp-server'] ?? null); + } + + public function testHttpUsesTheFullBaseUrlAndTheRoute(): void + { + Configure::write('App.fullBaseUrl', 'https://app.example.com/'); + + $this->assertSame(0, $this->runCommand(['--http', '--header', 'Authorization: Bearer secret-token'])); + + $this->assertSame([ + 'type' => 'http', + 'url' => 'https://app.example.com/mcp', + 'headers' => ['Authorization' => 'Bearer secret-token'], + 'protocolEra' => 'auto', + ], $this->launched[0]['config']['mcpServers']['cakephp-mcp-server'] ?? null); + } + + public function testUrlOptionImpliesHttp(): void + { + $this->assertSame(0, $this->runCommand(['--url', 'http://localhost:8765/mcp'])); + + $server = $this->launched[0]['config']['mcpServers']['cakephp-mcp-server'] ?? []; + $this->assertSame('http', $server['type'] ?? null); + $this->assertSame('http://localhost:8765/mcp', $server['url'] ?? null); + $this->assertArrayNotHasKey('headers', $server); + } + + public function testTheConfigFileIsRemovedAfterwards(): void + { + $this->runCommand([]); + + $this->assertFileDoesNotExist($this->launched[0]['command'][4]); + } + + public function testDryRunPrintsWithoutLaunchingAndHidesHeaderValues(): void + { + $code = $this->runCommand(['--url', 'https://app.example.com/mcp', '--header', 'Authorization: Bearer secret-token', '--dry-run']); + + $this->assertSame(0, $code); + $this->assertSame([], $this->launched); + $output = implode("\n", $this->out->messages()); + $this->assertStringContainsString('"url": "https://app.example.com/mcp"', $output); + $this->assertStringContainsString('"Authorization": "***"', $output); + $this->assertStringNotContainsString('secret-token', $output); + $this->assertStringContainsString('npx --yes @modelcontextprotocol/inspector@2 --config', $output); + } + + public function testEnvironmentVariablesArePassedToTheStdioServer(): void + { + putenv('MCP_INSPECTOR_TEST=from-the-shell'); + try { + $this->assertSame(0, $this->runCommand(['--env', 'MCP_INSPECTOR_TEST'])); + $this->assertSame(0, $this->runCommand(['--env', 'MCP_INSPECTOR_TEST', '--dry-run'])); + } finally { + putenv('MCP_INSPECTOR_TEST'); + } + + $server = $this->launched[0]['config']['mcpServers']['cakephp-mcp-server'] ?? []; + $this->assertSame(['MCP_INSPECTOR_TEST' => 'from-the-shell'], $server['env'] ?? null); + $output = implode("\n", $this->out->messages()); + $this->assertStringContainsString('"MCP_INSPECTOR_TEST": "***"', $output); + $this->assertStringNotContainsString('from-the-shell', $output); + } + + public function testMissingEnvironmentVariablesAreRejected(): void + { + $this->assertSame(1, $this->runCommand(['--env', 'MCP_INSPECTOR_NOT_SET'])); + + $this->assertSame([], $this->launched); + $this->assertStringContainsString('MCP_INSPECTOR_NOT_SET', implode("\n", $this->err->messages())); + } + + public function testEnvironmentVariablesNeedStdio(): void + { + $this->assertSame(1, $this->runCommand(['--http', '--env', 'PATH'])); + + $this->assertStringContainsString('stdio', implode("\n", $this->err->messages())); + } + + public function testLaunchRunsTheCommandAndRestoresSignalHandlers(): void + { + $before = function_exists('pcntl_signal_get_handler') ? pcntl_signal_get_handler(SIGINT) : null; + $command = new class extends McpInspectorCommand { + /** + * @param list $command + */ + public function launchNow(array $command): int + { + return $this->launch($command, new ConsoleIo(new StubConsoleOutput(), new StubConsoleOutput())); + } + }; + + $this->assertSame(3, $command->launchNow([PHP_BINARY, '-r', 'exit(3);'])); + if (function_exists('pcntl_signal_get_handler')) { + $this->assertSame($before, pcntl_signal_get_handler(SIGINT)); + } + } + + public function testHttpWithoutABaseUrlAsksForOne(): void + { + Configure::write('App.fullBaseUrl', false); + + $this->assertSame(1, $this->runCommand(['--http'])); + + $this->assertSame([], $this->launched); + $this->assertStringContainsString('--url', implode("\n", $this->err->messages())); + } + + public function testHttpWithTheRouteDisabledFails(): void + { + Configure::write('Mcp.route', false); + + $this->assertSame(1, $this->runCommand(['--http'])); + + $this->assertStringContainsString('Mcp.route', implode("\n", $this->err->messages())); + } + + public function testMalformedHeadersAreRejected(): void + { + $this->assertSame(1, $this->runCommand(['--url', 'https://app.example.com/mcp', '--header', 'no-colon'])); + + $this->assertSame([], $this->launched); + $this->assertStringContainsString('"Name: Value"', implode("\n", $this->err->messages())); + } + + public function testHeadersNeedHttp(): void + { + $this->assertSame(1, $this->runCommand(['--header', 'Authorization: Bearer x'])); + + $this->assertStringContainsString('--http', implode("\n", $this->err->messages())); + } + + public function testExitCodeOfTheInspectorIsReturned(): void + { + $this->assertSame(3, $this->runCommand([], 3)); + } + + /** + * @param list $argv Command arguments. + */ + private function runCommand(array $argv, int $exitCode = 0): ?int + { + $this->out = new StubConsoleOutput(); + $this->err = new StubConsoleOutput(); + $io = new ConsoleIo($this->out, $this->err, new StubConsoleInput([])); + + $launched = &$this->launched; + $command = new class ($launched, $exitCode) extends McpInspectorCommand { + /** + * @param list, config: array}> $launched + */ + public function __construct(private array &$launched, private readonly int $exitCode) + { + } + + protected function launch(array $command, ConsoleIo $io): int + { + $config = json_decode((string)file_get_contents($command[4]), true); + $this->launched[] = ['command' => $command, 'config' => is_array($config) ? $config : []]; + + return $this->exitCode; + } + }; + + return $command->run($argv, $io); + } +} diff --git a/tests/TestCase/Command/McpServerCommandTest.php b/tests/TestCase/Command/McpServerCommandTest.php new file mode 100644 index 0000000..8d785e5 --- /dev/null +++ b/tests/TestCase/Command/McpServerCommandTest.php @@ -0,0 +1,168 @@ + ArrayEngine::class]); + } + + protected function tearDown(): void + { + Cache::drop('mcp_sessions'); + Log::drop('stdout'); + Log::drop('stderr'); + parent::tearDown(); + } + + public function testIsRegisteredAsMcpServer(): void + { + $commands = (new McpPlugin())->console(new CommandCollection()); + + $this->assertTrue($commands->has('mcp server')); + $this->assertSame(McpServerCommand::class, $commands->get('mcp server')); + } + + public function testConstructorDoesNotCallTheParentConstructor(): void + { + // Cake 5.0.x Command has no constructor, so calling it fatals on the lowest supported version. + $source = (string)file_get_contents((string)(new ReflectionClass(McpServerCommand::class))->getFileName()); + + $this->assertStringNotContainsString('parent::__construct', $source); + } + + public function testTheContainerBuildsTheCommand(): void + { + $container = new Container(); + (new McpPlugin())->services($container); + + $this->assertInstanceOf(McpServerCommand::class, $container->get(McpServerCommand::class)); + } + + public function testServesToolsOverTheTransport(): void + { + $command = $this->command(); + + $this->assertSame(McpServerCommand::CODE_SUCCESS, $this->runCommand($command)); + $this->assertContains('echo', array_column($command->transport?->responseFor(2)['result']['tools'] ?? [], 'name')); + } + + public function testIdentityComesFromTheStdioResolver(): void + { + Configure::write('Mcp.stdio.identity', fn(): array => ['id' => 42]); + $command = $this->command([(string)json_encode(['jsonrpc' => '2.0', 'id' => 3, 'method' => 'tools/call', 'params' => [ + 'name' => 'whoami', + 'arguments' => new stdClass(), + ]])]); + + $this->runCommand($command); + + $text = (string)($command->transport?->responseFor(3)['result']['content'][0]['text'] ?? ''); + $this->assertSame(42, json_decode($text, true)['identifier'] ?? null); + } + + public function testTrustedStdioSkipsRbacAndUntrustedDoesNot(): void + { + Configure::write('Mcp.authorization', [ + 'authorizer' => RbacToolAuthorizer::class, + 'rbac' => ['log' => false, 'permissions' => []], + ]); + + $trusted = $this->command(); + $this->runCommand($trusted); + $this->assertContains('admin_only', array_column($trusted->transport?->responseFor(2)['result']['tools'] ?? [], 'name')); + + Configure::write('Mcp.stdio.trusted', false); + $untrusted = $this->command(); + $this->runCommand($untrusted); + $this->assertSame([], $untrusted->transport?->responseFor(2)['result']['tools'] ?? null); + } + + public function testAuditRecordsStdioCallsWithTheStdioIdentity(): void + { + Configure::write('Mcp.audit.enabled', true); + Configure::write('Mcp.stdio.identity', fn(): array => ['id' => 42]); + $records = []; + $listener = function (EventInterface $event) use (&$records): void { + $records[] = (array)$event->getData(); + }; + EventManager::instance()->on('Mcp.audit', $listener); + $out = new StubConsoleOutput(); + $command = $this->command([(string)json_encode(['jsonrpc' => '2.0', 'id' => 3, 'method' => 'tools/call', 'params' => [ + 'name' => 'echo', + 'arguments' => ['text' => 'hi'], + ]])]); + + try { + $command->run([], new ConsoleIo($out, new StubConsoleOutput(), new StubConsoleInput([]))); + } finally { + EventManager::instance()->off('Mcp.audit', $listener); + } + + $this->assertCount(1, $records); + $this->assertSame('ok', $records[0]['outcome']); + $this->assertSame(42, $records[0]['identity']); + $this->assertSame([], $out->messages()); + } + + public function testNothingButProtocolReachesStdout(): void + { + $out = new StubConsoleOutput(); + $command = $this->command(); + + $command->run([], new ConsoleIo($out, new StubConsoleOutput(), new StubConsoleInput([]))); + + $this->assertSame([], $out->messages()); + } + + /** + * @param list $extra More JSON-RPC lines after initialize/initialized/tools list (id 2). + */ + private function command(array $extra = []): RecordingMcpServerCommand + { + $container = new Container(); + $identity = new CurrentIdentity(); + $container->addShared(CurrentIdentity::class, $identity); + + return new RecordingMcpServerCommand(new ServerFactory($container, $identity), $identity, array_merge([ + (string)json_encode(['jsonrpc' => '2.0', 'id' => 1, 'method' => 'initialize', 'params' => [ + 'protocolVersion' => '2025-06-18', + 'capabilities' => new stdClass(), + 'clientInfo' => ['name' => 'test', 'version' => '1.0'], + ]]), + (string)json_encode(['jsonrpc' => '2.0', 'method' => 'notifications/initialized']), + (string)json_encode(['jsonrpc' => '2.0', 'id' => 2, 'method' => 'tools/list']), + ], $extra)); + } + + private function runCommand(McpServerCommand $command): ?int + { + return $command->run([], new ConsoleIo(new StubConsoleOutput(), new StubConsoleOutput(), new StubConsoleInput([]))); + } +} diff --git a/tests/TestCase/Container/ContainerBridgeTest.php b/tests/TestCase/Container/ContainerBridgeTest.php new file mode 100644 index 0000000..f5513c4 --- /dev/null +++ b/tests/TestCase/Container/ContainerBridgeTest.php @@ -0,0 +1,76 @@ +addShared(Clock::class, $clock); + + $this->assertSame($clock, (new ContainerBridge($container))->get(Clock::class)); + } + + public function testAutowiresUnregisteredClassesWithDefaults(): void + { + $greeter = (new ContainerBridge(new Container()))->get(Greeter::class); + + $this->assertInstanceOf(Greeter::class, $greeter); + $this->assertInstanceOf(Clock::class, $greeter->clock); + $this->assertSame('Hello', $greeter->greeting); + } + + public function testAutowiredClassesReceiveRegisteredDependencies(): void + { + $container = new Container(); + $clock = new Clock(); + $container->addShared(Clock::class, $clock); + + $greeter = (new ContainerBridge($container))->get(Greeter::class); + + $this->assertSame($clock, $greeter->clock); + } + + public function testAutowiredInstancesAreReusedByTheSameBridge(): void + { + $bridge = new ContainerBridge(new Container()); + + $this->assertSame($bridge->get(Greeter::class), $bridge->get(Greeter::class)); + } + + public function testUnknownIdIsNotFound(): void + { + $bridge = new ContainerBridge(new Container()); + + $this->assertFalse($bridge->has('No\\Such\\Thing')); + $this->expectException(NotFoundException::class); + $bridge->get('No\\Such\\Thing'); + } + + public function testUnresolvableScalarFails(): void + { + $this->expectException(ContainerException::class); + $this->expectExceptionMessage('$required'); + (new ContainerBridge(new Container()))->get(NeedsScalar::class); + } + + public function testCircularDependencyFails(): void + { + $this->expectException(ContainerException::class); + $this->expectExceptionMessage('Circular'); + (new ContainerBridge(new Container()))->get(CycleA::class); + } +} diff --git a/tests/TestCase/Controller/McpAuditRefusalTest.php b/tests/TestCase/Controller/McpAuditRefusalTest.php new file mode 100644 index 0000000..4f9f565 --- /dev/null +++ b/tests/TestCase/Controller/McpAuditRefusalTest.php @@ -0,0 +1,154 @@ +> + */ + private array $records = []; + + /** + * @var callable + */ + private $listener; + + protected function setUp(): void + { + parent::setUp(); + Configure::write('Mcp.audit.enabled', true); + Log::setConfig('audit_test', ['className' => ArrayLog::class, 'scopes' => ['mcp_audit']]); + $this->records = []; + $this->listener = function (EventInterface $event): void { + $this->records[] = (array)$event->getData(); + }; + EventManager::instance()->on('Mcp.audit', $this->listener); + } + + protected function tearDown(): void + { + EventManager::instance()->off('Mcp.audit', $this->listener); + Log::drop('audit_test'); + parent::tearDown(); + } + + /** + * @return list + */ + private function lines(): array + { + $engine = Log::engine('audit_test'); + $this->assertInstanceOf(ArrayLog::class, $engine); + + return array_values(array_map('strval', $engine->read())); + } + + public function testUnauthorizedToolCallIsRecorded(): void + { + $this->callTool('echo', ['text' => 'hi']); + + $this->assertResponseCode(401); + $this->assertCount(1, $this->records); + $record = $this->records[0]; + $this->assertSame('tools/call', $record['method']); + $this->assertSame('echo', $record['name']); + $this->assertSame('unauthorized', $record['outcome']); + $this->assertNull($record['identity']); + $this->assertNull($record['client']); + $this->assertNull($record['session']); + $this->assertSame(['text' => 'hi'], $record['arguments']); + $this->assertStringStartsWith('warning: ', $this->lines()[0]); + } + + public function testUnauthorizedInitializeIsNot(): void + { + $this->postMcp($this->mcpMessage(1, 'initialize', [ + 'protocolVersion' => '2025-06-18', + 'capabilities' => [], + 'clientInfo' => ['name' => 'test', 'version' => '1.0'], + ])); + + $this->assertResponseCode(401); + $this->assertSame([], $this->records); + } + + public function testTheTokenNeverAppears(): void + { + $token = 'not-a-valid-token'; + $this->callTool('echo', ['text' => 'hi'], $token); + + $this->assertResponseCode(401); + $this->assertCount(1, $this->records); + $recorded = implode("\n", $this->lines()) . json_encode($this->records); + $this->assertStringNotContainsString($token, $recorded); + $this->assertStringNotContainsString('Bearer', $recorded); + } + + /** + * @return array + */ + public static function unreadableBodies(): array + { + return [ + 'empty' => [''], + 'not json' => ['{not json'], + 'a list' => ['[{"jsonrpc":"2.0","id":1,"method":"tools/call"}]'], + ]; + } + + private function postRaw(string $body): void + { + $this->configRequest(['headers' => [ + 'Host' => 'localhost', + 'Accept' => 'application/json, text/event-stream', + 'Content-Type' => 'application/json', + ]]); + $this->post('/mcp', $body); + } + + /** + * @dataProvider unreadableBodies + */ + public function testUnreadableBodyIsNotRecorded(string $body): void + { + $this->postRaw($body); + $onStatus = $this->_response?->getStatusCode(); + $this->assertSame([], $this->records); + + Configure::write('Mcp.audit.enabled', false); + $this->postRaw($body); + + $this->assertSame($onStatus, $this->_response?->getStatusCode()); + $this->assertContains($onStatus, [400, 401]); + } + + public function testOffAddsNothing(): void + { + $this->callTool('echo', ['text' => 'hi']); + $onBody = (string)$this->_response?->getBody(); + $onChallenge = $this->_response?->getHeaderLine('WWW-Authenticate'); + + Configure::write('Mcp.audit.enabled', false); + $this->records = []; + $this->callTool('echo', ['text' => 'hi']); + + $this->assertResponseCode(401); + $this->assertSame($onBody, (string)$this->_response?->getBody()); + $this->assertSame($onChallenge, $this->_response?->getHeaderLine('WWW-Authenticate')); + $this->assertSame([], $this->records); + } +} diff --git a/tests/TestCase/Controller/McpBodyLimitTest.php b/tests/TestCase/Controller/McpBodyLimitTest.php new file mode 100644 index 0000000..3c9574f --- /dev/null +++ b/tests/TestCase/Controller/McpBodyLimitTest.php @@ -0,0 +1,55 @@ +callTool('echo', ['text' => str_repeat('a', 4096)]); + + $this->assertResponseCode(413); + $this->assertSame('', $this->_response?->getHeaderLine('WWW-Authenticate')); + $error = $this->responseJson()['error'] ?? []; + $this->assertSame(-32600, $error['code'] ?? null); + $this->assertSame(2048, $error['data']['maxBodyBytes'] ?? null); + $this->assertStringContainsString('the limit is 2048 bytes', (string)($error['message'] ?? '')); + } + + public function testABodyWithinTheLimitStillReachesTheTool(): void + { + Configure::write('Mcp.http.maxBodyBytes', 4096); + $text = str_repeat('a', 1500); + + $this->callTool('echo', ['text' => $text], TestTokens::EDITOR); + + $this->assertResponseOk(); + $this->assertSame($text, $this->responseJson()['result']['content'][0]['text'] ?? null); + } + + public function testAnInvalidLimitFailsClosed(): void + { + Configure::write('Mcp.http.maxBodyBytes', 0); + + $this->callTool('echo', ['text' => 'x'], TestTokens::EDITOR); + + $this->assertResponseCode(500); + $this->assertSame(-32603, $this->responseJson()['error']['code'] ?? null); + } +} diff --git a/tests/TestCase/Controller/McpControllerTest.php b/tests/TestCase/Controller/McpControllerTest.php new file mode 100644 index 0000000..25468c8 --- /dev/null +++ b/tests/TestCase/Controller/McpControllerTest.php @@ -0,0 +1,304 @@ +mcp($this->initialize(1)); + + $this->assertResponseOk(); + $this->assertSame('CakePHP MCP Server', $this->json()['result']['serverInfo']['name'] ?? null); + $this->assertNotSame('', $this->_response->getHeaderLine('Mcp-Session-Id')); + } + + public function testHandshakeSessionPersistsAcrossRequests(): void + { + $this->mcp($this->initialize(1)); + $headers = [ + 'Mcp-Session-Id' => $this->_response->getHeaderLine('Mcp-Session-Id'), + 'MCP-Protocol-Version' => self::HANDSHAKE, + ]; + + $this->mcp(['jsonrpc' => '2.0', 'method' => 'notifications/initialized'], $headers); + $this->assertResponseCode(202); + + $this->mcp(['jsonrpc' => '2.0', 'id' => 2, 'method' => 'tools/list'], $headers); + $this->assertResponseOk(); + $this->assertContains('echo', $this->toolNames()); + + $this->mcp($this->handshakeCall(3, 'echo', ['text' => 'over the session']), $headers); + $this->assertSame('over the session', $this->json()['result']['content'][0]['text'] ?? null); + } + + public function testModernEraListsAndCallsWithoutASession(): void + { + $this->mcp($this->modern(1, 'tools/list'), $this->modernHeaders('tools/list')); + $this->assertResponseOk(); + $this->assertContains('echo', $this->toolNames()); + + $this->mcp( + $this->modern(2, 'tools/call', ['name' => 'echo', 'arguments' => ['text' => 'stateless']]), + $this->modernHeaders('tools/call', 'echo'), + ); + $this->assertResponseOk(); + $this->assertSame('stateless', $this->json()['result']['content'][0]['text'] ?? null); + } + + public function testJsonBodyIsReadAfterBodyParserMiddleware(): void + { + $this->mcp( + $this->modern(1, 'tools/call', ['name' => 'echo', 'arguments' => ['text' => 'parsed twice']]), + $this->modernHeaders('tools/call', 'echo'), + ); + + $this->assertSame('parsed twice', $this->json()['result']['content'][0]['text'] ?? null); + } + + public function testToolsSeeTheAuthenticatedIdentity(): void + { + $this->mcp( + $this->modern(1, 'tools/call', ['name' => 'whoami', 'arguments' => new stdClass()]), + $this->modernHeaders('tools/call', 'whoami'), + ); + + $whoami = json_decode((string)($this->json()['result']['content'][0]['text'] ?? ''), true); + $this->assertSame(['identifier' => 1, 'subject' => '1'], $whoami); + } + + public function testMissingTokenIsChallenged(): void + { + $this->mcp($this->initialize(1), ['Authorization' => '']); + + $this->assertResponseCode(401); + $this->assertHeader('WWW-Authenticate', 'Bearer'); + } + + public function testNullRequiredStillChallenges(): void + { + Configure::write('Mcp.identity.required', null); + + $this->mcp($this->initialize(1), ['Authorization' => '']); + + $this->assertResponseCode(401); + } + + public function testInvalidTokenIsChallenged(): void + { + $this->mcp($this->initialize(1), ['Authorization' => 'Bearer nope']); + + $this->assertResponseCode(401); + } + + public function testSessionDeleteWithoutTokenIsChallenged(): void + { + $this->configRequest(['headers' => ['Host' => 'localhost', 'Mcp-Session-Id' => 'anything']]); + $this->delete('/mcp'); + + $this->assertResponseCode(401); + } + + public function testCorsPreflightIsNotChallenged(): void + { + $this->configRequest(['headers' => ['Host' => 'localhost']]); + $this->options('/mcp'); + + $this->assertResponseCode(204); + } + + public function testForeignHostIsRejected(): void + { + $this->mcp($this->initialize(1), ['Host' => 'evil.example']); + + $this->assertResponseCode(403); + } + + public function testFullBaseUrlHostIsAccepted(): void + { + Configure::write('App.fullBaseUrl', 'https://mcp.example.com'); + + $this->mcp($this->initialize(1), ['Host' => 'mcp.example.com']); + + $this->assertResponseOk(); + } + + public function testRbacHidesAndRejectsToolsPerRoleInBothEras(): void + { + Configure::write('Mcp.authorization', [ + 'authorizer' => RbacToolAuthorizer::class, + 'rbac' => ['log' => false, 'permissions' => [ + ['role' => 'editor', 'plugin' => 'CakeDC/Mcp', 'controller' => 'Tools', 'action' => ['echo', 'whoami']], + ['role' => 'admin', 'plugin' => 'CakeDC/Mcp', 'controller' => 'Tools', 'action' => '*'], + ]], + ]); + + $this->mcp($this->modern(1, 'tools/list'), $this->modernHeaders('tools/list')); + $this->assertNotContains('admin_only', $this->toolNames()); + + $this->mcp( + $this->modern(2, 'tools/call', ['name' => 'admin_only', 'arguments' => new stdClass()]), + $this->modernHeaders('tools/call', 'admin_only'), + ); + $this->assertSame('Tool not found: "admin_only".', $this->json()['error']['message'] ?? null); + + $this->mcp($this->initialize(3)); + $session = [ + 'Mcp-Session-Id' => $this->_response->getHeaderLine('Mcp-Session-Id'), + 'MCP-Protocol-Version' => self::HANDSHAKE, + ]; + $this->mcp(['jsonrpc' => '2.0', 'method' => 'notifications/initialized'], $session); + $this->mcp($this->handshakeCall(4, 'admin_only'), $session); + $this->assertSame('Tool not found: "admin_only".', $this->json()['error']['message'] ?? null); + + $this->mcp($this->modern(5, 'tools/list'), $this->modernHeaders('tools/list') + [ + 'Authorization' => 'Bearer ' . TestTokens::ADMIN, + ]); + $this->assertContains('admin_only', $this->toolNames()); + } + + public function testToolFailureDoesNotLeakDetails(): void + { + $this->mcp( + $this->modern(1, 'tools/call', ['name' => 'explode', 'arguments' => new stdClass()]), + $this->modernHeaders('tools/call', 'explode'), + ); + + // The SDK answers an unhandled tool exception with HTTP 400 and this JSON-RPC error, which proves + // the call was not rejected earlier (that would be 401, 403 or 404, or "Tool not found"). + $this->assertResponseCode(400); + $this->assertSame( + ['code' => -32603, 'message' => 'Error while executing tool'], + $this->json()['error'] ?? null, + ); + $body = (string)$this->_response->getBody(); + $this->assertStringNotContainsString('secret details', $body); + $this->assertStringNotContainsString('#0 ', $body); + } + + public function testServerBuildFailureIsAJsonRpcInternalError(): void + { + Configure::write('Mcp.authorization.authorizer', 'NotAnAuthorizer'); + + $this->mcp($this->initialize(1)); + + $this->assertResponseCode(500); + $this->assertSame( + ['jsonrpc' => '2.0', 'id' => null, 'error' => ['code' => -32603, 'message' => 'Internal error']], + $this->json(), + ); + $this->assertStringNotContainsString('NotAnAuthorizer', (string)$this->_response->getBody()); + } + + public function testHostAuthorizationCheckIsSkipped(): void + { + $this->mcp($this->initialize(1)); + + $this->assertTrue(AuthorizationSpy::$skipped); + } + + /** + * @param array $message + * @param array $headers Overrides; an empty Authorization removes it. + */ + private function mcp(array $message, array $headers = []): void + { + $headers += [ + 'Host' => 'localhost', + 'Accept' => 'application/json, text/event-stream', + 'Content-Type' => 'application/json', + 'Authorization' => 'Bearer ' . TestTokens::EDITOR, + ]; + $this->configRequest(['headers' => array_filter($headers, fn(string $value): bool => $value !== '')]); + $this->post('/mcp', (string)json_encode($message)); + } + + /** + * @return array + */ + private function initialize(int $id): array + { + return ['jsonrpc' => '2.0', 'id' => $id, 'method' => 'initialize', 'params' => [ + 'protocolVersion' => self::HANDSHAKE, + 'capabilities' => new stdClass(), + 'clientInfo' => ['name' => 'test', 'version' => '1.0'], + ]]; + } + + /** + * @param array $arguments + * @return array + */ + private function handshakeCall(int $id, string $tool, array $arguments = []): array + { + return ['jsonrpc' => '2.0', 'id' => $id, 'method' => 'tools/call', 'params' => [ + 'name' => $tool, + 'arguments' => $arguments === [] ? new stdClass() : $arguments, + ]]; + } + + /** + * @param array $params + * @return array + */ + private function modern(int $id, string $method, array $params = []): array + { + $params['_meta'] = [ + 'io.modelcontextprotocol/protocolVersion' => self::MODERN, + 'io.modelcontextprotocol/clientCapabilities' => new stdClass(), + ]; + + return ['jsonrpc' => '2.0', 'id' => $id, 'method' => $method, 'params' => $params]; + } + + /** + * @return array + */ + private function modernHeaders(string $method, ?string $name = null): array + { + $headers = ['MCP-Protocol-Version' => self::MODERN, 'Mcp-Method' => $method]; + if ($name !== null) { + $headers['Mcp-Name'] = $name; + } + + return $headers; + } + + /** + * @return array + */ + private function json(): array + { + $decoded = json_decode((string)$this->_response->getBody(), true); + + return is_array($decoded) ? $decoded : []; + } + + /** + * @return list + */ + private function toolNames(): array + { + return array_column($this->json()['result']['tools'] ?? [], 'name'); + } +} diff --git a/tests/TestCase/DocsTest.php b/tests/TestCase/DocsTest.php new file mode 100644 index 0000000..841dfe2 --- /dev/null +++ b/tests/TestCase/DocsTest.php @@ -0,0 +1,79 @@ + + */ + private function markdownFiles(): array + { + $files = [self::ROOT . 'README.md', self::ROOT . 'CHANGELOG.md']; + foreach (glob(self::ROOT . 'docs/*.md') ?: [] as $file) { + $files[] = $file; + } + + return $files; + } + + public function testEveryAuthSettingIsDocumented(): void + { + $configuration = (string)file_get_contents(self::ROOT . 'docs/configuration.md'); + $keys = []; + foreach (McpConfig::DEFAULTS['auth'] as $key => $value) { + $keys[] = 'auth.' . $key; + if (is_array($value) && !array_is_list($value)) { + foreach (array_keys($value) as $child) { + $keys[] = 'auth.' . $key . '.' . $child; + } + } + } + foreach ($keys as $key) { + $this->assertStringContainsString('`' . $key . '`', $configuration, $key . ' is not documented'); + } + } + + public function testEveryAuditSettingIsDocumented(): void + { + $configuration = (string)file_get_contents(self::ROOT . 'docs/configuration.md'); + foreach (array_keys(McpConfig::DEFAULTS['audit']) as $key) { + $this->assertStringContainsString('`audit.' . $key . '`', $configuration, 'audit.' . $key . ' is not documented'); + } + $this->assertStringContainsString('Mcp.audit', $configuration); + } + + public function testRelativeLinksResolve(): void + { + foreach ($this->markdownFiles() as $file) { + preg_match_all('/\]\((?!https?:|mailto:|#)([^)#\s]+)/', (string)file_get_contents($file), $matches); + foreach ($matches[1] as $link) { + $this->assertFileExists(dirname($file) . '/' . $link, basename($file) . ' links to ' . $link); + } + } + } + + public function testNoEmOrEnDashes(): void + { + $files = $this->markdownFiles(); + $sources = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(self::ROOT . 'src')); + foreach ($sources as $source) { + if ($source->isFile() && $source->getExtension() === 'php') { + $files[] = $source->getPathname(); + } + } + foreach ($files as $file) { + $text = (string)file_get_contents($file); + $this->assertStringNotContainsString("\u{2014}", $text, $file . ' has an em-dash'); + $this->assertStringNotContainsString("\u{2013}", $text, $file . ' has an en-dash'); + } + } +} diff --git a/tests/TestCase/Event/AuditListenerTest.php b/tests/TestCase/Event/AuditListenerTest.php new file mode 100644 index 0000000..1752ad8 --- /dev/null +++ b/tests/TestCase/Event/AuditListenerTest.php @@ -0,0 +1,377 @@ +> + */ + private array $records = []; + + /** + * @var callable + */ + private $listener; + + protected function setUp(): void + { + parent::setUp(); + Cache::drop('mcp_sessions'); + Cache::setConfig('mcp_sessions', ['className' => ArrayEngine::class]); + Configure::write('Mcp.audit.enabled', true); + Configure::write('Mcp.audit.log', false); + $this->records = []; + $this->listener = function (EventInterface $event): void { + $this->records[] = (array)$event->getData(); + }; + EventManager::instance()->on('Mcp.audit', $this->listener); + } + + protected function tearDown(): void + { + EventManager::instance()->off('Mcp.audit', $this->listener); + Cache::drop('mcp_sessions'); + parent::tearDown(); + } + + /** + * @return array + */ + private function onlyRecord(): array + { + $this->assertCount(1, $this->records); + + return $this->records[0]; + } + + private function onlyForAdmins(string $tool): ToolAuthorizerInterface + { + return new class ($tool) implements ToolAuthorizerInterface { + public function __construct(private readonly string $tool) + { + } + + public function canCall(mixed $identity, string $tool): bool + { + return $tool !== $this->tool || (is_array($identity) && ($identity['role'] ?? null) === 'admin'); + } + }; + } + + private function listener(?ToolGate $gate = null): AuditListener + { + $identity = new CurrentIdentity(); + + return new AuditListener( + AuditSettings::fromConfig(), + new AuditWriter(AuditSettings::fromConfig()), + $gate ?? new ToolGate(new AllowAllToolAuthorizer(), $identity), + $identity, + ); + } + + public function testOffByDefault(): void + { + Configure::delete('Mcp.audit'); + + $this->mcpCallTool('echo', ['text' => 'hi']); + + $this->assertSame([], $this->records); + } + + public function testOkCall(): void + { + $this->mcpActingAs(['id' => 7]); + + $this->mcpCallTool('echo', ['text' => 'hi']); + + $record = $this->onlyRecord(); + $this->assertSame('tools/call', $record['method']); + $this->assertSame('echo', $record['name']); + $this->assertSame(AuditRecord::OK, $record['outcome']); + $this->assertSame(7, $record['identity']); + $this->assertSame(['text' => 'hi'], $record['arguments']); + $this->assertIsInt($record['durationMs']); + $this->assertGreaterThanOrEqual(0, $record['durationMs']); + $this->assertIsString($record['session']); + $this->assertNotSame('', $record['session']); + $this->assertSame(2, $record['request']); + $this->assertNull($record['error']); + } + + public function testToolError(): void + { + $this->mcpCallTool('create_note', ['title' => 'ab']); + + $record = $this->onlyRecord(); + $this->assertSame(AuditRecord::TOOL_ERROR, $record['outcome']); + $this->assertStringContainsString('Use at least 3 characters.', (string)$record['error']); + } + + public function testThrowingToolIsError(): void + { + $this->mcpCallTool('explode'); + + $record = $this->onlyRecord(); + $this->assertSame(AuditRecord::ERROR, $record['outcome']); + $this->assertSame('Error while executing tool', $record['error']); + } + + public function testUnknownToolAndBadArgumentsAreInvalid(): void + { + $this->mcpCallTool('missing_tool'); + $this->mcpCallTool('echo', ['text' => ['not', 'a', 'string']]); + + $this->assertCount(2, $this->records); + $this->assertSame(AuditRecord::INVALID, $this->records[0]['outcome']); + $this->assertSame(AuditRecord::INVALID, $this->records[1]['outcome']); + } + + public function testDeniedIsRecordedButLooksUnknownToTheClient(): void + { + Configure::write('Mcp.authorization.authorizer', $this->onlyForAdmins('admin_only')); + $this->mcpActingAs(['id' => 1, 'role' => 'user']); + + $denied = $this->mcpCallTool('admin_only'); + $unknown = $this->mcpCallTool('missing_tool'); + + $this->assertSame(AuditRecord::DENIED, $this->records[0]['outcome']); + $this->assertSame(AuditRecord::INVALID, $this->records[1]['outcome']); + $this->assertSame( + json_encode($unknown), + str_replace('admin_only', 'missing_tool', (string)json_encode($denied)), + ); + } + + public function testUnknownToolIsInvalidEvenWhenTheAuthorizerRefusesUnknownNames(): void + { + // Like RbacToolAuthorizer: only the granted tools pass, so a missing tool is refused too. + Configure::write('Mcp.authorization.authorizer', new class implements ToolAuthorizerInterface { + public function canCall(mixed $identity, string $tool): bool + { + return $tool === 'echo'; + } + }); + $this->mcpActingAs(['id' => 1]); + + $unknown = $this->mcpCallTool('no_such_tool'); + $denied = $this->mcpCallTool('admin_only'); + + $this->assertSame(AuditRecord::INVALID, $this->records[0]['outcome']); + $this->assertSame(AuditRecord::DENIED, $this->records[1]['outcome']); + $this->assertSame( + json_encode($unknown), + str_replace('admin_only', 'no_such_tool', (string)json_encode($denied)), + ); + } + + /** + * @return array, 1: string|null}> + */ + public static function claims(): array + { + return [ + 'client_id' => [['client_id' => 'a'], 'a'], + 'azp' => [['azp' => 'b'], 'b'], + 'aud string' => [['aud' => 'c'], 'c'], + 'aud list of one' => [['aud' => ['d']], 'd'], + 'aud list of two' => [['aud' => ['d', 'e']], null], + ]; + } + + /** + * @param array $claims + * @dataProvider claims + */ + public function testClientFromClaims(array $claims, ?string $client): void + { + $this->assertSame($client, AuditListener::clientOf(new AccessToken([], $claims + ['sub' => '1']))); + $this->mcpActingAs(['id' => 1], null, $claims); + + $this->mcpCallTool('echo', ['text' => 'hi']); + + $this->assertSame($client, $this->onlyRecord()['client']); + } + + public function testNoTokenNoClient(): void + { + $this->assertNull(AuditListener::clientOf(null)); + } + + public function testListingIsNotRecorded(): void + { + $this->mcpListTools(); + + $this->assertSame([], $this->records); + } + + public function testPromptsAndResourcesOnlyWhenListed(): void + { + $session = new Session(new InMemorySessionStore()); + $prompt = GetPromptRequest::fromArray([ + 'jsonrpc' => '2.0', 'id' => 5, 'method' => 'prompts/get', + 'params' => ['name' => 'briefing', 'arguments' => ['days' => '14']], + ]); + $resource = ReadResourceRequest::fromArray([ + 'jsonrpc' => '2.0', 'id' => 6, 'method' => 'resources/read', 'params' => ['uri' => 'app://glossary'], + ]); + + $listener = $this->listener(); + $listener->onResponse(new ResponseEvent(new Response(5, []), $prompt, $session)); + $this->assertSame([], $this->records); + + Configure::write('Mcp.audit.methods', ['prompts/get', 'resources/read']); + $listener = $this->listener(); + $listener->onResponse(new ResponseEvent(new Response(5, []), $prompt, $session)); + $listener->onResponse(new ResponseEvent(new Response(6, []), $resource, $session)); + + $this->assertSame('briefing', $this->records[0]['name']); + $this->assertSame(['days' => '14'], $this->records[0]['arguments']); + $this->assertSame('app://glossary', $this->records[1]['name']); + $this->assertSame([], $this->records[1]['arguments']); + } + + public function testTrustedGateHasNoDenials(): void + { + $identity = new CurrentIdentity(); + $listener = $this->listener(new ToolGate($this->onlyForAdmins('admin_only'), $identity, true)); + $request = CallToolRequest::fromArray([ + 'jsonrpc' => '2.0', 'id' => 3, 'method' => 'tools/call', 'params' => ['name' => 'admin_only', 'arguments' => []], + ]); + + $listener->onError(new ErrorEvent( + Error::forInvalidParams('Tool not found: "admin_only".', 3), + $request, + new Session(new InMemorySessionStore()), + null, + )); + + $this->assertSame(AuditRecord::INVALID, $this->onlyRecord()['outcome']); + } + + public function testUnknownStartTimeGivesNullDuration(): void + { + $request = CallToolRequest::fromArray([ + 'jsonrpc' => '2.0', 'id' => 4, 'method' => 'tools/call', 'params' => ['name' => 'echo', 'arguments' => []], + ]); + + $this->listener()->onResponse(new ResponseEvent(new Response(4, []), $request, new Session(new InMemorySessionStore()))); + + $this->assertNull($this->onlyRecord()['durationMs']); + } + + public function testAToolWaitingForInputIsNotRecordedYet(): void + { + $request = CallToolRequest::fromArray([ + 'jsonrpc' => '2.0', 'id' => 4, 'method' => 'tools/call', 'params' => ['name' => 'confirm', 'arguments' => []], + ]); + + $this->listener()->onResponse(new ResponseEvent( + new Response(4, new InputRequiredResult(requestState: 'round-1')), + $request, + new Session(new InMemorySessionStore()), + )); + + $this->assertSame([], $this->records); + } + + public function testLongNamesAndRequestIdsAreCut(): void + { + $name = str_repeat('n', 300); + $request = CallToolRequest::fromArray([ + 'jsonrpc' => '2.0', 'id' => str_repeat('r', 300), 'method' => 'tools/call', + 'params' => ['name' => $name, 'arguments' => []], + ]); + + $this->listener()->onResponse(new ResponseEvent( + new Response(str_repeat('r', 300), []), + $request, + new Session(new InMemorySessionStore()), + )); + + $this->assertSame(str_repeat('n', 255), $this->onlyRecord()['name']); + $this->assertSame(str_repeat('r', 255), $this->onlyRecord()['request']); + } + + public function testAFailingAuthorizerDoesNotEscapeTheListener(): void + { + $identity = new CurrentIdentity(); + $gate = new ToolGate(new class implements ToolAuthorizerInterface { + public function canCall(mixed $identity, string $tool): bool + { + throw new RuntimeException('authorizer exploded'); + } + }, $identity); + $request = CallToolRequest::fromArray([ + 'jsonrpc' => '2.0', 'id' => 3, 'method' => 'tools/call', 'params' => ['name' => 'echo', 'arguments' => []], + ]); + + $this->listener($gate)->onError(new ErrorEvent( + Error::forInvalidParams('Tool not found: "echo".', 3), + $request, + new Session(new InMemorySessionStore()), + null, + )); + + $this->assertSame([], $this->records); + } + + public function testDurationComesFromTheClock(): void + { + $identity = new CurrentIdentity(); + $times = [10.0, 10.25]; + $listener = new AuditListener( + AuditSettings::fromConfig(), + new AuditWriter(AuditSettings::fromConfig()), + new ToolGate(new AllowAllToolAuthorizer(), $identity), + $identity, + function () use (&$times): float { + return (float)array_shift($times); + }, + ); + $session = new Session(new InMemorySessionStore()); + $request = CallToolRequest::fromArray([ + 'jsonrpc' => '2.0', 'id' => 4, 'method' => 'tools/call', 'params' => ['name' => 'echo', 'arguments' => []], + ]); + + $listener->onRequest(new RequestEvent($request, $session)); + $listener->onResponse(new ResponseEvent(new Response(4, []), $request, $session)); + + $this->assertSame(250, $this->onlyRecord()['durationMs']); + } +} diff --git a/tests/TestCase/Event/EventDispatcherTest.php b/tests/TestCase/Event/EventDispatcherTest.php new file mode 100644 index 0000000..36b877c --- /dev/null +++ b/tests/TestCase/Event/EventDispatcherTest.php @@ -0,0 +1,52 @@ +listen(ArrayObject::class, function () use (&$calls): void { + $calls[] = 'exact'; + }); + $dispatcher->listen(IteratorAggregate::class, function () use (&$calls): void { + $calls[] = 'interface'; + }); + $dispatcher->listen(stdClass::class, function () use (&$calls): void { + $calls[] = 'unrelated'; + }); + $event = new ArrayObject(); + + $this->assertSame($event, $dispatcher->dispatch($event)); + $this->assertSame(['exact', 'interface'], $calls); + } + + public function testStopsOnceAStoppableEventIsStopped(): void + { + $dispatcher = new EventDispatcher(); + $event = new class implements StoppableEventInterface { + public int $calls = 0; + + public function isPropagationStopped(): bool + { + return $this->calls > 0; + } + }; + $dispatcher->listen($event::class, fn(object $e) => $e->calls++); + $dispatcher->listen($event::class, fn(object $e) => $e->calls++); + + $dispatcher->dispatch($event); + + $this->assertSame(1, $event->calls); + } +} diff --git a/tests/TestCase/Event/ToolListFilterTest.php b/tests/TestCase/Event/ToolListFilterTest.php new file mode 100644 index 0000000..011ce11 --- /dev/null +++ b/tests/TestCase/Event/ToolListFilterTest.php @@ -0,0 +1,68 @@ +tool('echo'), $this->tool('admin_only')], 'cursor-2'); + $event = $this->event(new Response(3, $result)); + + ($this->filter())($event); + + $filtered = $event->getResponse()->result; + $this->assertInstanceOf(ListToolsResult::class, $filtered); + $this->assertSame(['echo'], array_map(fn(Tool $tool): string => $tool->name, $filtered->tools)); + $this->assertSame('cursor-2', $filtered->nextCursor); + $this->assertSame(3, $event->getResponse()->getId()); + } + + public function testLeavesOtherResponsesAlone(): void + { + $response = new Response(4, ['anything' => true]); + $event = $this->event($response); + + ($this->filter())($event); + + $this->assertSame($response, $event->getResponse()); + } + + private function filter(): ToolListFilter + { + $onlyEcho = new class implements ToolAuthorizerInterface { + public function canCall(mixed $identity, string $tool): bool + { + return $tool === 'echo'; + } + }; + + return new ToolListFilter(new ToolGate($onlyEcho, new CurrentIdentity())); + } + + /** + * @param \Mcp\Schema\JsonRpc\Response $response + */ + private function event(Response $response): ResponseEvent + { + return new ResponseEvent($response, (new ListToolsRequest())->withId(1), $this->createStub(SessionInterface::class)); + } + + private function tool(string $name): Tool + { + return new Tool($name, null, ['type' => 'object'], null, null); + } +} diff --git a/tests/TestCase/Identity/CurrentIdentityTest.php b/tests/TestCase/Identity/CurrentIdentityTest.php new file mode 100644 index 0000000..a54f644 --- /dev/null +++ b/tests/TestCase/Identity/CurrentIdentityTest.php @@ -0,0 +1,41 @@ +assertSame(7, CurrentIdentity::identifierOf(['id' => 7])); + $this->assertSame('u-1', CurrentIdentity::identifierOf(new ArrayObject(['id' => 'u-1']))); + $this->assertSame(9, CurrentIdentity::identifierOf(new Entity(['id' => 9]))); + $this->assertSame(11, CurrentIdentity::identifierOf(new Identity(new ArrayObject(['id' => 11])))); + } + + public function testIdentifierIsNullForMissingOrOddValues(): void + { + $this->assertNull(CurrentIdentity::identifierOf(null)); + $this->assertNull(CurrentIdentity::identifierOf(['name' => 'no id'])); + $this->assertNull(CurrentIdentity::identifierOf(['id' => 1.5])); + $this->assertNull(CurrentIdentity::identifierOf('a string')); + } + + public function testHoldsTheIdentity(): void + { + $current = new CurrentIdentity(); + $this->assertFalse($current->has()); + + $current->set(['id' => 3]); + + $this->assertTrue($current->has()); + $this->assertSame(['id' => 3], $current->get()); + $this->assertSame(3, $current->getIdentifier()); + } +} diff --git a/tests/TestCase/Log/McpLoggerTest.php b/tests/TestCase/Log/McpLoggerTest.php new file mode 100644 index 0000000..8151acc --- /dev/null +++ b/tests/TestCase/Log/McpLoggerTest.php @@ -0,0 +1,60 @@ + ArrayLog::class, 'scopes' => ['mcp']]); + } + + protected function tearDown(): void + { + Log::drop('mcp_test'); + parent::tearDown(); + } + + public function testWritesToCakeLogUnderTheMcpScope(): void + { + (new McpLogger())->warning('Tool {name} failed', ['name' => 'echo']); + + $engine = Log::engine('mcp_test'); + $this->assertInstanceOf(ArrayLog::class, $engine); + $lines = $engine->read(); + $this->assertCount(1, $lines); + $this->assertStringContainsString('warning', $lines[0]); + $this->assertStringContainsString('Tool echo failed', $lines[0]); + } + + public function testExceptionDetailsAndUnusedContextReachTheLog(): void + { + (new McpLogger())->error( + 'Unhandled error during tool execution', + ['name' => 'echo', 'exception' => new RuntimeException('database exploded')], + ); + + $engine = Log::engine('mcp_test'); + $this->assertInstanceOf(ArrayLog::class, $engine); + $line = $engine->read()[0]; + $this->assertStringContainsString('database exploded', $line); + $this->assertStringContainsString('name=echo', $line); + } + + public function testPlaceholderContextIsNotAppendedTwice(): void + { + (new McpLogger())->warning('Tool {name} failed', ['name' => 'echo']); + + $engine = Log::engine('mcp_test'); + $this->assertInstanceOf(ArrayLog::class, $engine); + $this->assertStringNotContainsString('name=echo', $engine->read()[0]); + } +} diff --git a/tests/TestCase/McpConfigTest.php b/tests/TestCase/McpConfigTest.php new file mode 100644 index 0000000..42af299 --- /dev/null +++ b/tests/TestCase/McpConfigTest.php @@ -0,0 +1,190 @@ +assertSame('/mcp', McpConfig::get('route')); + $this->assertSame(['src/Mcp'], McpConfig::get('discovery.scanDirs')); + $this->assertTrue(McpConfig::get('identity.required')); + $this->assertSame(AllowAllToolAuthorizer::class, McpConfig::get('authorization.authorizer')); + $this->assertTrue(McpConfig::get('stdio.trusted')); + } + + public function testHostValuesOverrideAndKeepSiblingDefaults(): void + { + Configure::write('Mcp', ['server' => ['name' => 'Host Server']]); + + $this->assertSame('Host Server', McpConfig::get('server.name')); + $this->assertSame('1.0.0', McpConfig::get('server.version')); + } + + public function testListsAreReplacedNotAppended(): void + { + Configure::write('Mcp.discovery.scanDirs', ['src/Tools']); + + $this->assertSame(['src/Tools'], McpConfig::get('discovery.scanDirs')); + } + + public function testRouteCanBeDisabledWithFalse(): void + { + Configure::write('Mcp.route', false); + + $this->assertFalse(McpConfig::get('route')); + } + + public function testDiscoveryCacheIsOffInDebugAndNamedOtherwise(): void + { + Configure::write('debug', true); + $this->assertNull(McpConfig::discoveryCache()); + + Configure::write('debug', false); + $this->assertSame('_cake_mcp_', McpConfig::discoveryCache()); + + Configure::write('Mcp.discovery.cache', false); + $this->assertNull(McpConfig::discoveryCache()); + } + + public function testAllowedHostsDefaultToFullBaseUrlHostPlusLocalhost(): void + { + Configure::write('App.fullBaseUrl', 'https://MCP.Example.com:8443'); + + $this->assertSame(['mcp.example.com', 'localhost', '127.0.0.1', '[::1]'], McpConfig::allowedHosts()); + } + + public function testExplicitAllowedHostsAreUsedAsGivenLowercased(): void + { + Configure::write('Mcp.http.allowedHosts', ['API.example.com']); + + $this->assertSame(['api.example.com'], McpConfig::allowedHosts()); + } + + public function testEmptyArrayOverAnAssociativeDefaultKeepsTheDefault(): void + { + Configure::write('Mcp.identity', []); + + $this->assertTrue(McpConfig::get('identity.required')); + $this->assertSame('identity', McpConfig::get('identity.attribute')); + } + + public function testEmptyListOverAListDefaultStillReplaces(): void + { + Configure::write('Mcp.discovery.scanDirs', []); + + $this->assertSame([], McpConfig::get('discovery.scanDirs')); + } + + public function testIsEndpointMatchesTheRoute(): void + { + foreach (['/mcp', '/mcp/'] as $path) { + $this->assertTrue(McpConfig::isEndpoint(new ServerRequest(['url' => $path])), $path); + } + foreach (['/mcpx', '/api/mcp', '/', '/.well-known/oauth-protected-resource/mcp'] as $path) { + $this->assertFalse(McpConfig::isEndpoint(new ServerRequest(['url' => $path])), $path); + } + } + + public function testIsEndpointIsFalseWhenTheRouteIsDisabled(): void + { + Configure::write('Mcp.route', false); + + $this->assertFalse(McpConfig::isEndpoint(new ServerRequest(['url' => '/mcp']))); + } + + public function testRbacPermissionsBypassAuthForTheEndpoint(): void + { + $this->assertSame([ + [ + 'role' => '*', + 'plugin' => 'CakeDC/Mcp', + 'controller' => 'Mcp', + 'action' => 'handle', + 'bypassAuth' => true, + ], + ], McpConfig::rbacPermissions()); + } + + public function testRbacPermissionsLetAnonymousRequestsReachThePluginOnly(): void + { + Router::reload(); + (new McpPlugin())->routes(Router::createRouteBuilder('/')); + $rbac = new Rbac(['permissions' => McpConfig::rbacPermissions(), 'log' => false]); + $routed = fn(string $url, string $method): ServerRequest => (new ServerRequest([ + 'url' => $url, + 'environment' => ['REQUEST_METHOD' => $method], + ]))->withAttribute('params', Router::parseRequest(new ServerRequest([ + 'url' => $url, + 'environment' => ['REQUEST_METHOD' => $method], + ]))); + + try { + $this->assertTrue($rbac->checkPermissions([], $routed('/mcp', 'POST'))); + $other = (new ServerRequest(['url' => '/users/delete']))->withAttribute('params', [ + 'plugin' => null, + 'controller' => 'Users', + 'action' => 'delete', + ]); + $this->assertFalse($rbac->checkPermissions([], $other)); + } finally { + Router::reload(); + } + } + + public function testHostAuthModeIsAccepted(): void + { + McpConfig::assertHostAuthMode(); + Configure::write('Mcp.auth.mode', 'host'); + McpConfig::assertHostAuthMode(); + + $this->assertSame('host', McpConfig::get('auth.mode')); + } + + public function testTheAuthModesOf2xAreRefused(): void + { + Configure::write('Mcp.auth.mode', 'oauth'); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('"Mcp.auth.mode" "oauth" is not available in cakedc/cakephp-mcp 1.x (CakePHP 4)'); + McpConfig::assertHostAuthMode(); + } + + public function testTheBodyLimitDefaultsToTheSdkLimit(): void + { + Configure::delete('Mcp'); + + $this->assertSame(StreamableHttpTransport::DEFAULT_MAX_BODY_BYTES, McpConfig::maxBodyBytes()); + $this->assertSame(4194304, McpConfig::get('http.maxBodyBytes')); + } + + public function testTheBodyLimitMustBeAPositiveInteger(): void + { + Configure::write('Mcp.http.maxBodyBytes', 1024); + $this->assertSame(1024, McpConfig::maxBodyBytes()); + + foreach ([0, -1, '1024', 1.5, null] as $invalid) { + Configure::write('Mcp.http.maxBodyBytes', $invalid); + try { + McpConfig::maxBodyBytes(); + $this->fail('Accepted ' . var_export($invalid, true)); + } catch (InvalidArgumentException $e) { + $this->assertStringContainsString('Mcp.http.maxBodyBytes', $e->getMessage()); + } + } + } +} diff --git a/tests/TestCase/McpPluginTest.php b/tests/TestCase/McpPluginTest.php new file mode 100644 index 0000000..34cffd8 --- /dev/null +++ b/tests/TestCase/McpPluginTest.php @@ -0,0 +1,104 @@ +tearDownCaches(); + } + + protected function tearDown(): void + { + $this->tearDownCaches(); + parent::tearDown(); + } + + private function tearDownCaches(): void + { + Cache::drop('_cake_mcp_'); + Cache::drop('mcp_sessions'); + Cache::drop('host_sessions'); + } + + public function testTheTestAppLoadsThePlugin(): void + { + $app = new Application(CONFIG); + $app->bootstrap(); + $app->pluginBootstrap(); + + $this->assertTrue($app->getPlugins()->has('CakeDC/Mcp')); + } + + public function testBootstrapDefinesMissingCacheConfigs(): void + { + $app = new Application(CONFIG); + $app->bootstrap(); + $app->pluginBootstrap(); + + $this->assertInstanceOf(FileEngine::class, Cache::pool('_cake_mcp_')); + $this->assertInstanceOf(FileEngine::class, Cache::pool('mcp_sessions')); + } + + public function testBootstrapKeepsCacheConfigsTheHostDefined(): void + { + Configure::write('Mcp.session.cache', 'host_sessions'); + Cache::setConfig('host_sessions', ['className' => ArrayEngine::class]); + + $app = new Application(CONFIG); + $app->bootstrap(); + $app->pluginBootstrap(); + + $this->assertInstanceOf(ArrayEngine::class, Cache::pool('host_sessions')); + } + + public function testBootstrapRefusesTheAuthModesOf2x(): void + { + foreach (['oauth', 'external'] as $mode) { + Configure::write('Mcp.auth.mode', $mode); + $app = new Application(CONFIG); + $app->bootstrap(); + try { + $app->pluginBootstrap(); + $this->fail(sprintf('Mcp.auth.mode %s should be refused.', $mode)); + } catch (InvalidArgumentException $e) { + $this->assertStringContainsString('is not available in cakedc/cakephp-mcp 1.x', $e->getMessage()); + } + } + } + + public function testRoutesConnectTheEndpointAtTheConfiguredPath(): void + { + Configure::write('Mcp.route', '/ai/mcp'); + $collection = new RouteCollection(); + + (new McpPlugin())->routes(new RouteBuilder($collection, '/')); + + $this->assertCount(1, $collection->routes()); + $this->assertSame('/ai/mcp', $collection->routes()[0]->template); + } + + public function testRoutesAreSkippedWhenDisabled(): void + { + Configure::write('Mcp.route', false); + $collection = new RouteCollection(); + + (new McpPlugin())->routes(new RouteBuilder($collection, '/')); + + $this->assertCount(0, $collection->routes()); + } +} diff --git a/tests/TestCase/Middleware/BodyLimitMiddlewareTest.php b/tests/TestCase/Middleware/BodyLimitMiddlewareTest.php new file mode 100644 index 0000000..9dedddf --- /dev/null +++ b/tests/TestCase/Middleware/BodyLimitMiddlewareTest.php @@ -0,0 +1,164 @@ +middleware(16)->process($this->post(str_repeat('a', 16)), $this->handler()); + + $this->assertSame(200, $response->getStatusCode()); + $this->assertSame(str_repeat('a', 16), $this->handled); + } + + public function testAnAnnouncedOversizedBodyIsRefusedWithoutReadingIt(): void + { + $unreadable = new class ('php://memory', 'r') extends Stream { + /** + * @param int $length Bytes to read. + * @return string + */ + public function read($length): string + { + throw new RuntimeException('The body must not be read.'); + } + + public function getSize(): ?int + { + return null; + } + }; + $request = (new ServerRequest(['environment' => ['REQUEST_METHOD' => 'POST']])) + ->withHeader('Content-Length', '17') + ->withBody($unreadable); + + $response = $this->middleware(16)->process($request, $this->handler()); + + $this->assertTooLarge($response, 16); + $this->assertNull($this->handled); + } + + public function testABodyOfUnknownSizeIsReadOnlyUpToTheLimit(): void + { + $resource = fopen('php://memory', 'r+'); + fwrite($resource, str_repeat('a', 100)); + rewind($resource); + $unsized = new class ($resource) extends Stream { + public function getSize(): ?int + { + return null; + } + }; + $request = (new ServerRequest(['environment' => ['REQUEST_METHOD' => 'POST']]))->withBody($unsized); + + $response = $this->middleware(16)->process($request, $this->handler()); + + $this->assertTooLarge($response, 16); + $this->assertNull($this->handled); + } + + public function testAnUnsizedBodyIsNeverReadPastTheLimitPlusOneByte(): void + { + $resource = fopen('php://memory', 'r+'); + fwrite($resource, str_repeat('a', 100000)); + rewind($resource); + $counting = new class ($resource) extends Stream { + public int $bytesRead = 0; + + public function getSize(): ?int + { + return null; + } + + /** + * @param int $length Bytes to read. + * @return string + */ + public function read($length): string + { + $chunk = parent::read($length); + $this->bytesRead += strlen($chunk); + + return $chunk; + } + }; + $request = (new ServerRequest(['environment' => ['REQUEST_METHOD' => 'POST']]))->withBody($counting); + + $response = $this->middleware(16)->process($request, $this->handler()); + + $this->assertTooLarge($response, 16); + $this->assertLessThanOrEqual(17, $counting->bytesRead); + } + + public function testOtherMethodsPassUntouched(): void + { + $request = new ServerRequest(['environment' => ['REQUEST_METHOD' => 'GET']]); + + $response = $this->middleware(1)->process($request, $this->handler()); + + $this->assertSame(200, $response->getStatusCode()); + } + + private function middleware(int $max): BodyLimitMiddleware + { + return new BodyLimitMiddleware($max, new ResponseFactory(), new StreamFactory()); + } + + private function post(string $body): ServerRequest + { + return (new ServerRequest(['environment' => ['REQUEST_METHOD' => 'POST']])) + ->withBody((new StreamFactory())->createStream($body)); + } + + private function handler(): RequestHandlerInterface + { + $record = function (ServerRequestInterface $request): ResponseInterface { + $this->handled = (string)$request->getBody(); + + return new Response(['status' => 200]); + }; + + return new class ($record) implements RequestHandlerInterface { + public function __construct(private readonly Closure $record) + { + } + + public function handle(ServerRequestInterface $request): ResponseInterface + { + return ($this->record)($request); + } + }; + } + + private function assertTooLarge(ResponseInterface $response, int $limit): void + { + $this->assertSame(413, $response->getStatusCode()); + $this->assertSame('application/json', $response->getHeaderLine('Content-Type')); + $this->assertSame('', $response->getHeaderLine('WWW-Authenticate')); + $body = json_decode((string)$response->getBody(), true); + $this->assertSame('2.0', $body['jsonrpc'] ?? null); + $this->assertSame(-32600, $body['error']['code'] ?? null); + $this->assertSame($limit, $body['error']['data']['maxBodyBytes'] ?? null); + $message = (string)($body['error']['message'] ?? ''); + $this->assertStringContainsString(sprintf('the limit is %d bytes', $limit), $message); + $this->assertStringContainsString('Mcp.http.maxBodyBytes', $message); + $this->assertStringContainsString('smaller payload', $message); + } +} diff --git a/tests/TestCase/Middleware/IdentityMiddlewareTest.php b/tests/TestCase/Middleware/IdentityMiddlewareTest.php new file mode 100644 index 0000000..7272678 --- /dev/null +++ b/tests/TestCase/Middleware/IdentityMiddlewareTest.php @@ -0,0 +1,143 @@ +current = new CurrentIdentity(); + $this->handled = null; + } + + public function testMissingIdentityIsChallengedWhenRequired(): void + { + $response = $this->middleware()->process($this->request(), $this->handler()); + + $this->assertSame(401, $response->getStatusCode()); + $this->assertSame('Bearer', $response->getHeaderLine('WWW-Authenticate')); + $this->assertStringContainsString('unauthorized', (string)$response->getBody()); + $this->assertNull($this->handled); + } + + public function testMissingIdentityPassesWhenNotRequired(): void + { + $response = $this->middleware(required: false)->process($this->request(), $this->handler()); + + $this->assertSame(200, $response->getStatusCode()); + $this->assertNotNull($this->handled); + $this->assertNull($this->handled->getAttribute(AccessToken::class)); + $this->assertFalse($this->current->has()); + } + + public function testOptionsPassesWithoutIdentity(): void + { + $response = $this->middleware()->process($this->request('OPTIONS'), $this->handler()); + + $this->assertSame(200, $response->getStatusCode()); + $this->assertNotNull($this->handled); + } + + public function testIdentityBecomesAnAccessTokenAndTheCurrentIdentity(): void + { + $identity = ['id' => 7, 'role' => 'editor']; + + $this->middleware()->process($this->request()->withAttribute('identity', $identity), $this->handler()); + + $token = $this->handled?->getAttribute(AccessToken::class); + $this->assertInstanceOf(AccessToken::class, $token); + $this->assertSame('7', $token->getSubject()); + $this->assertSame([], $token->getScopes()); + $this->assertSame($identity, $this->current->get()); + } + + public function testScopesComeFromTheConfiguredCallable(): void + { + $scopes = fn(mixed $identity): array => ['posts:' . $identity['role'], 42]; + + $this->middleware(scopes: $scopes)->process( + $this->request()->withAttribute('identity', ['id' => 1, 'role' => 'editor']), + $this->handler(), + ); + + $token = $this->handled?->getAttribute(AccessToken::class); + $this->assertInstanceOf(AccessToken::class, $token); + $this->assertSame(['posts:editor'], $token->getScopes()); + } + + public function testCustomAttributeName(): void + { + $this->middleware(attribute: 'user')->process( + $this->request()->withAttribute('user', ['id' => 5]), + $this->handler(), + ); + + $this->assertSame(5, $this->current->getIdentifier()); + } + + public function testCurrentIdentityIsResetOnEveryRequest(): void + { + $this->current->set(['id' => 99]); + + $this->middleware(required: false)->process($this->request(), $this->handler()); + + $this->assertFalse($this->current->has()); + } + + private function middleware(bool $required = true, string $attribute = 'identity', ?Closure $scopes = null): IdentityMiddleware + { + return new IdentityMiddleware( + $this->current, + new ResponseFactory(), + new StreamFactory(), + $required, + $attribute, + $scopes, + ); + } + + private function request(string $method = 'POST'): ServerRequest + { + return new ServerRequest(['environment' => ['REQUEST_METHOD' => $method]]); + } + + private function handler(): RequestHandlerInterface + { + return new class ($this) implements RequestHandlerInterface { + public function __construct(private IdentityMiddlewareTest $test) + { + } + + public function handle(ServerRequestInterface $request): ResponseInterface + { + $this->test->record($request); + + return new Response(); + } + }; + } + + public function record(ServerRequestInterface $request): void + { + $this->handled = $request; + } +} diff --git a/tests/TestCase/Server/ServerFactoryTest.php b/tests/TestCase/Server/ServerFactoryTest.php new file mode 100644 index 0000000..0f81123 --- /dev/null +++ b/tests/TestCase/Server/ServerFactoryTest.php @@ -0,0 +1,269 @@ + ArrayEngine::class]); + $container = new Container(); + $this->identity = new CurrentIdentity(); + $container->addShared(CurrentIdentity::class, $this->identity); + $this->factory = new ServerFactory($container, $this->identity); + } + + protected function tearDown(): void + { + Cache::drop('mcp_sessions'); + parent::tearDown(); + } + + public function testListsDiscoveredTools(): void + { + $this->assertSame( + ['admin_only', 'create_note', 'echo', 'explode', 'whoami'], + $this->toolNames($this->runServer()), + ); + } + + public function testValidationErrorsReachTheModelAsAToolError(): void + { + $transport = $this->runServer([$this->call(3, 'create_note', ['title' => 'ab'])]); + + $result = $transport->responseFor(3)['result'] ?? []; + $this->assertTrue($result['isError'] ?? false); + $this->assertSame( + "The note was not created.\n- title: Use at least 3 characters.", + $result['content'][0]['text'] ?? null, + ); + } + + public function testToolAnnotationsReachTheToolList(): void + { + $tools = array_column($this->runServer()->responseFor(2)['result']['tools'] ?? [], null, 'name'); + + $this->assertSame(['readOnlyHint' => true, 'idempotentHint' => true], $tools['echo']['annotations'] ?? null); + $this->assertArrayNotHasKey('annotations', $tools['explode'] ?? []); + } + + public function testCallsATool(): void + { + $transport = $this->runServer([$this->call(3, 'echo', ['text' => 'hello'])]); + + $this->assertSame('hello', $transport->responseFor(3)['result']['content'][0]['text'] ?? null); + } + + public function testToolsSeeTheCurrentIdentity(): void + { + $this->identity->set(['id' => 5]); + + $transport = $this->runServer([$this->call(3, 'whoami')]); + + $text = (string)($transport->responseFor(3)['result']['content'][0]['text'] ?? ''); + $this->assertSame(5, json_decode($text, true)['identifier'] ?? null); + } + + public function testToolExceptionsDoNotLeakTheirMessage(): void + { + $transport = $this->runServer([$this->call(3, 'explode')]); + + $response = (string)json_encode($transport->responseFor(3)); + $this->assertStringContainsString('-32603', $response); + $this->assertStringNotContainsString('secret details', $response); + } + + public function testDeniedToolsAreHiddenAndRejected(): void + { + Configure::write('Mcp.authorization.authorizer', $this->onlyEcho()); + + $transport = $this->runServer([$this->call(3, 'admin_only')]); + + $this->assertSame(['echo'], $this->toolNames($transport)); + $this->assertSame('Tool not found: "admin_only".', $transport->responseFor(3)['error']['message'] ?? null); + } + + public function testTrustedServersSkipTheAuthorizer(): void + { + Configure::write('Mcp.authorization.authorizer', $this->onlyEcho()); + + $this->assertContains('admin_only', $this->toolNames($this->runServer([], true))); + } + + public function testRbacAuthorizerFromConfig(): void + { + Configure::write('Mcp.authorization', [ + 'authorizer' => RbacToolAuthorizer::class, + 'rbac' => ['log' => false, 'permissions' => [ + ['role' => 'editor', 'plugin' => 'CakeDC/Mcp', 'controller' => 'Tools', 'action' => ['echo']], + ]], + ]); + $this->identity->set(['id' => 1, 'role' => 'editor']); + + $this->assertSame(['echo'], $this->toolNames($this->runServer())); + } + + public function testMissingScanDirYieldsEmptyToolList(): void + { + Configure::write('Mcp.discovery.scanDirs', ['src/DoesNotExist']); + + $this->assertSame([], $this->toolNames($this->runServer())); + } + + public function testInstructionsAreAnnouncedOnInitialize(): void + { + Configure::write('Mcp.server', ['name' => 'Test Server', 'instructions' => 'Use echo to test.']); + + $result = $this->runServer()->responseFor(1)['result'] ?? []; + + $this->assertSame('Test Server', $result['serverInfo']['name'] ?? null); + $this->assertSame('Use echo to test.', $result['instructions'] ?? null); + } + + public function testServerInfoFromConfig(): void + { + Configure::write('Mcp.server', [ + 'title' => 'My App', + 'description' => 'Articles and orders.', + 'websiteUrl' => 'https://app.example.com', + ]); + + $info = $this->runServer()->responseFor(1)['result']['serverInfo'] ?? []; + + $this->assertSame('CakePHP MCP Server', $info['name'] ?? null); + $this->assertSame('My App', $info['title'] ?? null); + $this->assertSame('Articles and orders.', $info['description'] ?? null); + $this->assertSame('https://app.example.com', $info['websiteUrl'] ?? null); + } + + public function testConfigureHookReceivesTheBuilder(): void + { + Configure::write('Mcp.server.configure', function (Builder $builder): void { + $builder->addTool(fn(): string => 'pong', name: 'ping', description: 'Answers pong.'); + }); + + $transport = $this->runServer([$this->call(3, 'ping')]); + + $this->assertContains('ping', $this->toolNames($transport)); + $this->assertSame('pong', $transport->responseFor(3)['result']['content'][0]['text'] ?? null); + } + + public function testConfigureHookCannotReplaceThePluginSettings(): void + { + Configure::write('Mcp.authorization.authorizer', $this->onlyEcho()); + Configure::write('Mcp.server.configure', function (Builder $builder): void { + $builder->setServerInfo('Replaced', '9.9.9')->setEventDispatcher(new EventDispatcher()); + }); + + $transport = $this->runServer([$this->call(3, 'admin_only')]); + + $this->assertSame('CakePHP MCP Server', $transport->responseFor(1)['result']['serverInfo']['name'] ?? null); + $this->assertSame(['echo'], $this->toolNames($transport)); + $this->assertSame('Tool not found: "admin_only".', $transport->responseFor(3)['error']['message'] ?? null); + } + + public function testAuthorizerAppliesToToolsAddedByTheHook(): void + { + Configure::write('Mcp.authorization.authorizer', $this->onlyEcho()); + Configure::write('Mcp.server.configure', function (Builder $builder): void { + $builder->addTool(fn(): string => 'pong', name: 'ping', description: 'Answers pong.'); + }); + + $transport = $this->runServer([$this->call(3, 'ping')]); + + $this->assertSame(['echo'], $this->toolNames($transport)); + $this->assertSame('Tool not found: "ping".', $transport->responseFor(3)['error']['message'] ?? null); + } + + public function testRejectsAConfigureHookThatIsNotCallable(): void + { + Configure::write('Mcp.server.configure', 'not_a_function'); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Mcp.server.configure'); + $this->factory->create(); + } + + public function testRejectsAnInvalidAuthorizer(): void + { + Configure::write('Mcp.authorization.authorizer', 'NotAnAuthorizer'); + + $this->expectException(InvalidArgumentException::class); + $this->factory->create(); + } + + /** + * Runs initialize, notifications/initialized, tools/list (id 2), then $extra. + * + * @param list $extra More JSON-RPC lines. + */ + private function runServer(array $extra = [], bool $trusted = false): RecordingTransport + { + $transport = new RecordingTransport(array_merge([ + (string)json_encode(['jsonrpc' => '2.0', 'id' => 1, 'method' => 'initialize', 'params' => [ + 'protocolVersion' => '2025-06-18', + 'capabilities' => new stdClass(), + 'clientInfo' => ['name' => 'test', 'version' => '1.0'], + ]]), + (string)json_encode(['jsonrpc' => '2.0', 'method' => 'notifications/initialized']), + (string)json_encode(['jsonrpc' => '2.0', 'id' => 2, 'method' => 'tools/list']), + ], $extra)); + $this->factory->create($trusted)->run($transport); + + return $transport; + } + + /** + * @param array $arguments + */ + private function call(int $id, string $tool, array $arguments = []): string + { + return (string)json_encode(['jsonrpc' => '2.0', 'id' => $id, 'method' => 'tools/call', 'params' => [ + 'name' => $tool, + 'arguments' => $arguments === [] ? new stdClass() : $arguments, + ]]); + } + + /** + * @return list + */ + private function toolNames(RecordingTransport $transport): array + { + $names = array_column($transport->responseFor(2)['result']['tools'] ?? [], 'name'); + sort($names); + + return $names; + } + + private function onlyEcho(): ToolAuthorizerInterface + { + return new class implements ToolAuthorizerInterface { + public function canCall(mixed $identity, string $tool): bool + { + return $tool === 'echo'; + } + }; + } +} diff --git a/tests/TestCase/TestSuite/McpTestTraitScopesTest.php b/tests/TestCase/TestSuite/McpTestTraitScopesTest.php new file mode 100644 index 0000000..c3e4f77 --- /dev/null +++ b/tests/TestCase/TestSuite/McpTestTraitScopesTest.php @@ -0,0 +1,44 @@ +mcpActingAs(new ArrayObject(['id' => 1])); + + $this->mcpCallTool('create_note', ['title' => 'Groceries']); + + $this->assertMcpToolSucceeded(); + } + + public function testScopesDoNotRefuseACall(): void + { + $this->mcpActingAs(new ArrayObject(['id' => 1]), []); + + $this->mcpCallTool('create_note', ['title' => 'Groceries']); + + $this->assertMcpToolSucceeded(); + } + + public function testClaimsReachTheAccessToken(): void + { + $this->mcpActingAs(new ArrayObject(['id' => 1]), ['notes:read'], ['sub' => 'from-claims']); + + $this->mcpCallTool('whoami'); + + $this->assertMcpResultContains('from-claims'); + } +} diff --git a/tests/TestCase/TestSuite/McpTestTraitTest.php b/tests/TestCase/TestSuite/McpTestTraitTest.php new file mode 100644 index 0000000..4ba4236 --- /dev/null +++ b/tests/TestCase/TestSuite/McpTestTraitTest.php @@ -0,0 +1,182 @@ + ArrayEngine::class]); + } + + protected function tearDown(): void + { + Cache::drop('mcp_sessions'); + parent::tearDown(); + } + + public function testCallsAToolAndReadsItsText(): void + { + $this->mcpCallTool('echo', ['text' => 'hello']); + + $this->assertMcpToolSucceeded(); + $this->assertMcpResultContains('hell'); + $this->assertSame('hello', $this->mcpResultText()); + } + + public function testToolsSeeTheIdentityAndTheAccessToken(): void + { + $this->mcpActingAs(['id' => 7]); + + $this->mcpCallTool('whoami'); + + $this->assertMcpStructuredContent(['subject' => '7', 'identifier' => 7]); + } + + public function testAnonymousByDefault(): void + { + $this->mcpCallTool('whoami'); + + $this->assertMcpStructuredContent(['identifier' => null, 'subject' => null]); + } + + public function testToolErrorsAreReadable(): void + { + $this->mcpCallTool('create_note', ['title' => 'ab']); + + $this->assertMcpToolError('- title: Use at least 3 characters.'); + $this->expectException(AssertionFailedError::class); + $this->assertMcpToolSucceeded(); + } + + public function testUnexpectedExceptionsAreJsonRpcErrors(): void + { + $this->mcpCallTool('explode'); + + $this->assertMcpJsonRpcError(-32603, 'Error while executing tool'); + $this->assertStringNotContainsString('secret', (string)json_encode($this->mcpResponse())); + } + + public function testInvalidArgumentsAreJsonRpcErrors(): void + { + $this->mcpCallTool('echo', []); + + $this->assertMcpJsonRpcError(-32602, 'Invalid parameters'); + } + + public function testDeniedToolsAreHiddenAndRejected(): void + { + Configure::write('Mcp.authorization.authorizer', $this->onlyForAdmins('admin_only')); + $this->mcpActingAs(['id' => 1, 'role' => 'user']); + + $this->assertMcpToolNotListed('admin_only'); + $this->assertMcpToolListed('echo'); + $this->mcpCallTool('admin_only'); + $this->assertMcpToolDenied(); + + $this->mcpActingAs(['id' => 2, 'role' => 'admin']); + $this->assertMcpToolListed('admin_only'); + $this->mcpCallTool('admin_only'); + $this->assertMcpToolSucceeded(); + } + + public function testDeniedFailsForAToolThatDoesNotExist(): void + { + $this->mcpCallTool('no_such_tool'); + + $this->expectException(AssertionFailedError::class); + $this->expectExceptionMessage('is not registered'); + $this->assertMcpToolDenied(); + } + + public function testDeniedFailsWhenTheCallSucceeded(): void + { + $this->mcpCallTool('echo', ['text' => 'hi']); + + $this->expectException(AssertionFailedError::class); + $this->assertMcpToolDenied(); + } + + public function testListToolsReturnsTheDefinitions(): void + { + $tools = array_column($this->mcpListTools(), null, 'name'); + + $this->assertSame(['readOnlyHint' => true, 'idempotentHint' => true], $tools['echo']['annotations'] ?? null); + } + + public function testMockedServicesReachTheTools(): void + { + Configure::write('Mcp.discovery.scanDirs', ['src/Mcp', 'src/McpExtra']); + $this->mockService(Greeter::class, fn(): Greeter => new Greeter(new Clock(), 'Hola')); + + $this->mcpCallTool('greet', ['name' => 'Ana']); + + $this->assertSame('Hola, Ana', $this->mcpResultText()); + } + + public function testToolsCanUseTheApplicationRoutes(): void + { + Configure::write('Mcp.discovery.scanDirs', ['src/McpExtra']); + + $this->mcpCallTool('article_link', ['id' => 5]); + + $this->assertMcpToolSucceeded(); + $this->assertSame('/Articles/view/5', $this->mcpResultText()); + } + + public function testFailuresShowTheServerLog(): void + { + Configure::write('Mcp.discovery.scanDirs', ['src/McpExtra']); + $this->mcpCallTool('broken'); + + $this->expectException(AssertionFailedError::class); + $this->expectExceptionMessage('The broken tool is broken on purpose.'); + $this->assertMcpToolSucceeded(); + } + + public function testNotListedFailsForAToolThatDoesNotExist(): void + { + $this->expectException(AssertionFailedError::class); + $this->expectExceptionMessage('is not registered'); + $this->assertMcpToolNotListed('no_such_tool'); + } + + public function testAssertionsNeedACall(): void + { + $this->expectException(AssertionFailedError::class); + $this->expectExceptionMessage('mcpCallTool()'); + $this->assertMcpToolSucceeded(); + } + + private function onlyForAdmins(string $tool): ToolAuthorizerInterface + { + return new class ($tool) implements ToolAuthorizerInterface { + public function __construct(private readonly string $tool) + { + } + + public function canCall(mixed $identity, string $tool): bool + { + return $tool !== $this->tool || (is_array($identity) && ($identity['role'] ?? null) === 'admin'); + } + }; + } +} diff --git a/tests/TestCase/Tool/ToolErrorTest.php b/tests/TestCase/Tool/ToolErrorTest.php new file mode 100644 index 0000000..e3746af --- /dev/null +++ b/tests/TestCase/Tool/ToolErrorTest.php @@ -0,0 +1,71 @@ + ['_empty' => 'This field cannot be left empty'], + 'slug' => ['unique' => 'Already taken', 'format' => 'Use lowercase letters'], + ]); + + $this->assertSame( + "The data is invalid.\n- title: This field cannot be left empty\n- slug: Already taken; Use lowercase letters", + $exception->getMessage(), + ); + } + + public function testFlatFieldMessagesKeepTheFieldName(): void + { + $this->assertSame( + "The data is invalid.\n- title: Required\n- slug: Taken", + ToolError::invalid(['title' => 'Required', 'slug' => 'Taken'])->getMessage(), + ); + } + + public function testNestedErrorsUseDottedPaths(): void + { + $exception = ToolError::invalid([ + 'tags' => [0 => ['name' => ['_required' => 'This field is required']]], + ]); + + $this->assertSame("The data is invalid.\n- tags.0.name: This field is required", $exception->getMessage()); + } + + public function testReadsTheErrorsOfAnEntityAndItsAssociations(): void + { + $tag = new Entity(); + $tag->setError('name', ['_required' => 'This field is required']); + $article = new Entity(['tags' => [$tag]]); + $article->setError('title', ['_empty' => 'This field cannot be left empty']); + + $this->assertSame( + "The data is invalid.\n- title: This field cannot be left empty\n- tags.0.name: This field is required", + ToolError::invalid($article)->getMessage(), + ); + } + + public function testCustomFirstLine(): void + { + $exception = ToolError::invalid(['title' => ['_empty' => 'Empty']], 'The article was not saved.'); + + $this->assertSame("The article was not saved.\n- title: Empty", $exception->getMessage()); + } + + public function testMessageWithoutAFieldIsListedAlone(): void + { + $this->assertSame("The data is invalid.\n- Something is off", ToolError::invalid(['Something is off'])->getMessage()); + } + + public function testNoErrorsLeavesOnlyTheFirstLine(): void + { + $this->assertSame('The data is invalid.', ToolError::invalid([])->getMessage()); + } +} diff --git a/tests/bootstrap.php b/tests/bootstrap.php new file mode 100644 index 0000000..8a12669 --- /dev/null +++ b/tests/bootstrap.php @@ -0,0 +1,61 @@ + 'TestApp', + 'encoding' => 'UTF-8', + 'base' => false, + 'baseUrl' => false, + 'dir' => APP_DIR, + 'webroot' => 'webroot', + 'wwwRoot' => WWW_ROOT, + 'fullBaseUrl' => 'http://localhost', + 'paths' => [ + 'plugins' => [ROOT . 'plugins' . DS], + 'templates' => [ROOT . 'templates' . DS], + ], +]); + +Security::setSalt('cakephp-mcp-test-salt-cakephp-mcp-test-salt-0123456789'); + +Cache::setConfig([ + '_cake_core_' => ['engine' => 'Array'], + '_cake_translations_' => ['engine' => 'Array'], + '_cake_model_' => ['engine' => 'Array'], + '_cake_routes_' => ['engine' => 'Array'], +]); diff --git a/tests/bootstrap_suite.php b/tests/bootstrap_suite.php new file mode 100644 index 0000000..ab571d0 --- /dev/null +++ b/tests/bootstrap_suite.php @@ -0,0 +1,10 @@ +run($argv)); diff --git a/tests/test_app/src/Application.php b/tests/test_app/src/Application.php new file mode 100644 index 0000000..146e92c --- /dev/null +++ b/tests/test_app/src/Application.php @@ -0,0 +1,87 @@ +addPlugin(McpPlugin::class, ['routes' => Configure::read('TestApp.mcpRoutes') !== false]); + } + + /** + * @param \Cake\Http\MiddlewareQueue $middlewareQueue The queue. + * @return \Cake\Http\MiddlewareQueue + */ + public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue + { + $csrf = new CsrfProtectionMiddleware(); + $csrf->skipCheckCallback(fn(ServerRequest $request): bool => McpConfig::isEndpoint($request)); + + return $middlewareQueue + ->add(new ErrorHandlerMiddleware()) + ->add(new RoutingMiddleware($this)) + ->add(new BodyParserMiddleware()) + ->add($csrf) + ->add(new AuthenticationMiddleware($this)) + ->add(new AuthorizationSpyMiddleware()); + } + + /** + * @param \Cake\Routing\RouteBuilder $routes The builder. + * @return void + */ + public function routes(RouteBuilder $routes): void + { + $routes->scope('/', function (RouteBuilder $builder): void { + $builder->fallbacks(); + }); + } + + /** + * @param \Psr\Http\Message\ServerRequestInterface $request The request. + * @return \Authentication\AuthenticationServiceInterface + */ + public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface + { + $service = new AuthenticationService(); + $service->loadIdentifier('Authentication.Callback', [ + 'callback' => fn(array $data): ?ArrayObject => TestTokens::identity($data['token'] ?? null), + ]); + $service->loadAuthenticator('Authentication.Token', [ + 'header' => 'Authorization', + 'tokenPrefix' => 'Bearer', + ]); + + return $service; + } +} diff --git a/tests/test_app/src/AuthorizationSpy.php b/tests/test_app/src/AuthorizationSpy.php new file mode 100644 index 0000000..507ff69 --- /dev/null +++ b/tests/test_app/src/AuthorizationSpy.php @@ -0,0 +1,21 @@ + $messages JSON-RPC lines to feed. + */ + public function __construct(ServerFactory $factory, CurrentIdentity $identity, private readonly array $messages) + { + parent::__construct($factory, $identity); + } + + /** + * @inheritDoc + */ + protected function createTransport(): TransportInterface + { + return $this->transport = new RecordingTransport($this->messages); + } +} diff --git a/tests/test_app/src/Mcp/AdminTools.php b/tests/test_app/src/Mcp/AdminTools.php new file mode 100644 index 0000000..fb2fed8 --- /dev/null +++ b/tests/test_app/src/Mcp/AdminTools.php @@ -0,0 +1,18 @@ + + */ + #[McpTool(name: 'whoami')] + public function whoami(RequestContext $context): array + { + return [ + 'identifier' => $this->identity->getIdentifier(), + 'subject' => $context->getAccessToken()?->getSubject(), + ]; + } + + /** + * Always fails, to exercise error handling. + */ + #[McpTool(name: 'explode')] + public function explode(): string + { + throw new RuntimeException('boom with secret details'); + } +} diff --git a/tests/test_app/src/Mcp/NoteTools.php b/tests/test_app/src/Mcp/NoteTools.php new file mode 100644 index 0000000..0d77f91 --- /dev/null +++ b/tests/test_app/src/Mcp/NoteTools.php @@ -0,0 +1,28 @@ + + */ + #[McpTool(name: 'create_note')] + public function create(string $title): array + { + $validator = (new Validator())->minLength('title', 3, 'Use at least 3 characters.'); + $errors = $validator->validate(['title' => $title]); + if ($errors !== []) { + throw ToolError::invalid($errors, 'The note was not created.'); + } + + return ['title' => $title]; + } +} diff --git a/tests/test_app/src/McpExtra/FailingTools.php b/tests/test_app/src/McpExtra/FailingTools.php new file mode 100644 index 0000000..2700047 --- /dev/null +++ b/tests/test_app/src/McpExtra/FailingTools.php @@ -0,0 +1,29 @@ + 'Articles', 'action' => 'view', $id]); + } + + /** + * Fails with an exception only the server log shows. + */ + #[McpTool(name: 'broken')] + public function broken(): string + { + throw new LogicException('The broken tool is broken on purpose.'); + } +} diff --git a/tests/test_app/src/McpExtra/GreetingTools.php b/tests/test_app/src/McpExtra/GreetingTools.php new file mode 100644 index 0000000..5daf077 --- /dev/null +++ b/tests/test_app/src/McpExtra/GreetingTools.php @@ -0,0 +1,23 @@ +greeter->greeting . ', ' . $name; + } +} diff --git a/tests/test_app/src/Middleware/AuthorizationSpyMiddleware.php b/tests/test_app/src/Middleware/AuthorizationSpyMiddleware.php new file mode 100644 index 0000000..186c6d0 --- /dev/null +++ b/tests/test_app/src/Middleware/AuthorizationSpyMiddleware.php @@ -0,0 +1,25 @@ +handle($request->withAttribute('authorization', new AuthorizationSpy())); + } +} diff --git a/tests/test_app/src/Service/Clock.php b/tests/test_app/src/Service/Clock.php new file mode 100644 index 0000000..509f7db --- /dev/null +++ b/tests/test_app/src/Service/Clock.php @@ -0,0 +1,12 @@ +|null + */ + public static function identity(?string $token): ?ArrayObject + { + return match ($token) { + self::EDITOR => new ArrayObject(['id' => 1, 'role' => 'editor', 'name' => 'Ed']), + self::ADMIN => new ArrayObject(['id' => 2, 'role' => 'admin', 'name' => 'Ada']), + default => null, + }; + } +} diff --git a/tests/test_app/webroot/index.php b/tests/test_app/webroot/index.php new file mode 100644 index 0000000..e01031a --- /dev/null +++ b/tests/test_app/webroot/index.php @@ -0,0 +1,15 @@ +emit($server->run());