How to build an MCP server in PHP and use it in Claude Code

Marcos Marcolin • November 27, 2026 • 7 min read

PHP AI Open Source

In the previous post I explained what MCP (Model Context Protocol) is and how it works. Now it's time to get our hands dirty: we'll build an MCP server in PHP, from scratch, and connect it to Claude Code.

The example is real and small: a server that lets the agent query the posts on this blog. It can list posts by category, search for a term and read the full content of a post. It's around 100 lines of PHP, and most of it is code you already write every day.

Table of contents

What we'll build

MCP server in PHP flow: Claude Code talks over stdio to server.php, which discovers the tools in the BlogTools class, which uses PostRepository to read the Markdown files

There are four pieces:

The detail I like the most: only server.php and the attributes in BlogTools know MCP exists. The rest is a class you could test with PHPUnit without knowing anything about AI.

Prerequisites

We'll use mcp/sdk, the official MCP SDK for PHP, maintained by the PHP Foundation together with the Symfony team. An honest heads-up: until its first major release, the project itself considers the SDK experimental, so the API may still change between versions. This post uses 0.10.

Creating the project

mkdir mcp-blog && cd mcp-blog
composer require mcp/sdk symfony/finder

symfony/finder is used by the SDK to automatically discover classes with MCP attributes.

In composer.json, add autoloading for our classes:

{
    "require": {
        "php": "^8.2",
        "mcp/sdk": "^0.10.0",
        "symfony/finder": "^7.0 || ^8.0"
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    }
}

Then run composer dump-autoload. The final structure looks like this:

mcp-blog/
├── composer.json
├── server.php
└── src/
    ├── BlogTools.php
    └── PostRepository.php

Reading the posts: plain PHP

The posts on this blog are Markdown files with a header (front matter) like this:

---
title: "PHP corrige 7 falhas críticas: o que fazer com o 8.5.13 e o 8.4.28"
date: 2026-11-20
description: "As 17 falhas corrigidas no PHP 8.5.13, 8.4.28, ..."
categories: [php, phpsrc, opensource]
---

PostRepository reads those files and returns arrays. No MCP here:

<?php

declare(strict_types=1);

namespace App;

final class PostRepository
{
    public function __construct(private readonly string $dir)
    {
    }

    /**
     * All posts, newest first.
     */
    public function all(): array
    {
        $posts = array_map($this->parse(...), glob($this->dir . '/*.md') ?: []);
        usort($posts, fn (array $a, array $b) => strcmp($b['date'], $a['date']));

        return $posts;
    }

    public function find(string $slug): ?array
    {
        $file = $this->dir . '/' . basename($slug) . '.md';

        return is_file($file) ? $this->parse($file) : null;
    }

    private function parse(string $file): array
    {
        $raw = file_get_contents($file);
        preg_match('/^---\R(.*?)\R---\R(.*)$/s', $raw, $m);
        [$frontMatter, $content] = [$m[1] ?? '', $m[2] ?? $raw];

        $field = fn (string $name) => preg_match("/^{$name}:\s*\"?(.*?)\"?\s*$/m", $frontMatter, $v) ? $v[1] : '';
        $categories = preg_match('/^categories:\s*\[(.*)\]/m', $frontMatter, $c)
            ? array_map('trim', explode(',', $c[1]))
            : [];

        return [
            'slug' => basename($file, '.md'),
            'title' => $field('title'),
            'date' => $field('date'),
            'description' => $field('description'),
            'categories' => $categories,
            'content' => trim($content),
        ];
    }
}

Notice the basename($slug) inside find(). The slug will be sent by an AI model, so treat it like any external input: without it, a stray ../../ would read files outside the posts folder.

Exposing the tools

Now the MCP part. A tool is just a public method with the #[McpTool] attribute:

<?php

declare(strict_types=1);

namespace App;

use Mcp\Schema\ToolAnnotations;
use Mcp\Server\Capability\Attribute\McpResourceTemplate;
use Mcp\Server\Capability\Attribute\McpTool;
use Mcp\Server\Capability\Attribute\Schema;

final class BlogTools
{
    private readonly PostRepository $posts;

    public function __construct()
    {
        $this->posts = new PostRepository(getenv('BLOG_POSTS_DIR') ?: __DIR__ . '/../posts');
    }

    /**
     * Lists the latest blog posts, optionally filtered by category.
     */
    #[McpTool(name: 'list_posts', annotations: new ToolAnnotations(readOnlyHint: true))]
    public function listPosts(
        #[Schema(description: 'Category to filter by, for example "php"')]
        ?string $category = null,
        #[Schema(description: 'Maximum number of posts', minimum: 1, maximum: 50)]
        int $limit = 10,
    ): array {
        $posts = $this->posts->all();

        if ($category !== null) {
            $posts = array_filter($posts, fn (array $p) => in_array($category, $p['categories'], true));
        }

        return array_map(
            fn (array $p) => array_intersect_key($p, array_flip(['slug', 'title', 'date', 'categories'])),
            array_slice(array_values($posts), 0, $limit),
        );
    }

    /**
     * Searches for posts containing a term in the title, description or content.
     */
    #[McpTool(name: 'search_posts', annotations: new ToolAnnotations(readOnlyHint: true))]
    public function searchPosts(
        #[Schema(description: 'Term to search for', minLength: 2)]
        string $term,
        #[Schema(description: 'Maximum number of results', minimum: 1, maximum: 20)]
        int $limit = 5,
    ): array {
        $found = array_filter(
            $this->posts->all(),
            fn (array $p) => mb_stripos($p['title'] . ' ' . $p['description'] . ' ' . $p['content'], $term) !== false,
        );

        return array_map(
            fn (array $p) => array_intersect_key($p, array_flip(['slug', 'title', 'date', 'description'])),
            array_slice(array_values($found), 0, $limit),
        );
    }

