This is the third part of the MCP series. In the first one I explained what the protocol is and how it works. In the second one we built an MCP server in PHP that runs on your machine, over stdio, and lets Claude Code query the posts on this blog.
That server had two limitations, on purpose: it only worked on the machine running it and it only read data. In this post we'll fix both. The same server becomes an HTTP service, with token authentication, different permissions for each person and a tool that writes data.
The good news: the classes from part 2 don't change. Everything we'll do happens around them.
Table of contents
- What changes from stdio to HTTP
- What we'll build
- Prerequisites
- The HTTP entry point
- Token authentication
- A tool that writes data
- Testing with curl
- Connecting it to Claude Code
- Going to production
- Static token or OAuth?
- Conclusion
What changes from stdio to HTTP
With stdio, Claude Code starts server.php as a child process and talks to it over standard input and output. It's simple and safe, because everything happens on your machine, but every person needs the code, the dependencies and access to the data.
With Streamable HTTP, the server lives at an address, like https://mcp.yourcompany.com, and the client sends each message as a POST. That changes three things:
- One server for the whole team. Anyone who wants to use it only needs the URL and a token.
- Authentication is no longer optional. With
stdio, whoever runs the process already has access to the machine. At an HTTP address, anyone can knock on the door. - Every request is independent. As we saw in part 1, the 2026-07-28 spec made the protocol stateless. And that fits PHP really well: each request boots, answers and dies, with no state kept in memory.
What we'll build
These are the same pieces as part 2, with three new ones:
- public/index.php: replaces
server.php. It turns the HTTP request into a PSR-7 object, hands it to the server and sends the response back. - TokenAuth: a PSR-15 middleware that checks the token before anything reaches MCP.
- IdeaTools: a new class with a tool to submit post ideas for the team to review, stored in a SQLite database. It's our write example.
BlogTools and PostRepository are copied from part 2 without changing a single line.
Prerequisites
The same as part 2 (PHP 8.2 or later, Composer and Claude Code), plus the pdo_sqlite extension, which is enabled in most PHP installs. And three packages to deal with HTTP:
composer require nyholm/psr7 nyholm/psr7-server laminas/laminas-httphandlerrunner
- nyholm/psr7: a lightweight PSR-7 implementation, the HTTP request and response interfaces the SDK uses.
- nyholm/psr7-server: builds the PSR-7 request from
$_SERVER,$_GETand friends. - laminas/laminas-httphandlerrunner: sends the PSR-7 response back to the browser (or, in this case, to Claude Code).
If you use a framework, it already has all of this. Here I stick to plain PHP to make it clear what each part does.
The final structure looks like this:
mcp-blog/
βββ composer.json
βββ tokens.php
βββ data/
β βββ ideas.sqlite
βββ public/
β βββ index.php
βββ src/
βββ BlogTools.php
βββ IdeaTools.php
βββ PostRepository.php
βββ TokenAuth.php
public/ exists for a reason: it's the only folder exposed by the web server. tokens.php, data/ and src/ stay out of reach of whoever hits the URL.
The HTTP entry point
public/index.php is the HTTP equivalent of server.php:
<?php
declare(strict_types=1);
require __DIR__ . '/../vendor/autoload.php';
use App\TokenAuth;
use Laminas\HttpHandlerRunner\Emitter\SapiEmitter;
use Mcp\Server\Server;
use Mcp\Server\Transport\Http\Middleware\CorsMiddleware;
use Mcp\Server\Transport\Http\Middleware\DnsRebindingProtectionMiddleware;
use Mcp\Server\Transport\StreamableHttpTransport;
use Nyholm\Psr7\Factory\Psr17Factory;
use Nyholm\Psr7Server\ServerRequestCreator;
$psr17 = new Psr17Factory();
$request = (new ServerRequestCreator($psr17, $psr17, $psr17, $psr17))->fromGlobals();
$hosts = explode(',', getenv('MCP_ALLOWED_HOSTS') ?: 'localhost,127.0.0.1');
$transport = new StreamableHttpTransport(
$request,
$psr17,
$psr17,
middleware: [
new CorsMiddleware(),
new DnsRebindingProtectionMiddleware(allowedHosts: $hosts),
new TokenAuth(require __DIR__ . '/../tokens.php'),
],
);
$server = Server::builder()
->setServerInfo('Blog do Marcolin', '1.0.0')
->setDiscovery(__DIR__ . '/..', ['src'])
->build();
(new SapiEmitter())->emit($server->run($transport));
Compared to part 2:
Server::builder()is identical. Tools are still discovered through the attributes insrc/.StdioTransportgave way toStreamableHttpTransport, which receives the PSR-7 request.- Over HTTP,
run()returns a PSR-7 response instead of an exit code, andSapiEmittersends it.
The middlewares run before MCP, in list order. The first two come from the SDK:
- CorsMiddleware: handles the CORS rules, in case a client runs in the browser.
- DnsRebindingProtectionMiddleware: rejects requests whose
Hostheader isn't on the list. This blocks a well-known attack where a malicious website makes the victim's browser reach a local server.
The Host gotcha. By default, the SDK only accepts
localhost,127.0.0.1and[::1]. That works on your machine, but in production every request will get 403 Forbidden: Invalid Host header. That's why the list comes from theMCP_ALLOWED_HOSTSvariable: in production, it holds your domain.
One detail: when you pass your own middleware list, it replaces the SDK's default list. That's why CorsMiddleware and DnsRebindingProtectionMiddleware are declared again there. If you pass only TokenAuth, you lose both protections without noticing.
Token authentication
TokenAuth is a plain PSR-15 middleware. It reads the Authorization: Bearer ... header, looks the token up in the list and, if it finds it, attaches to the request who owns it and what they can do:
<?php
declare(strict_types=1);
namespace App;
use Mcp\Server\Authorization\AccessToken;
use Nyholm\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
final class TokenAuth implements MiddlewareInterface
{
/**
* @param array<string, array{sub: string, scopes: list<string>}> $tokens keyed by the sha256 of the token
*/
public function __construct(private readonly array $tokens)
{
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
// A CORS preflight never carries credentials.
if ($request->getMethod() === 'OPTIONS') {
return $handler->handle($request);
}
if (!preg_match('/^Bearer\s+(\S+)$/i', $request->getHeaderLine('Authorization'), $m)) {
return new Response(401, ['WWW-Authenticate' => 'Bearer']);
}
$owner = $this->tokens[hash('sha256', $m[1])] ?? null;
if ($owner === null) {
return new Response(401, ['WWW-Authenticate' => 'Bearer error="invalid_token"']);
}
$token = new AccessToken($owner['scopes'], ['sub' => $owner['sub']]);
return $handler->handle($request->withAttribute(AccessToken::class, $token));
}
}
The key part is the last line. AccessToken is a class from the SDK itself, and StreamableHttpTransport looks for exactly that attribute on the request. If it's there, the tools can know who is calling, as we'll see in the next section.
The tokens live in tokens.php:
<?php
// Never store the token itself, only its hash. Generate a token with:
// php -r 'echo bin2hex(random_bytes(32)), PHP_EOL;'
return [
hash('sha256', 'read-token-123') => ['sub' => 'ana', 'scopes' => ['posts:read']],
hash('sha256', 'editor-token-456') => ['sub' => 'marcos', 'scopes' => ['posts:read', 'ideas:write']],
];
A few decisions worth explaining:
- One token per person, never one token shared by the team. That way you know who did what and can revoke someone's access without affecting everyone else.
- Only the hash is stored. If the file leaks, the tokens are still safe. In the example I compute the hash inline to keep it readable. In real life, you store the precomputed hash, and the token itself only exists with whoever uses it.
- Scopes say what each token can do. Ana can only read. Marcos can read and submit ideas.
Example tokens.
read-token-123is only there to keep the post readable. In production, use the command in the comment to generate random 64-character tokens.
A tool that writes data
In part 2 I left a recommendation: start with read-only, and tools that change data should be few, well described and flagged as such. Time to follow my own advice.
<?php
declare(strict_types=1);
namespace App;
use Mcp\Schema\ToolAnnotations;
use Mcp\Server\Capability\Attribute\McpTool;
use Mcp\Server\Capability\Attribute\Schema;
use Mcp\Server\Exception\ToolCallException;
use Mcp\Server\RequestContext;
final class IdeaTools
{
private readonly \PDO $db;
public function __construct()
{
$this->db = new \PDO('sqlite:' . (getenv('IDEAS_DB') ?: __DIR__ . '/../data/ideas.sqlite'));
$this->db->exec('CREATE TABLE IF NOT EXISTS ideas (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
summary TEXT NOT NULL,
author TEXT NOT NULL,
created_at TEXT NOT NULL
)');
}
/**
* Lists the post ideas the team has already submitted, newest first.
*/
#[McpTool(name: 'list_ideas', annotations: new ToolAnnotations(readOnlyHint: true))]
public function listIdeas(): array
{
return $this->db->query('SELECT * FROM ideas ORDER BY id DESC')->fetchAll(\PDO::FETCH_ASSOC);
}
/**
* Submits a new post idea for the team to review. It does not publish anything on the blog.
*/
#[McpTool(
name: 'add_idea',
annotations: new ToolAnnotations(readOnlyHint: false, destructiveHint: false, idempotentHint: false),
)]
public function addIdea(
RequestContext $context,
#[Schema(description: 'Working title for the post', minLength: 5, maxLength: 120)]
string $title,
#[Schema(description: 'What the post should cover, in a few sentences', minLength: 20, maxLength: 1000)]
string $summary,
): array {
$token = $context->getAccessToken();
if ($token === null || !$token->hasScope('ideas:write')) {
throw new ToolCallException('This token is read-only. Ask for a token with the ideas:write scope.');
}
$idea = [
'title' => $title,
'summary' => $summary,
'author' => $token->getSubject(),
'created_at' => date(DATE_ATOM),
];
$this->db
->prepare('INSERT INTO ideas (title, summary, author, created_at) VALUES (:title, :summary, :author, :created_at)')
->execute($idea);
return ['id' => (int) $this->db->lastInsertId()] + $idea;
}
}
What's new here:
RequestContext $context. When a tool declares a parameter of this type, the SDK injects the request context. It doesn't show up in the schema the model receives: the model still only seestitleandsummary. The context is how we get theAccessTokenthatTokenAuthattached.- Prepared statements, always. The title and summary are written by the model, which may have read anything before. With
prepare()and named parameters, a title like'); DROP TABLE ideas; --is just text. I tested it. - The author comes from the token, not from the model.
getSubject()returns the token'ssub. Ifauthorwere a tool parameter, the model could fill in any name. Anything that identifies the caller must come from authentication, never from the arguments. ToolCallExceptionfor errors the model should read. A regular exception becomes a generic error.ToolCallExceptionbecomes a response withisError: trueand your message, which the model reads and passes on to the user. That's why the message says what to do, not just what went wrong.- The annotations tell the truth.
readOnlyHint: falsesays the tool changes data.destructiveHint: falsesays it only adds, without deleting or overwriting anything.idempotentHint: falsewarns that calling it twice creates two ideas. Some hosts use this information to decide when to ask for confirmation. - The description makes the boundary clear. "It does not publish anything on the blog" keeps the model from thinking that submitting an idea is the same as publishing a post.
Permissions can be checked in two places, and each one answers differently:
Host and token stop the request at the edge, with an HTTP status, before any MCP code runs. The scope is checked inside the tool, and the error goes back to the model as a response it can explain. Note that the read-only token still sees add_idea in the tool list. It just can't run it.
Why SQLite? Because there's nothing to install and the database is a file, created on the first call by
CREATE TABLE IF NOT EXISTS. In a real system, the table would come from a migration and the DSN would point to your MySQL or PostgreSQL. The rest of the class stays the same.
Testing with curl
In part 2 we tested with the SDK's PHP client. Now that the server speaks HTTP, we can test with curl. For development, PHP's built-in server does the job:
BLOG_POSTS_DIR=/path/to/blog/source/_posts_en php -S localhost:8000 public/index.php
Without a token, the request stops before MCP:
curl -i -X POST http://localhost:8000/ \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer
With the read-only token, trying to submit an idea:
curl -X POST http://localhost:8000/ \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-H 'Authorization: Bearer read-token-123' \
-d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"add_idea","arguments":{"title":"MCP with Laravel","summary":"How to use laravel/mcp to expose tools from a Laravel app."}}}'
{"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"This token is read-only. Ask for a token with the ideas:write scope."}],"isError":true}}
And with a Host that isn't on the list:
curl -i -X POST http://localhost:8000/ -H 'Host: evil.example.com' ...
HTTP/1.1 403 Forbidden
Forbidden: Invalid Host header.
About protocol versions. These
curlcalls use the simplest format, which the SDK accepts for clients on earlier revisions of the spec. In the 2026-07-28 revision, each request also carries the client's version and capabilities, in headers and in the_metafield. You don't need to build any of that: the SDK and Claude Code take care of these details. If you prefer a visual interface, the MCP Inspector also works with HTTP servers.
Connecting it to Claude Code
For an HTTP server, you pass the URL and the authentication header:
claude mcp add --transport http blog http://localhost:8000/ \
--header "Authorization: Bearer editor-token-456"
If the server belongs to the team, it makes sense to version the config in a .mcp.json at the project root, as I mentioned in part 1. But the token must not go into the repository. Claude Code expands environment variables in that file, so each person uses their own token:
{
"mcpServers": {
"blog": {
"type": "http",
"url": "https://mcp.yourcompany.com/",
"headers": {
"Authorization": "Bearer ${MCP_BLOG_TOKEN}"
}
}
}
}
I tested it with Marcos's token, which can submit ideas:
Using the tools from the blog MCP server: is there any post about MCP? If there isn't one about MCP with Laravel, submit an idea for it with a short summary.
Real answer from Claude Code, after calling search_posts and add_idea:
Yes. The blog has three posts about MCP:
- What is MCP (Model Context Protocol) and how does it work? (2026-11-27)
- How to build an MCP server in PHP and use it in Claude Code (2026-11-27)
- Remote MCP server in PHP: HTTP, authentication and tools that write data (2026-12-01)
The two PHP posts use the official PHP SDK (
mcp/sdk). A search for "Laravel" returns both of them, but neither has Laravel in its title or description, so there's no post about MCP with Laravel. I submitted an idea (#1), "Building an MCP server with Laravel". Its summary covers the official Laravel MCP package, tools and resources that use Eloquent models, securing the endpoint with Sanctum, testing, and connecting to Claude Code.
Yes, it found this very post. The tests ran against the blog's posts folder with part 3 already in it.
And in the database, the author came from the token:
sqlite3 -header -column data/ideas.sqlite 'SELECT id, title, author, created_at FROM ideas'
id title author created_at
-- ----------------------------------- ------ -------------------------
1 Building an MCP server with Laravel marcos 2026-12-01T12:24:00+00:00
Now with Ana's token, which can only read, asking for an idea about MCP with Symfony:
I couldn't submit the "Building an MCP Server with Symfony" idea because the blog MCP server's token is read-only. You'll need a token with the
ideas:writescope to add ideas.
That's the ToolCallException message reaching the user, explained by the model.
Going to production
php -S is for development only. To put the server online:
- Always HTTPS. The token travels in a header. Without TLS, anyone along the way can read it.
- Point the web server at
public/. With Nginx and PHP-FPM, Apache or FrankenPHP, every request to the endpoint goes topublic/index.php, just like a regular PHP application. - Set
MCP_ALLOWED_HOSTSto your domain, likemcp.yourcompany.com. Without it, the server answers 403 to everything. - Cache discovery. Right now the SDK scans
src/on every request to find the attributes. With few classes that's fast, butsetDiscovery()accepts a PSR-16 cache through thecacheparameter, and it's worth using in production. - Rate limiting. An agent stuck in a loop can call the same tool hundreds of times. A rate limit in Nginx or at the proxy, per token or per IP, avoids surprises.
- The
data/folder must be writable by the user running PHP (www-data, with Nginx and PHP-FPM). It's the most common error when moving away fromphp -S. - Logs with the author. Log who called which tool, with the token's
sub. When a weird idea shows up, you'll want to know where it came from.
And there's a free bonus: since the server keeps no session, it scales like any PHP application. You can put several instances behind a load balancer with no shared session and no sticky sessions. Only the data needs to live somewhere shared: with SQLite, each instance would have its own file, so in that scenario the database has to be a shared MySQL or PostgreSQL.
Static token or OAuth?
A static token, like in this post, works well for internal tools: a small team, tokens handed out manually and revoked when someone leaves.
When the server is for customers, or when you want each person to sign in with the account they already have, the way to go is OAuth. The MCP spec defines this flow, and the SDK already ships the pieces: AuthorizationMiddleware validates JWT tokens issued by your authorization server (Keycloak, Auth0, your application's login) with JwtTokenValidator, and publishes the metadata the client uses to find out where to sign in. In Claude Code, the person authenticates in the browser, starting from the /mcp command.
The best part is that the tools don't change. They keep reading the AccessToken through RequestContext, with getSubject() and hasScope(). The only thing that changes is who issues the token.
Conclusion
In part 2, the MCP server was a script on your machine. Now it's an HTTP service the whole team uses, with one token per person, scope-based permissions and a tool that writes to the database without letting the model decide who the author is.
And, once again, almost none of this is about AI. Middleware, token hashing, scopes, prepared statements, HTTPS, rate limiting: it's what we already do to protect any API. The SDK handles the protocol, and the rest is PHP you already know.
If you just got here, the full series is:
- What is MCP and how does it work
- How to build an MCP server in PHP
- Remote MCP server in PHP (this post)
See you next time, and cheers!