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
- Prerequisites
- Creating the project
- Reading the posts: plain PHP
- Exposing the tools
- A resource for the full content
- The server.php
- Testing without AI
- Connecting it to Claude Code
- Best practices
- What about a real system?
- Conclusion
What we'll build
There are four pieces:
- Claude Code: the host, which starts the server and talks to it over
stdio. - server.php: builds the server with the official SDK and wires up the transport.
- BlogTools: the class with the tools and the resource, marked with PHP attributes.
- PostRepository: plain PHP that reads and parses the posts'
.mdfiles.
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
- PHP 8.2 or higher. Version 0.10 of the SDK requires 8.2.
- Composer.
- Claude Code installed, for the final test.
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:
- The docblock becomes the
description. That's what the model reads to decide when to use the tool, so write it with the model in mind. - The attribute's
namebecomes the tool name. Without it, the SDK uses the method name. - The parameter types become the
inputSchema.?stringbecomes["null", "string"], and a parameter without a default value becomes required. #[Schema]adds a description and constraints (minimum,maximum,minLength) to each parameter.
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()));
setServerInfo()sets the name and version the client will see.setDiscovery()looks for classes with MCP attributes insidesrc/.StdioTransportmakes the server talk over standard input and output.
Watch out for stdout. In a
stdioserver, standard output is the protocol channel. A forgottenecho,var_dump()orprint_r()mixes text into the JSON-RPC stream and breaks the communication. To debug, write toSTDERRor 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:
- Descriptions are part of the interface. The model picks a tool by its name and description. "Searches for posts containing a term in the title, description or content" works much better than "search".
- Limit response size. Everything a tool returns goes into the model's context. That's why the tools take a
limitand don't return the full content of the posts: that's what the resource is for. - Let the schema validate. With
minimum,maximumandminLength, invalid arguments are rejected before they reach your code. - Validate anything that becomes a path, query or command. That's why
find()usesbasename(). Treat arguments from the model as user input. - Start with read-only. Tools that change data should be few, well described and flagged as such (
destructiveHint). - Nothing on stdout. Worth repeating: with
stdio, logs go toSTDERR.
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:
- HTTP transport. For a server shared by the team or offered to customers, the SDK also has an HTTP transport (
StreamableHttpTransport) that runs behind your web server, with authentication. I show how in part 3. - Framework. If your application is Symfony or Laravel, there are ready-made integrations, such as
symfony/mcp-bundleandlaravel/mcp, that reuse the container and routes you already have.
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!