Documentation menu

Tutorials

Tutorial 4: MCP Server

Give desktop AI apps, IDEs and other MCP clients access to your app through the Model Context Protocol: tools they can call, a resource they can read and a prompt they can use, all backed by a small notes table.

What you will build

#
  • add_note, list_notes and get_note tools
  • a notes://recent resource with the newest notes
  • a summarise_note prompt
  • the stdio transport (php taphra mcp:serve), which desktop clients start as a process, and the HTTP transport (POST /mcp), protected by a token

For a ready-made app with all of this, start from the starter instead: composer create-project taphra/mcp-server my-app.

Prerequisites

#
  • PHP 8.2 or later, with the pdo_sqlite extension (php -m lists your extensions)
  • Composer

Step 1: Create the app

#
Shell
composer create-project taphra/skeleton my-app
cd my-app

The skeleton's app/Config/databases.yml has a SQLite connection, app_master, on the file app/Database/app.sqlite.

Step 2: The notes table

#

A migration is a file in app/Migrations/ named migration_<id>_<Description>.php, with a class named Migrate_migration_<id>_<Description>. (php taphra make:migration create notes table writes one with the current time as the id.) Create app/Migrations/migration_20261201000000_CreateNotesTable.php:

PHP
<?php

use Taphra\DatabaseConnection;
use Taphra\SchemaBuilder;

class Migrate_migration_20261201000000_CreateNotesTable
{
    public function up(array $args): void
    {
        (new SchemaBuilder(DatabaseConnection::load('app_master')))->create('notes', function ($t) {
            $t->id();
            $t->string('title');
            $t->text('body');
            $t->timestamps();
        });
    }

    public function down(array $args): void
    {
        (new SchemaBuilder(DatabaseConnection::load('app_master')))->dropIfExists('notes');
    }
}

Run it:

Shell
php taphra migrate
Text
1 up migration(s) performed.

A DataStore reads and writes the table. Create app/DataStores/NoteDataStore.php:

PHP
<?php
namespace App\DataStores;

class NoteDataStore extends AppDataStore
{
    use \Taphra\Traits\Timestamps;

    public $objectName = 'notes';
    protected $fillable = ['title', 'body'];
}

Step 3: The MCP controller

#

An MCP controller extends Taphra\Ai\Mcp\McpController. Its methods with an #[McpTool], #[McpResource] or #[McpPrompt] attribute are what the server offers; each takes the client's arguments as an array. Create app/Controllers/NotesMcpController.php:

PHP
<?php
namespace App\Controllers;

use App\DataStores\NoteDataStore;
use Taphra\Ai\Mcp\McpController;
use Taphra\Ai\Mcp\McpPrompt;
use Taphra\Ai\Mcp\McpResource;
use Taphra\Ai\Mcp\McpTool;
use Taphra\Ai\Mcp\McpToolException;

class NotesMcpController extends McpController
{
    #[McpTool(
        name: 'add_note',
        description: 'Save a note. Returns the new note.',
        inputSchema: [
            'type'       => 'object',
            'properties' => [
                'title' => ['type' => 'string', 'description' => 'A short title'],
                'body'  => ['type' => 'string', 'description' => 'The text of the note'],
            ],
            'required' => ['title', 'body'],
        ]
    )]
    public function addNote(array $params): array
    {
        $v = \Taphra\Validator::make($params, ['title' => 'required|max:255', 'body' => 'required']);
        if ($v->validate()->fails()) {
            throw new McpToolException('Invalid note: ' . json_encode($v->errors()));
        }
        return NoteDataStore::create([
            'title' => (string) $params['title'],
            'body'  => (string) $params['body'],
        ])->toArray();
    }

    #[McpTool(
        name: 'list_notes',
        description: 'The newest notes, newest first.',
        inputSchema: [
            'type'       => 'object',
            'properties' => [
                'limit' => ['type' => 'integer', 'description' => 'How many (1 to 50, default 10)'],
            ],
        ]
    )]
    public function listNotes(array $params): array
    {
        $limit = max(1, min(50, (int) ($params['limit'] ?? 10)));
        return (new NoteDataStore())->find([], $limit, 0, 'id', 'DESC')->toArray();
    }

    #[McpTool(
        name: 'get_note',
        description: 'One note by its ID.',
        inputSchema: [
            'type'       => 'object',
            'properties' => ['id' => ['type' => 'integer', 'description' => 'Note ID']],
            'required'   => ['id'],
        ]
    )]
    public function getNote(array $params): array
    {
        $note = NoteDataStore::findById((int) ($params['id'] ?? 0));
        if ($note === null) {
            throw new McpToolException('No note with ID ' . (int) ($params['id'] ?? 0));
        }
        return $note->toArray();
    }

    #[McpResource(uri: 'notes://recent', name: 'Recent notes', description: 'The 10 newest notes as JSON.', mimeType: 'application/json')]
    public function recentNotes(array $params): array
    {
        $notes = (new NoteDataStore())->find([], 10, 0, 'id', 'DESC')->toArray();
        return ['contents' => [['text' => json_encode($notes)]]];
    }

    #[McpPrompt(
        name: 'summarise_note',
        description: 'Ask the model to summarise one note.',
        arguments: [['name' => 'id', 'description' => 'Note ID', 'required' => true]]
    )]
    public function summariseNote(array $params): array
    {
        $note = $this->getNote($params);
        return ['messages' => [[
            'role'    => 'user',
            'content' => ['type' => 'text', 'text' => "Summarise this note in one sentence.\n\n{$note['title']}\n\n{$note['body']}"],
        ]]];
    }
}

A tool that throws McpToolException sends its message back to the client as a tool error (isError: true), so the model can correct itself. Any other exception is logged on the server (stderr under mcp:serve) and the client gets a generic message, so database errors and paths stay on the server. Methods with an MCP attribute are never reachable as URL actions.

Step 4: The stdio server

#

php taphra mcp:serve finds every MCP controller in app/Controllers/ by itself. See what it offers:

Shell
php taphra mcp:serve --list
Text
MCP controllers directory: .../my-app/app/Controllers
Tools: 3
  add_note
  list_notes
  get_note
Resources: 1
  Recent notes  notes://recent
Prompts: 1
  summarise_note

The server reads one JSON-RPC message per line on standard input and answers on standard output. Try a short session by hand:

Shell
printf '%s\n' \
  '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"shell","version":"1"}}}' \
  '{"jsonrpc":"2.0","method":"notifications/initialized"}' \
  '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"add_note","arguments":{"title":"Groceries","body":"Milk, eggs, bread"}}}' \
  '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"get_note","arguments":{"id":42}}}' \
  '{"jsonrpc":"2.0","id":4,"method":"prompts/get","params":{"name":"summarise_note","arguments":{"id":"1"}}}' \
  | php taphra mcp:serve
Text
{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-06-18","capabilities":{"tools":{"listChanged":false},"resources":{"subscribe":false,"listChanged":false},"prompts":{"listChanged":false}},"serverInfo":{"name":"skeleton","version":"1.1.0"}}}
{"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"{\"id\":1,\"title\":\"Groceries\",\"body\":\"Milk, eggs, bread\",\"created_at\":\"...\",\"updated_at\":\"...\"}"}],"isError":false,"structuredContent":{"id":1,"title":"Groceries","body":"Milk, eggs, bread","created_at":"...","updated_at":"..."}}}
{"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"No note with ID 42"}],"isError":true}}
{"jsonrpc":"2.0","id":4,"result":{"description":"Ask the model to summarise one note.","messages":[{"role":"user","content":{"type":"text","text":"Summarise this note in one sentence.\n\nGroceries\n\nMilk, eggs, bread"}}]}}

The notification (no id) gets no answer. The server's name is app_name from app/Config/app.yml.

Step 5: Connect a desktop client

#

Most desktop MCP clients read a JSON configuration file with an mcpServers section (see your client's documentation for where it lives). Add the server there, with the absolute path of your project, then restart the client:

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

The command works from any working directory. Over stdio no token is needed: only the process that started the server talks to it.

Step 6: The HTTP transport

#

For clients on other machines, McpController::handle() serves MCP over HTTP (Streamable HTTP). Route POST, GET and DELETE on one path to it. Replace app/Config/routes.yml with:

YAML
GET:
  /health: health/index
  /mcp: notesMcp/handle

POST:
  /mcp: notesMcp/handle

DELETE:
  /mcp: notesMcp/handle

The HTTP endpoint refuses every request until you set a token of at least 32 bytes. Write a random one to .env (app/bootstrap.php reads it on every request), then start the server:

Shell
echo "TAPHRA_MCP_TOKEN=$(php -r 'echo bin2hex(random_bytes(32));')" >> .env
php taphra serve

In a second terminal, from the project folder, a client starts a session with initialize, sending the token as a bearer token (the commands read it back from .env):

Shell
curl -s -i -X POST http://127.0.0.1:8000/mcp \
  -H "Authorization: Bearer $(sed -n 's/^TAPHRA_MCP_TOKEN=//p' .env)" \
  -H 'Content-Type: application/json' \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"curl","version":"1"}}}' \
  | grep -iE '^(HTTP/|content-type|mcp-session-id)'
Text
HTTP/1.1 200 OK
Content-Type: application/json
Mcp-Session-Id: ...

Later requests send the Mcp-Session-Id header back, with MCP-Protocol-Version: 2025-06-18; DELETE /mcp with that header ends the session. Without the token the endpoint answers 401:

Shell
curl -s -o /dev/null -w '%{http_code}\n' -X POST http://127.0.0.1:8000/mcp \
  -H 'Content-Type: application/json' \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}'
Text
401

GET answers 405: this server opens no stream of its own.

Shell
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8000/mcp \
  -H "Authorization: Bearer $(sed -n 's/^TAPHRA_MCP_TOKEN=//p' .env)"
Text
405

A request with an Origin header (a web page) gets a 403 unless the origin is a localhost address or is listed under mcp.allowed_origins in app/Config/ai.yml. To use your own authentication instead of the token, override authorizeMcp(array $headers): bool in the controller.

Supported methods

#
Method What it does
initialize handshake: protocol version, capabilities, server name
tools/list, tools/call the #[McpTool] methods
resources/list, resources/read the #[McpResource] methods
prompts/list, prompts/get the #[McpPrompt] methods

Next steps

#
  • Tools for your own agent instead of an MCP client: Tutorial 5: Agent with tools
  • The taphra/mcp-server starter: the same pieces on a posts table, with a health route and Docker files.