    // the resource comes in the next section
}

The SDK reads the method and builds the tool definition the model receives on its own:

Mapping from PHP code to the tool definition: the docblock becomes the description, the attribute name becomes the name, and the parameter types and Schema attributes become the inputSchema

This is the schema the SDK generated for search_posts, taken from a real run:

{
  "type": "object",
  "properties": {
    "term": { "type": "string", "description": "Term to search for", "minLength": 2 },
    "limit": { "type": "integer", "default": 5, "description": "Maximum number of results", "minimum": 1, "maximum": 20 }
  },
  "required": ["term"]
}

And the return value? You return a plain PHP array and the SDK converts it to JSON, both as text and as structured content (structuredContent).

readOnlyHint: true tells the host the tool only reads data. Some hosts use that to decide when to ask the user for confirmation.

A resource for the full content

Listing and searching are actions, so they became tools. A post's content, on the other hand, is data identified by an address, so it makes more sense as a resource. Since the address changes per post, we use a resource template:

    /**
     * Full content of a post, in Markdown.
     */
    #[McpResourceTemplate(uriTemplate: 'post://{slug}', name: 'post', mimeType: 'text/markdown')]
    public function post(string $slug): string
    {
        return $this->posts->find($slug)['content']
            ?? throw new \InvalidArgumentException("Post \"{$slug}\" not found.");
    }

The {slug} in the URI becomes the method's $slug parameter. Reading post://php-86 returns the Markdown of the PHP 8.6 post.

The server.php

All that's left is building the server:

<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use Mcp\Server\Server;
use Mcp\Server\Transport\StdioTransport;

exit(Server::builder()
    ->setServerInfo('Marcolin Blog', '1.0.0')
    ->setDiscovery(__DIR__, ['src'])
    ->build()
    ->run(new StdioTransport()));

Watch out for stdout. In a stdio server, standard output is the protocol channel. A forgotten echo, var_dump() or print_r() mixes text into the JSON-RPC stream and breaks the communication. To debug, write to STDERR or to a log file.

Testing without AI

Before putting an agent in the middle, it's worth testing the server in a predictable way. The SDK itself ships an MCP client, so you can write a test script in PHP:

<?php

require __DIR__ . '/vendor/autoload.php';

use Mcp\Client\Client;
use Mcp\Client\Transport\StdioTransport;

$client = Client::builder()->setClientInfo('test', '1.0.0')->build();
$client->connect(new StdioTransport(command: 'php', args: [__DIR__ . '/server.php']));

foreach ($client->listTools()->tools as $tool) {
    echo $tool->name, PHP_EOL;
}

$result = $client->callTool('list_posts', ['category' => 'php', 'limit' => 3]);
echo $result->content[0]->text, PHP_EOL;

$client->disconnect();
BLOG_POSTS_DIR=/path/to/blog/source/_posts php client-test.php

Output:

list_posts
search_posts
[{"slug":"php-falhas-seguranca-novembro-2026","title":"PHP corrige 7 falhas críticas: o que fazer com o 8.5.13 e o 8.4.28","date":"2026-11-20","categories":["php","phpsrc","opensource"]},{"slug":"socket-io-v4-servidor-php", ...}]

If you prefer a visual interface, the MCP Inspector opens in the browser and lets you call each tool by hand:

npx @modelcontextprotocol/inspector php server.php

Connecting it to Claude Code

With the server working, register it in Claude Code. The -e option passes environment variables to the process:

claude mcp add blog \
  -e BLOG_POSTS_DIR=/path/to/blog/source/_posts \
  -- php /path/to/mcp-blog/server.php

Check it with claude mcp list or, inside a session, with /mcp. Now just ask in natural language:

Using the tools from the blog MCP server, what are the 3 most recent posts in the php category? Is there any post about TypePHP?

Claude Code's real answer, after calling list_posts and search_posts (the post titles are in Portuguese because the blog's main language is Portuguese):

The 3 most recent posts in the php category: 1. PHP corrige 7 falhas críticas: o que fazer com o 8.5.13 e o 8.4.28 (2026-11-20) 2. Socket.IO v4 em PHP: servidor novo e benchmark com Node.js (2026-11-16) 3. PHP2Shell: a falha crítica no PHP e como se proteger (2026-10-27)

Yes, there's a post about TypePHP: TypePHP, o compilador que transforma PHP em binário nativo (2026-08-27).

The first time each tool is called, Claude Code asks for your permission. That's the host doing its job, as we saw in the previous post.

Best practices

A few things I learned while building this example:

What about a real system?

The pattern is the same. Swap PostRepository for your repository, service or internal API, and the tools become things like get_customer, list_open_invoices or order_status.

Two changes usually show up when you move past the example:

Conclusion

Building an MCP server in PHP is less about AI and more about what we already know how to do: read data, validate input and return a well-structured response. The official SDK handles the protocol and PHP attributes keep the code clean.

With about 100 lines, Claude Code started answering questions about this blog using the real post data, without copying and pasting anything into the conversation.

If you have a PHP system running today, you probably already have almost everything you need to expose parts of it to AI agents.

In the next part, this same server becomes an HTTP service for the whole team, with token authentication and a tool that writes data.

See you next time, and cheers!

Share: