MCP Server
Mark a method with #[MCPTool] and the build lists it as a tool of a
Model Context Protocol
server, so an assistant like Claude can call it with the parameters it describes.
Declaring a tool
A tool is a static method that returns a Response, marked with the attribute that gives it the
Access it needs. The description the assistant reads to decide when to use it is the text of its doc
comment before the tags, which can take several lines, and the description of the attribute replaces
it, and the build skips a tool that has neither. Its name comes from
the class, without the MCP at its end, and the method, both in snake case, so
TaskMCP::getProjects is task_get_projects, and the name of the attribute
gives another one. A name can only have letters, numbers, _ and -, up to 64 characters,
and the build skips a tool whose name is not valid or is already taken. Its arguments are taken in one of two
ways.
With the Request of a Model
A tool that takes one of the Schema requests, like a route, has the inputs of
that Request as its arguments. The build writes them in the getInputSchema() of each Request, with the
name each one is sent with, like taskID for the ID, and its type: an enum is a string with its cases
and a date is a string in the date format. None of them is required, so the description says which ones the tool
uses:
use Framework\IO\Response;
use Framework\MCP\Attr\MCPTool;
use Framework\System\Access;
class TaskMCP {
/**
* Searches the Tasks of a Project, by taskProjectID
* @param TaskRequest $request
* @return Response
*/
#[MCPTool(Access::API)]
public static function search(TaskRequest $request): Response {
return Response::data([ "list" => Task::getFiltered($request) ]);
}
}A tool whose method starts with list or search also has the inputs that every Request
takes to sort and paginate: page, starting at 0, amount, orderBy and
orderAsc. After the Request the method can take params of its own, like the ones below, which are added
to its schema and read from the same arguments. One with the name of an input of the Request takes its place, so a
param without a default makes that input required:
/**
* Searches the Tasks of a Project
* @param TaskRequest $request
* @param int $authorID Optional. The admin that asks for it.
* @return Response
*/
#[MCPTool(Access::API)]
public static function search(TaskRequest $request, int $authorID = 0): Response {
With params of its own
When a Request has more inputs than the tool needs, or the tool needs some that no Model has, the method takes
each argument as a param. Its type gives the one of the schema, a param without a default is required, and the
text after its name in the @param is its description. One that is not sent keeps its default, so a
null tells it apart. Such a tool can build the Request and call the other one:
use Framework\IO\Response;
use Framework\MCP\Attr\MCPTool;
use Framework\System\Access;
class TaskMCP {
/**
* Moves a Task to a position of a Column
* @param int $taskID The ID of the Task.
* @param int $taskSectionID The Column to move it to.
* @param int $position Optional. The position in the Column, starting at 0.
* @return Response
*/
#[MCPTool(Access::API)]
public static function move(int $taskID, int $taskSectionID, int $position = 0): Response {
return Task::move(new TaskRequest(id: $taskID, taskSectionID: $taskSectionID, position: $position));
}
}
| Param | Schema |
|---|---|
int, float, bool, string | integer, number, boolean and string. |
array | A list of strings, or of integers when its @param says list<int>. |
An Enum | A string with the names of its cases, read with fromValue(). |
Date | A string in the date format. |
A tool that takes the plain Request has no arguments in its schema, and reads whatever is sent. A call
that does not send a required input is answered with an error that names the missing ones, before the tool runs.
The title and the hints
Each tool is listed with a title for the person, made from the class and the method like the name,
so TaskMCP::getProjects is Task: Get projects, and with the hints that tell the client
what to ask before calling it. They are taken from the start of the method, and the attribute changes each one:
- readOnly: a method that starts with
get,listorsearchonly reads, so the client can call it without asking. - destructive: one that starts with
deleteorremovedeletes, so the client asks before calling it. One that only reads is never destructive. - openWorld: false unless the attribute says it, for the tools that reach outside of the app, like one that sends an email.
- idempotent: only sent when the attribute says it, for a tool that changes nothing more when called again.
#[MCPTool(Access::API, destructive: true)]
public static function upload(string $fileName, string $content): Response {
The endpoint
An app with at least one tool answers the protocol at the /mcp path, which the
.htaccess sends to the same index.php. Framework::execute() gives
it to MCPServer::execute() before reading anything of the request, so it is apart from the
routes: none of them is reached through it, and it is not reached
through them.
RewriteRule ^mcp$ backend/index.php [QSA,L]
Another path is given in a config, and the paths of the OAuth start with it too, so the
.htaccess sends that one instead:
use Framework\MCP\MCPServer;
MCPServer::setPath("/api/mcp");Before any message the server checks:
- The origin: a request with an
Originof another host is answered with a403, so a page open in a browser can not call it. - The login: only the
Authorization: Bearerheader is read, and only the token of an Access that has one of its own, or one that the OAuth gave, logs in. A session, the token of the API or none at all are answered with a401and aWWW-Authenticatethat points to where the OAuth starts. - The version: an
MCP-Protocol-Versionheader that the server does not know is answered with a400.
The token of an Access is the one of the owner of the app, so it lists and calls every tool. A credential only lists and calls the ones its Access is granted. With Claude Code the server is added as an HTTP one:
claude mcp add --transport http acme https://acme.com/mcp --header "Authorization: Bearer $TOKEN"
The assistants show the server with the name of the app and the favicon of the site, and the app can give them more about it in a config. Each one is only sent when it is set:
- Title: the name to show instead of the one of the app.
- Description: what the server is for.
- Website Url: the url of the site of the app.
- Icon: a path after the
APP_URL, or theURLwhen the app has none. - Instructions: how to use the tools, which the assistant reads when it connects.
use Framework\MCP\MCPServer;
MCPServer::setTitle("Acme");
MCPServer::setDescription("The tasks and the tickets of Acme");
MCPServer::setWebsiteUrl("https://acme.com");
MCPServer::setIcon("apple-touch-icon.png");
MCPServer::setInstructions("Search a task before editing it.");Connecting with OAuth
An assistant like claude.ai can not keep a token of its own, so it connects as a credential with the OAuth
that the protocol asks for. The app turns it on by giving the route of the page where a credential allows an app, with
{requestID} in it, and the Access it needs, in a config. The route goes after the
APP_URL, or the URL when the app has none:
use Framework\MCP\MCPAuth;
use Framework\System\Access;
MCPAuth::setAuthorizeRoute("oauth/{requestID}");
MCPAuth::setAccess(Access::Admin);The paths of the OAuth come in through the same branch as the MCP, so the .htaccess sends them too:
RewriteRule ^mcp(/.*)?$ backend/index.php [QSA,L]
RewriteRule ^\.well-known/oauth- backend/index.php [QSA,L]
| Path | Answer |
|---|---|
/.well-known/oauth-protected-resource | The MCP as a resource, and the server that gives its tokens. |
/.well-known/oauth-authorization-server | The paths below, the code flow with PKCE and the refresh tokens. |
/mcp/register | Registers an app with its urls, which have to be https or of the computer it runs in. |
/mcp/authorize | Stores the request of a known app, with the PKCE, and sends the browser to the page of the app for 10 minutes. |
/mcp/token | Gives an access token of an hour and a refresh token of 30 days for a code, or new ones for a refresh token. Each code and each refresh token is used once. |
The page logs the credential in like any other of the app, shows the name and the host of MCPAuth::getRequestApp(), as the name is the one the app gave itself, and
sends the answer to MCPAuth::answer() through a route of its own. It returns the url to send the
browser back to the app, with the code, or with an error when it was denied or the credential does not have the
Access. The codes and the tokens are only stored hashed, in the mcp_grant and mcp_token
tables, and a credential that loses the Access stops logging in with them.
The messages
The server answers each message on its own and keeps nothing between them, so it opens no stream and a
GET is answered with a 405.
| Message | Answer |
|---|---|
initialize | The version of the protocol the client asked for when it is known, or the latest, with the name and the version of the app. |
tools/list | The tools the current Access can call, with their schemas. |
tools/call | The result of the tool, as a text. |
ping | An empty result. |
| A notification | A 202 with no body, as it has no id. |
The Response of the tool becomes its result: the data as JSON, and the
success before it, and the data goes in the structuredContent too when it is an object. An error, or the errors of the fields, are translated and
sent as a result with isError, so the assistant reads what went wrong and can try again. An unknown
tool, or one the Access can not call, is an error of the protocol instead.
Calling a server
MCPClient::callTool() calls a tool of another server, like the one of the same app in another
environment, which is how a console command can work on production from a local copy. It sends the token as the
server expects it, and returns an MCPResult with the data of the tool, or with the error of the
protocol or of the tool:
use Framework\MCP\MCPClient;
$result = MCPClient::callTool("https://acme.com/mcp", $token, "task_get", [ "taskID" => 5 ]);
if ($result->isError) {
print("Error: {$result->error}\n");
return;
}
print($result->data->getDict("elem")->getString("name"));
A console command calls the same app in another environment with MCPClient::callEnvironment(),
which takes the url from the MCP_<ENV>_URL of the .env, or the URL for
local, and the token from the MCP_TOKEN. It prints the error and returns null when the
call fails, and both can be given to reach another copy:
$data = MCPClient::callEnvironment("prod", "task_get", [ "taskID" => 5 ]);
if ($data === null) {
return;
}