Documentation menu

AI

MCP server

The Model Context Protocol (MCP) lets an AI client such as a desktop app, an IDE or an agent call into your application. Taphra serves methods of your controllers as MCP tools, resources and prompts: over stdio with php taphra mcp:serve for clients that start a local process, and over Streamable HTTP for remote clients. The server is part of the bundled taphra/ai package (Taphra\Ai\Mcp); its README covers using it without the framework.

Contents

#

What the server implements

#
Area Supported
Protocol revisions 2025-11-25, 2025-06-18, 2025-03-26 and 2024-11-05, negotiated in initialize. A client asking for another revision gets 2025-11-25.
Methods initialize, ping, tools/list, tools/call, resources/list, resources/templates/list (always empty), resources/read, prompts/list, prompts/get
Lists Cursor pagination, 100 items per page by default
2025-06-18 and later Tool and resource title, tool outputSchema, structuredContent in tool results
Transports stdio (newline-delimited JSON-RPC) and Streamable HTTP (JSON responses)

The server answers requests; it never sends requests or notifications of its own. Sampling, elicitation, resource subscriptions, list-changed notifications and server-initiated SSE streams are not implemented. The stateless 2026-07-28 revision is not implemented either: its server/discover probe gets a "method not found" error, so clients that speak both revisions fall back to initialize.

Declaring tools, resources and prompts

#

A capability is a public method with one of three attributes: #[McpTool], #[McpResource] or #[McpPrompt] (namespace Taphra\Ai\Mcp). Start with the generator:

Shell
php taphra make:mcp Order

It writes app/Controllers/OrderMcpController.class.php with a placeholder tool, resource and prompt, and, the first time, the base class app/Controllers/AppMcpController.class.php:

app/Controllers/AppMcpController.class.php
<?php
namespace App\Controllers;

/**
 * Base class for this app's MCP controllers.
 *
 * Over HTTP every request is refused until you set TAPHRA_MCP_TOKEN (or
 * mcp.token in app/Config/ai.yml) or override authorizeMcp(). The stdio
 * server (php taphra mcp:serve) needs no token.
 */
abstract class AppMcpController extends \Taphra\Ai\Mcp\McpController
{
}

Both files end in .class.php, so Composer loads them through the skeleton's classmap: run composer dump-autoload before you route HTTP requests to them. mcp:serve reads the files itself and does not need it.

Fill in the controller. This one serves a tool, a resource and a prompt:

app/Controllers/OrderMcpController.class.php
<?php
namespace App\Controllers;

use Taphra\Ai\Mcp\McpPrompt;
use Taphra\Ai\Mcp\McpResource;
use Taphra\Ai\Mcp\McpTool;
use Taphra\Ai\Mcp\McpToolException;

class OrderMcpController extends AppMcpController
{
    private const ORDERS = [
        ['id' => 1, 'customer' => 'Ada', 'total' => 42.5, 'status' => 'paid'],
        ['id' => 2, 'customer' => 'Linus', 'total' => 18.0, 'status' => 'open'],
    ];

    #[McpTool(
        name: 'find_order',
        description: 'Find one order by id.',
        inputSchema: [
            'type'       => 'object',
            'properties' => ['id' => ['type' => 'integer', 'description' => 'Order id']],
            'required'   => ['id'],
        ],
        annotations: ['readOnlyHint' => true],
    )]
    public function findOrder(array $params): array
    {
        $id = (int) ($params['id'] ?? 0);
        foreach (self::ORDERS as $order) {
            if ($order['id'] === $id) {
                return $order;
            }
        }
        throw new McpToolException("No order with id $id");   // this message reaches the client
    }

    #[McpResource(uri: 'orders://open', name: 'Open orders', description: 'Orders not paid yet', mimeType: 'application/json')]
    public function openOrders(array $params): array
    {
        return array_values(array_filter(self::ORDERS, fn(array $o) => $o['status'] === 'open'));
    }

    #[McpPrompt(
        name: 'summarise_order',
        description: 'Ask for a summary of one order',
        arguments: [['name' => 'id', 'description' => 'Order id', 'required' => true]],
    )]
    public function summariseOrder(array $params): string
    {
        return 'Summarise order #' . (int) $params['id'] . ' for the support team.';
    }
}

Every method receives one array: the tool's arguments, the prompt's arguments, or ['uri' => ...] for a resource.

The attribute parameters:

Attribute Parameters
McpTool name, description, inputSchema (JSON Schema, default an empty object), title, outputSchema, annotations (hints such as readOnlyHint or destructiveHint)
McpResource uri, name, description, mimeType, title
McpPrompt name, description, arguments (a list of ['name' => ..., 'description' => ..., 'required' => bool]), title

Things to know:

  • The server does not check tool arguments against inputSchema; the schema tells the model what to send. Check and cast arguments in the method, as findOrder() does with (int). Required prompt arguments are checked: a missing one is an "invalid params" error.
  • When you set outputSchema, the method must return an associative array that matches it. The server does not check it.
  • Methods with an MCP attribute are never URL actions: a request to /orderMcp/findOrder gets a 404. They are reached through the MCP server only.
  • Tool and prompt names, and resource URIs, must be unique. When two methods use the same one, the first discovered wins and php taphra mcp:serve --list lists the duplicate it skipped.

Return values and errors

#
A tool returns The client gets
a string one text content block
an associative array or an object the JSON as a text block, and the same data as structuredContent (revision 2025-06-18 and later)
a list, a number or a boolean the JSON as a text block
null an empty result
['content' => [...], 'isError' => bool, 'structuredContent' => [...]] that result as it is

Collections and other objects are converted first: JsonSerializable, then toArray(), then iteration. A DataStoreCollection from find() can be returned as it is.

An exception thrown by a tool becomes a tool result with isError: true, so the model can read the problem and try again. Only a Taphra\Ai\Mcp\McpToolException (or an McpError) sends its message to the client: throw one for messages such as "title is required". Any other exception is logged on the server with PHP's error_log() (stderr under mcp:serve) and the client gets a generic message, so database errors, paths and other internals stay on the server. Pass an error_logger callable in the server options to log elsewhere.

A resource returns a string (sent as text with the resource's mimeType), an array (sent as JSON, application/json unless you set another type), or ['contents' => [['text' => ...], ['blob' => base64, 'mimeType' => ...]]]. A prompt returns a string (one user message), a list of messages, or ['description' => ..., 'messages' => [['role' => 'user' | 'assistant', 'content' => ...]]].

Protocol errors are JSON-RPC errors:

Code When
-32700 The message is not valid JSON
-32600 Not a valid JSON-RPC request
-32601 Unknown method
-32602 Unknown tool or prompt, a missing required prompt argument, malformed arguments, an invalid cursor
-32002 Unknown resource URI (the URI is in error.data)
-32603 A resource or prompt method threw: the message of an McpToolException, otherwise a generic message (the exception is logged)

CRUD tools from a DataStore

#

--from-datastore reads a DataStore class (no database connection needed) and writes typed tools for it:

Shell
php taphra make:mcp Post --from-datastore=PostDataStore
Text
Generated tools:
  list_posts, get_post, create_post, update_post, delete_post
Generated resource: posts://list

The input schemas come from the DataStore's $casts, $fillable and a declared $dataDefinition; created_at, updated_at and deleted_at are left out of create and update. The generated methods call find(), read(), save() and delete(), so the DataStore's mass-assignment rules apply: create_post and update_post can only set $fillable columns. list_posts caps limit at 100, and delete_post carries the destructiveHint annotation.

Every connected client can call every tool you serve. Delete the generated methods a client should not have, such as delete_post, before you connect one.

Serving over stdio

#

Check what will be served:

Shell
php taphra mcp:serve --list
Text
MCP controllers directory: /var/www/my-app/app/Controllers
Tools: 1
  find_order
Resources: 1
  Open orders  orders://open
Prompts: 1
  summarise_order

php taphra mcp:serve then reads JSON-RPC messages from stdin and writes one JSON line per response to stdout, until stdin closes. It serves every class under app/Controllers (subfolders included, .php or .class.php, namespaced or not) that has MCP methods, and every concrete McpController subclass. Only MCP messages go to stdout: anything a method prints, PHP warnings and uncaught errors go to stderr. The server name in initialize is app_name from app/Config/app.yml, unless an McpController subclass sets other options with mcpServerOptions() (see Serving over HTTP): mcp:serve uses them too, so both transports describe the server the same way.

A session from a client, one message per line (responses shortened):

Text
> {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"probe","version":"1"}}}
< {"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-11-25","capabilities":{"tools":{"listChanged":false},"resources":{"subscribe":false,"listChanged":false},"prompts":{"listChanged":false}},"serverInfo":{"name":"my-app","version":"1.1.0"}}}
> {"jsonrpc":"2.0","method":"notifications/initialized"}
> {"jsonrpc":"2.0","id":2,"method":"tools/list"}
< {"jsonrpc":"2.0","id":2,"result":{"tools":[{"name":"find_order","description":"Find one order by id.","inputSchema":{"type":"object","properties":{"id":{"type":"integer","description":"Order id"}},"required":["id"]},"annotations":{"readOnlyHint":true}}]}}
> {"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"find_order","arguments":{"id":1}}}
< {"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"{\"id\":1,\"customer\":\"Ada\",\"total\":42.5,\"status\":\"paid\"}"}],"isError":false,"structuredContent":{"id":1,"customer":"Ada","total":42.5,"status":"paid"}}}
> {"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"find_order","arguments":{"id":9}}}
< {"jsonrpc":"2.0","id":4,"result":{"content":[{"type":"text","text":"No order with id 9"}],"isError":true}}

The command boots the app like any other CLI command. With no APP_ENV set, that is production mode, with the production sections of your config files. stdio has no authentication: whoever can start the process can already read your files.

Desktop clients

#

Most desktop MCP clients take a JSON configuration with an mcpServers section. Add the server there, with the absolute path to your project's taphra script. The command works from any working directory.

JSON
{
  "mcpServers": {
    "my-app": {
      "command": "php",
      "args": ["/absolute/path/to/my-app/taphra", "mcp:serve"],
      "env": { "APP_ENV": "dev" }
    }
  }
}

Leave out env to serve with the production configuration. Other clients that start a local process take the same command and arguments.

Serving over HTTP

#

An HTTP endpoint is a controller action: McpController::handle(). Route POST, GET and DELETE on one path to it. Method sections are top-level keys of routes.yml (see routing):

YAML
# app/Config/routes.yml
POST:
  /mcp: orderMcp/handle
GET:
  /mcp: orderMcp/handle
DELETE:
  /mcp: orderMcp/handle

Several MCP controllers can share one endpoint: in the constructor of the routed one, call $this->discovery->discover(new OtherMcpController()).

Authentication

#

The endpoint refuses every request with 401 until you choose how clients authenticate. Either set a shared token of at least 32 bytes, which clients send as Authorization: Bearer <token> and which is compared in constant time (a shorter token refuses every request, and the error log says why; the mcp-server template writes one to .env at composer create-project):

Shell
export TAPHRA_MCP_TOKEN="$(php -r 'echo bin2hex(random_bytes(32));')"

or put it in app/Config/ai.yml as mcp.token (use a ${VARIABLE} placeholder, not the token itself). Or override authorizeMcp() with your own check, for example against API keys stored in a table:

PHP
// app/Controllers/OrderMcpController.class.php
protected function authorizeMcp(array $headers): bool
{
    $key = $headers['x-api-key'] ?? '';   // header names are lower case

    return $key !== '' && ApiKeyDataStore::firstWhere(['key_hash' => hash('sha256', $key)]) !== null;
}

MCP controllers extend RestController, not your AppController, so the skeleton's CSRF check does not apply to them; the token or your authorizeMcp() does that job.

What the transport checks

#
Request Answer
Not authorised 401 with WWW-Authenticate: Bearer
An Origin header that is not a loopback origin (localhost, 127.0.0.1, [::1]) or listed in mcp.allowed_origins 403. This protects a server on your machine from web pages (DNS rebinding). Requests without Origin, such as most non-browser clients, pass.
POST whose Content-Type is not the media type application/json (parameters such as charset are fine), or has none 415
POST with an Accept header that does not allow application/json 406
POST initialize 200, the result, and an Mcp-Session-Id header; 503 with Retry-After when 1000 sessions are already open
Any other POST without Mcp-Session-Id 400
An unknown or ended session 404
An MCP-Protocol-Version header that differs from the negotiated revision 400
A notification or a client response 202, no body
GET 405: the server does not open server-to-client streams
DELETE with Mcp-Session-Id 204, the session ends

Responses are always application/json, never an SSE stream. Allow browser origins in ai.yml:

YAML
# app/Config/ai.yml
mcp:
  token: "${TAPHRA_MCP_TOKEN}"
  allowed_origins: ["https://app.example.com"]

Sessions are JSON files in app/tmp/mcp_sessions, ended after an hour without a request; at most 1000 are open at a time. With several web servers behind a load balancer, override mcpSessionStore() to return a shared store (any McpSessionStoreInterface), or use sticky sessions. Override mcpServerOptions() to set the name, version, title, instructions or page_size the server reports; over HTTP the name defaults to "Taphra MCP Server". php taphra mcp:serve reports the same options (with several McpController subclasses, their options are merged in file order, a later file winning for the same key).

Testing MCP code

#

McpServer handles one JSON-RPC message in process, so a test can call a tool without a client or a transport. McpDiscovery collects the MCP methods of any object:

PHP
use App\Controllers\OrderMcpController;
use Taphra\Ai\Mcp\McpDiscovery;
use Taphra\Ai\Mcp\McpServer;

$server = new McpServer((new McpDiscovery())->discover(new OrderMcpController()));

$reply = $server->handleJson(json_encode([
    'jsonrpc' => '2.0',
    'id'      => 1,
    'method'  => 'tools/call',
    'params'  => ['name' => 'find_order', 'arguments' => ['id' => 2]],
]));

$result = json_decode($reply, true)['result'];
echo $result['structuredContent']['customer'];   // Linus

McpHttpTransport takes the method, the headers and the body and returns an McpHttpResponse (status, headers, body), so the HTTP rules can be tested the same way. McpMemorySessionStore keeps sessions in memory:

PHP
use App\Controllers\OrderMcpController;
use Taphra\Ai\Mcp\McpDiscovery;
use Taphra\Ai\Mcp\McpHttpTransport;
use Taphra\Ai\Mcp\McpMemorySessionStore;

$discovery = (new McpDiscovery())->discover(new OrderMcpController());
$json      = ['Content-Type' => 'application/json'];
$init      = json_encode(['jsonrpc' => '2.0', 'id' => 1, 'method' => 'initialize', 'params' => ['protocolVersion' => '2025-11-25']]);

// No authorize callback: every request is refused.
$closed = new McpHttpTransport($discovery, new McpMemorySessionStore());
echo $closed->handle('POST', $json, $init)->status, "\n";   // 401

$http = new McpHttpTransport($discovery, new McpMemorySessionStore(), [
    'authorize' => fn(array $headers): bool => McpHttpTransport::bearerTokenMatches($headers, 'test-token'),
]);
$auth = $json + ['Authorization' => 'Bearer test-token'];

$started = $http->handle('POST', $auth, $init);
$session = $started->header('Mcp-Session-Id');

$call = $http->handle('POST', $auth + ['Mcp-Session-Id' => $session], json_encode([
    'jsonrpc' => '2.0', 'id' => 2, 'method' => 'tools/call',
    'params'  => ['name' => 'find_order', 'arguments' => ['id' => 1]],
]));
echo $call->status, ' ', json_decode($call->body, true)['result']['structuredContent']['status'], "\n";   // 200 paid

To test the whole endpoint with routing and your authorizeMcp(), send requests through the app with HttpTestCase (see testing). On that entry McpController reads the headers and the body of the request the test sends. This test uses the /mcp routes above and a token set for the test:

PHP
<?php
// test/Http/OrderMcpTest.php
use Taphra\Testing\HttpTestCase;

class OrderMcpTest extends HttpTestCase
{
    private const TOKEN = 'test-token-0123456789abcdef0123456789abcdef';

    protected function setUp(): void
    {
        parent::setUp();
        putenv('TAPHRA_MCP_TOKEN=' . self::TOKEN);
    }

    protected function tearDown(): void
    {
        putenv('TAPHRA_MCP_TOKEN');
        parent::tearDown();
    }

    public function testFindOrder(): void
    {
        $auth = ['Authorization' => 'Bearer ' . self::TOKEN];

        $this->postJson('/mcp', ['jsonrpc' => '2.0', 'id' => 1, 'method' => 'tools/list'])
            ->assertUnauthorized();

        $started = $this->postJson('/mcp', [
            'jsonrpc' => '2.0', 'id' => 1, 'method' => 'initialize',
            'params'  => ['protocolVersion' => '2025-11-25'],
        ], $auth)->assertOk();
        $session = $auth + ['Mcp-Session-Id' => $started->getHeader('Mcp-Session-Id')];

        $this->postJson('/mcp', [
            'jsonrpc' => '2.0', 'id' => 2, 'method' => 'tools/call',
            'params'  => ['name' => 'find_order', 'arguments' => ['id' => 2]],
        ], $session)
            ->assertOk()
            ->assertJsonPath('result.structuredContent.customer', 'Linus');

        $this->delete('/mcp', [], $session)->assertStatus(204);
    }
}

Sessions are files in app/tmp/mcp_sessions here too; to keep them in memory during tests, override mcpSessionStore() in a test subclass of the controller.