Remote MCP server in PHP: HTTP, authentication and tools that write data

Marcos Marcolin β€’ December 1, 2026 β€’ 12 min read

PHP AI Open Source

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

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:

What we'll build

Flow of the remote MCP server in PHP: Claude Code sends a POST over HTTPS with a Bearer token, which goes through the CORS, Host and TokenAuth middlewares, reaches public/index.php with the StreamableHttpTransport and is dispatched to the BlogTools and IdeaTools classes, which read the posts and store the ideas

These are the same pieces as part 2, with three new ones:

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

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:

The middlewares run before MCP, in list order. The first two come from the SDK:

The Host gotcha. By default, the SDK only accepts localhost, 127.0.0.1 and [::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 the MCP_ALLOWED_HOSTS variable: 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:

Example tokens. read-token-123 is 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:

Permissions can be checked in two places, and each one answers differently:

The path of a request to the tool: the Host is checked by DnsRebindingProtection and returns 403 if not allowed; the token is checked by TokenAuth and returns 401 if missing or invalid; the scope is checked in the tool with hasScope and returns isError if not permitted; if everything passes, the tool returns the result

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 curl calls 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 _meta field. 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:write scope 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:

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:

  1. What is MCP and how does it work
  2. How to build an MCP server in PHP
  3. Remote MCP server in PHP (this post)

See you next time, and cheers!

Share: