atellitech / mcp-hyperf
Streamable HTTP MCP server (tools, prompts and resources) that plugs into an existing Hyperf HTTP route.
Requires
- php: >=8.3
- hyperf/contract: ^3.1
- hyperf/http-server: ^3.1
- psr/container: ^1.0 || ^2.0
- psr/http-message: ^1.0 || ^2.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.0
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^11
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-12-03 08:31:43 UTC
README
A stateless MCP server that serves tools, prompts and resources and uses the Streamable HTTP transport. Mount it on a route in your existing Hyperf HTTP server: it doesn't start its own server, open SSE streams or keep sessions.
POSThandles JSON-RPC:tools/list,tools/call,prompts/list,prompts/get,resources/list,resources/templates/listandresources/read, plus the version-specific methods below. Notifications get202.- The
toolscapability is always advertised.promptsandresourcesare advertised only when you register at least one. List changes and resource subscriptions aren't supported. GETandDELETEreturn405. APOSTwhoseAcceptheader lacksapplication/jsonortext/event-streamgets406. Answers are always JSON, never an SSE stream.- If the request has an
Originheader, it must be inallowed_origins. Otherwise the server returns403. Requests withoutOrigin(non-browser clients) are accepted. Withoutallowed_origins, theOriginhost only has to match theHostheader, which doesn't stop DNS rebinding: see Allowed origins. - Supported protocol versions:
2026-07-28,2025-11-25and2025-06-18, on the same endpoint.
Contents
- Protocol versions
- Requirements
- Install
- Write a tool
- Write a prompt
- Write a resource
- Register them
- Mount the route
Protocol versions
The server picks the version for each request on its own. A request is treated as 2026-07-28 when its params._meta contains io.modelcontextprotocol/protocolVersion, its method is server/discover, or its MCP-Protocol-Version header is 2026-07-28. Every other request uses the version initialize negotiated: the one the client asks for when it is 2025-11-25 or 2025-06-18, else 2025-11-25. These two behave the same here; none of the optional 2025-11-25 additions (tasks, icons, URL elicitation, sampling with tools) is implemented.
2025-11-25, 2025-06-18 |
2026-07-28 |
|
|---|---|---|
| Handshake | initialize |
none; server/discover is available |
ping |
yes | no (-32601) |
| Required per request | — | _meta with io.modelcontextprotocol/protocolVersion and io.modelcontextprotocol/clientCapabilities (else 400, -32602) |
| Header checks | MCP-Protocol-Version, if sent, must be supported |
MCP-Protocol-Version, Mcp-Method and Mcp-Name must match the body (else 400, -32020) |
| Unsupported version | 400 |
400, -32022 with data.supported / data.requested |
| Results | as before | also resultType: "complete" and _meta["io.modelcontextprotocol/serverInfo"] |
| Resource not found | -32002 |
-32602 with data.uri. A McpException::resourceNotFound() you throw is converted. |
| Unknown method | HTTP 200, -32601 |
HTTP 404, -32601 |
On 2026-07-28, results from server/discover, the */list methods and resources/read carry the caching hints ttlMs and cacheScope. Set them with cache_ttl_ms (default 0) and cache_scope (private by default, or public) in the config. Keep private if what a user sees depends on $context.
Authentication is up to your app. Run your normal auth middleware on the route, then pass the authenticated user to handle() as $context. Every tool, prompt and resource receives that value.
Requirements
- PHP >= 8.3
- Hyperf >= 3.1
- An MCP client that speaks protocol version
2025-06-18,2025-11-25or2026-07-28over Streamable HTTP
Install
Install the package:
composer require atellitech/mcp-hyperf
Publish the config file to config/autoload/mcp.php:
php bin/hyperf.php vendor:publish atellitech/mcp-hyperf
Write a tool
use AtelliTech\Hyperf\Mcp\McpTool; use AtelliTech\Hyperf\Mcp\Schema; use AtelliTech\Hyperf\Mcp\ToolException; final class ListThingsTool implements McpTool { public function name(): string { return 'list_things'; } public function description(): string { return 'List things of the current user.'; } public function inputSchema(): array { return Schema::object([ 'page' => ['type' => 'integer', 'minimum' => 1], ]); } public function call(array $arguments, mixed $context): mixed { // $context is whatever you passed to McpServer::handle(), e.g. the user if (($arguments['page'] ?? 1) > 100) { throw new ToolException('page too large'); // becomes an isError result } return ['items' => []]; // non-string results are JSON encoded } }
$arguments is the JSON object decoded to PHP arrays, so a numeric key such as "0" arrives as the integer 0, and a nested object whose keys are "0", "1", … looks like a list. The same holds for prompt arguments. Since v1.1.0 such objects are accepted; before, they were refused as invalid params.
Structured results
Return ToolResult::structured($data) to also send the result as structuredContent, a JSON object the client can read without parsing text. The same data goes in content as JSON text, for clients that only read that.
use AtelliTech\Hyperf\Mcp\ToolResult; public function call(array $arguments, mixed $context): mixed { return ToolResult::structured(['_data' => $rows, '_meta' => ['totalCount' => $total]]); }
$data must be an associative array, because structuredContent must be an object. A list, including a map whose keys are exactly 0..n-1, throws InvalidArgumentException: wrap it (['_data' => $rows]). A top-level [] is sent as {}, but an empty map inside it stays [] unless you pass new stdClass().
The response carries the data twice (content and structuredContent), as the spec recommends for older clients, so it is about twice the size of a text-only result. Plain strings and arrays are sent as text only, as before.
Tool annotations
Implement McpToolAnnotations as well to send tool annotations in tools/list. Clients use them to decide whether to ask the user before a call. A tool without annotations is taken to be the riskiest kind (readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true), so the annotation that changes most is readOnlyHint: true on every tool that only reads.
use AtelliTech\Hyperf\Mcp\McpTool; use AtelliTech\Hyperf\Mcp\McpToolAnnotations; final class ListThingsTool implements McpTool, McpToolAnnotations { // name(), description(), inputSchema(), call() as above public function annotations(): array { return ['readOnlyHint' => true, 'openWorldHint' => false]; } }
Annotations are hints, not permissions: check access in the tool itself. They are checked when the server is built: a list, a non-boolean *Hint or a non-string title throws InvalidArgumentException. A tool that doesn't implement the interface, or returns [], is listed without annotations.
Write a prompt
A prompt is a message template the user picks in the client. Argument values are always strings. If a required argument is missing, the server returns Invalid params and doesn't call get().
use AtelliTech\Hyperf\Mcp\McpPrompt; use AtelliTech\Hyperf\Mcp\PromptArgument; use AtelliTech\Hyperf\Mcp\PromptMessage; final class ReviewThingPrompt implements McpPrompt { public function name(): string { return 'review_thing'; } public function description(): string { return 'Review one thing and suggest fixes.'; } public function arguments(): array { return [ PromptArgument::make('id', 'ID of the thing', required: true), PromptArgument::make('tone', 'friendly or strict'), ]; } public function get(array $arguments, mixed $context): array|string { // a string becomes a single user text message return [ PromptMessage::user("Review thing {$arguments['id']}."), PromptMessage::resource('user', "app://things/{$arguments['id']}", '{"name":"…"}', 'application/json'), ]; } }
Write a resource
Use McpResource for a resource with a fixed URI:
use AtelliTech\Hyperf\Mcp\McpResource; use AtelliTech\Hyperf\Mcp\ResourceContents; final class LimitsResource implements McpResource { public function uri(): string { return 'app://limits'; } public function name(): string { return 'Limits'; } public function description(): string { return 'Quota limits of the current user.'; } public function mimeType(): string { return 'application/json'; } public function read(mixed $context): array|ResourceContents|string { return json_encode(['max_things' => 100]); // or ResourceContents::blob($bytes, 'image/png') } }
Use McpResourceTemplate for a family of resources. {var} matches one path segment and is URL-decoded once (don't decode it again): the decoded value is never empty and never contains / or \, and a {var} that fills a whole segment is never . or ... A URI that breaks this doesn't match, so app://files/..%2Fsecret skips app://files/{name} and the next template is tried. {+var} matches anything, including /, %2F and .., so check it yourself before using it as a path. Return null from read() when the resource doesn't exist, and the client gets a Resource not found error: -32002 on 2025-11-25 and 2025-06-18, -32602 on 2026-07-28.
use AtelliTech\Hyperf\Mcp\McpException; use AtelliTech\Hyperf\Mcp\McpResourceTemplate; use AtelliTech\Hyperf\Mcp\ResourceContents; final class ThingResource implements McpResourceTemplate { public function uriTemplate(): string { return 'app://things/{id}'; } public function name(): string { return 'Thing'; } public function description(): string { return 'One thing of the current user.'; } public function mimeType(): string { return 'application/json'; } public function read(string $uri, array $variables, mixed $context): array|ResourceContents|string|null { if (! ctype_digit($variables['id'])) { throw McpException::invalidParams('id must be numeric'); // becomes a JSON-RPC error } return null; // not found } }
Fixed URIs are matched first. Templates are tried in the order you register them.
Prompts and resources report errors as JSON-RPC errors, so throw McpException from them. Tools throw ToolException, which the model reads as an isError result. A tool result that can't be sent as JSON (invalid UTF-8, NAN, INF) also becomes an isError result, Tool result could not be encoded as JSON., instead of failing the request. Invalid UTF-8 in a ToolException message is replaced with U+FFFD. An exception your own jsonSerialize() throws still reaches your exception handler. A name the server doesn't have gets -32602 with Unknown tool: <name> or Unknown prompt: <name>, so the model reads it as missing, not as bad arguments.
Register them
Register everything in config/autoload/mcp.php. The classes are resolved from the container.
// config/autoload/mcp.php return [ 'name' => 'My API', 'version' => '1.0.0', 'instructions' => 'What the tools are for…', 'tools' => [ListThingsTool::class], 'prompts' => [ReviewThingPrompt::class], 'resources' => [LimitsResource::class, ThingResource::class], // McpResource or McpResourceTemplate 'max_body_size' => 20971520, // bytes; a bigger POST body gets 400 (-32700) 'cache_ttl_ms' => 0, // 2026-07-28 caching hint 'cache_scope' => 'private', // or 'public' if results don't depend on the user 'allowed_origins' => ['https://app.example.com'], // browser origins allowed to call the server ];
max_body_size limits what the server parses, not what it holds in memory: by the time handle() runs, the HTTP server has already read the whole body. Swoole's package_max_length (2 MiB by default) is what limits that, so set it at least as high as max_body_size.
Allowed origins
Set allowed_origins to the exact origins (scheme://host[:port]) of the web pages that may call the server, such as http://localhost:6274 for the MCP Inspector. A request whose Origin isn't in the list gets 403. Scheme, host and port must all match, case-insensitively (a default port such as :443 is dropped from the list). An entry that isn't scheme://host[:port], such as * or a URL with a path, throws InvalidArgumentException when the server is built. An empty list refuses every browser request. Requests without Origin are always accepted.
allowed_origins only decides between 403 and handling the request. A browser on another origin also needs CORS: its preflight OPTIONS gets 405 here, so answer it, and add the Access-Control-Allow-* headers, in a middleware in front of the route.
If you leave it out (or set it to null), the server only checks that the Origin host matches the Host header, as in v1.0.0. That check ignores ports and trusts Host, which the caller controls: a page at http://evil.test:9501 that rebinds evil.test to 127.0.0.1 passes it, and so does a page on another port of localhost. Set allowed_origins, especially when the server is reachable from a browser on localhost or a private network.
Mount the route
// MCP Controller use AtelliTech\Hyperf\Mcp\Hyperf\HttpResponder; use AtelliTech\Hyperf\Mcp\McpRequest; use AtelliTech\Hyperf\Mcp\McpServer; public function handle(McpServer $server, HttpResponder $responder): ResponseInterface { return $responder->respond( $server->handle(McpRequest::fromPsr($this->request), $this->currentUser()) ); }
// Routes Router::addRoute(['GET', 'POST', 'DELETE'], '/mcp', 'App\Controller\McpController@handle', [ 'middleware' => [YourAuthMiddleware::class], ]);
You can use the core (McpServer, McpRequest, McpResponse and the McpTool, McpPrompt, McpResource and McpResourceTemplate interfaces) without Hyperf. Construct McpServer yourself and turn the McpResponse into whatever response type your framework uses.
Changelog
See CHANGELOG.md, including what changes when you upgrade from v1.0.0.