---
title: "MCPServer Plugin"
url: https://festi.dev/8.0/Plugins/MCPServer/
---

# MCPServer Plugin

## Model Context Protocol (MCP)

The [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) is an open standard that enables seamless integration between LLM applications and external data sources and tools. This PHP implementation allows you to build MCP servers that can expose:

- **Resources**: Context and data for AI models to use
- **Prompts**: Templated messages and workflows for users
- **Tools**: Functions for AI models to execute

## Installation

1. **Prerequisites**: Ensure the RPC plugin is installed and configured
2. **Add the plugin**:
   ```
   git submodule add [REPOSITORY_URL] plugins/MCPServer
   ```
3. **Run database migrations**: Execute the SQL files from `install/` directory for your database type:
   - `install.mysql.sql` for MySQL
   - `install.pgsql.sql` for PostgreSQL
   - `install.mssql.sql` for SQL Server
4. **Register RPC methods as MCP tools**: Each callable tool must exist in the `rpc_methods` table. The host project registers tools there (e.g. via its own migrations that insert or update `rpc_methods`).

## Upgrade notes

`install/install.*.sql` runs once, on a fresh install. The update files change an **existing**
install. There is one file per engine for each update. Each file is idempotent and safe to run
again. Run `update` first, then `update2`. A released update file does not change; a new change
goes into a new file.

- `update.*.sql` adds the columns `rpc_methods.open_world` and `rpc_methods.is_idempotent`, and
  the settings `mcp_protocol_versions`, `mcp_allowed_origins` and `mcp_max_request_size`.
- `update2.*.sql` adds the setting `mcp_host`.

The update files do not add the columns `rpc_methods.is_read_only`, `rpc_methods.title` and
`rpc_methods.url_template`. The sync of RPC methods writes them too. An install that does not
have them must first add them with the statements of `install.*.sql`, or the sync stops with
`Unknown column`.

| Engine | Files |
|---|---|
| MySQL and MariaDB | `install/update.mysql.sql`, `install/update2.mysql.sql` |
| PostgreSQL | `install/update.pgsql.sql`, `install/update2.pgsql.sql` |
| SQL Server | `install/update.mssql.sql`, `install/update2.mssql.sql` |

The host project runs them through its own migration, so a plugin upgrade also needs a matching
`dumps/updates<N>.sql` (or the host's equivalent) that applies the same statements under the
version tracking of `festi-migrate`. A plugin file nobody runs upgrades nothing.

### `rpc_methods.open_world` and `rpc_methods.is_idempotent`

`syncRpcMethods` writes both columns for every method, so sync fails with `Unknown column`
until they exist. `open_world` backs `openWorldHint` (see
[Optional: open-world vs bounded tools](https://festi.dev/8.0/Plugins/MCPServer/docs/ToolAnnotations/index.md)); `is_idempotent` backs
`idempotentHint`. Default `0` on both, which is what a method that carries no marker reports.

Run **sync RPC methods** after the migration so the new columns are filled from the declared
annotations.

A note on the MySQL file: `ALTER TABLE ... ADD COLUMN IF NOT EXISTS` is a MariaDB extension and
MySQL 8.0 rejects it, so `update.mysql.sql` guards each column through `information_schema` and
applies it as a prepared statement. That form is idempotent on both engines.

### Streamable HTTP transport settings (FAP-51)

`update.*.sql` adds `mcp_protocol_versions`, `mcp_allowed_origins` and `mcp_max_request_size`, each guarded so re-running the file changes nothing and an operator's own value is never overwritten. All three default to the behaviour the endpoint had before they existed, so an upgrade serves every client it served before.

Two things do change and are worth expecting:

- **`initialize` now negotiates.** It used to answer `mcp_protocol_version` whatever the client asked for. It now answers the revision the client asked for when `mcp_protocol_versions` lists it, and this server's latest otherwise, which is what the lifecycle spec requires. A client asking for `2025-03-26` is now told `2025-03-26` instead of `2025-06-18`. An install that skips the migration keeps the old single-revision answer, because an empty list falls back to `mcp_protocol_version`.
- **`GET` and `DELETE` on the MCP endpoint now answer `405`.** Nothing in this plugin ever served them; a host that routed something else through the `mcp` area should check it.

`mcp_max_request_size` ships at 1 MiB rather than off. An inbound MCP body is a single JSON-RPC message, in practice a `tools/call` with JSON arguments, so a legacy caller sending more than a mebibyte of JSON-RPC is not plausible and PHP's own `post_max_size` is usually lower still. Set it to `0` to disable the cap.

Set `mcp_allowed_origins` on any deployment a browser can reach, and **always** on a deployment whose host plugin authenticates from the ambient session. It ships empty because the Rpc entry-point template answers with `Access-Control-Allow-Origin: *` at the web server, so a browser consumer may exist today and must not be cut off silently by an upgrade. See [Origin validation](https://festi.dev/8.0/Plugins/MCPServer/docs/Transport/index.md#origin-validation-dns-rebinding-protection).

### The `mcp_host` setting row (`update2.*.sql`)

The transport reads `mcp_host` on each MCP request since FAP-51, but `update.*.sql` and `install.*.sql` did not add it. An install with no `mcp_host` row answers each MCP request, also a CORS preflight, with 500 `Undefined setting with key: mcp_host`. `install.*.sql` now writes the row, and `update2.*.sql` adds it to an existing install with an empty value. An empty value is a deployment that does not pin its host (see [Configuration](#configuration)). The insert is guarded, so a value that the operator set stays. `McpEntryPointTemplateTest` runs the PostgreSQL files in SQLite and then the entry point template with the settings that they wrote.

### The MCP entry point now answers the CORS preflight (FAP-51)

`install/mcp/mcp.php` used to `exit()` on `OPTIONS` at the top of the file, before the framework booted, which returned 200 with no `Access-Control-*` header and so failed every cross-origin preflight. It now builds the plugin first, loads the settings with `loadSettings()`, and calls `MCPServerPlugin::sendCorsPreflight()`, which answers 204 from `mcp_allowed_origins`. The plugin loads the settings only when it binds the request. Thus an entry point that calls `sendCorsPreflight()` without `loadSettings()` before it answers each preflight with 500 `Undefined setting with key: mcp_allowed_origins`. **Copy the new template into your host app**, or keep answering the preflight at your web server and make its origin list agree with the setting.

### Vendored Rpc test submodule (FAP-51)

`tests/Resources/plugins/Rpc` moves `f336c80` to `b94334b` (upstream Rpc `master`). FAP-51 needs exactly one commit from that range, `71415ad`, which adds `RpcPlugin::prepareAcceptedResponse()` (202 Accepted with an empty body for a notification-only POST); the rest rides along because the submodule tracks a branch rather than a tag. Nothing ships from this directory: it is a test resource, and the only effect is what the suite runs against.

### Session fixation in the copied entry point (FAP-51)

`install/mcp/common.php` is a **template** copied into each host app at install time, not code this plugin executes, so a fix to it does not reach a project that already copied it. Earlier versions accepted a caller-supplied session id:

```php
if (!empty($_REQUEST['ssids'])) {
    session_id($_REQUEST['ssids']);
}
```

That lets an attacker fix a victim's session id through a URL parameter (session fixation). If your project copied that file, **delete the block from your own copy**. MCP callers authenticate with `Authorization: Bearer`, the `X-Authorization` header or the `token` GET parameter; no supported flow needs `ssids`. The Rpc plugin removed the same block from `install/rpc/common.php`.

## Dependencies

This plugin depends on the RPC plugin and leverages its type handling utilities to maintain consistency and avoid code duplication. The `TypeMapper` class delegates basic type operations to RPC's `ParameterProcessor`, while adding MCP-specific functionality for JSON Schema generation.

## Architecture

The MCPServer plugin acts as a bridge between the MCP protocol and your existing RPC methods:

1. **RPC Methods → MCP Tools**: All RPC methods (marked with `@rpc` annotation) are automatically exposed as MCP tools
2. **Type Mapping**: PHP types are converted to JSON Schema for MCP tool definitions
3. **Permission Checking**: RPC method permissions (`@section` annotations) are enforced
4. **Parameter Passing**: Named parameters from MCP are passed straight to the plugin method via PHP 8 named-arg splat; params the caller omitted resolve to the method's declared defaults.

### Domain Classes

The plugin is organized into several domain classes:

- **`TypeMapper`** - Maps PHP types to JSON Schema types, handles nullable and union types
- **`SchemaBuilder`** - Builds JSON Schema for tool input parameters and output (`getOutput()` derives an `outputSchema` from the method's return type)
- **`OutputSchema`** - An `outputSchema` plus the rule for shaping a raw result into conforming `structuredContent` (wraps non-object roots under a `result` key)
- **`ClassJsonSchemaGenerator`** - Generates JSON Schema from ValuesObject classes using JsonProperty annotations
- **`ParameterMetadataParser`** - Extracts parameter names and metadata from docblocks
- **`UnionTypeResolver`** - Resolves union types by selecting the first valid type
- **`ToolsCollector`** - Collects and filters RPC methods, converts them to MCP tool definitions
- **`ResponseFormatter`** - Formats MCP responses (success and error)
- **`ProtocolResponseFactory`** - Creates MCP protocol-compliant responses

`MCPServerPlugin` keeps the event handlers and the rpc methods of the protocol. It gives the work of `tools/call` and of the HTTP transport to these classes:

- **`ToolRegistry`** - Gives the rpc methods that are on the MCP tool surface. The rpc methods of the MCP server itself are not on it.
- **`ToolCallHandler`** - Answers one `tools/call` request: it reads the request fields, resolves the tool name, refuses or runs the call, and gives an answer for a failure.
- **`ToolAccessGate`** - Decides whether the caller may call a tool, under the same decision that `tools/list` renders.
- **`ToolCallRunner`** - Runs an accepted call between `BeforeToolCallEvent` and `AfterToolCallEvent`.
- **`ToolInvoker`** - Invokes an accepted tool and gives its MCP result.
- **`DgsToolCall`** - Answers a DataGridStore tool with its page url and area. The method behind the tool does not run.
- **`RpcToolDispatcher`** - Calls the plugin method behind a tool with the named arguments of the caller.
- **`ToolCallErrors`** - The error answers of `tools/call`. No answer shows an internal of the server.
- **`TransportSettings`** - Builds the transport rules and the pinned host from the settings when a request comes.
- **`HttpEndpoint`** - Answers the HTTP side of a request: the CORS preflight, a refused request, the CORS headers, the event-stream answer and the bearer challenge of a 401.

### RPC Method Caching

`ToolRegistry` reads the RPC methods one time and keeps them for the lifetime of the plugin instance. `getTools()` and each grant decision of `tools/call` use the same rows.

## Configuration

The plugin uses the following settings (configured via `festi_settings` table):

- `mcp_protocol_version` - the single MCP protocol revision an install configured before `mcp_protocol_versions` existed (default: `2025-06-18`). Still read as the fallback when the list is unset.
- `mcp_protocol_versions` - the revisions this server speaks, newest first, separated by commas (default: `2025-06-18,2025-03-26`). The first entry is what an `initialize` asking for anything else is answered with. See [Transport](https://festi.dev/8.0/Plugins/MCPServer/docs/Transport/index.md#protocol-version).
- `mcp_allowed_origins` - browser origins allowed to call the endpoint, separated by commas (default: empty, which refuses no origin). See [Origin validation](https://festi.dev/8.0/Plugins/MCPServer/docs/Transport/index.md#origin-validation-dns-rebinding-protection).
- `mcp_max_request_size` - largest request body in bytes, `0` disables the cap (default: `1048576`, one mebibyte).
- `mcp_server_name` - Server name identifier (default: `festi-mcp`)
- `mcp_server_version` - Server version (default: `1.0.0`)
- `mcp_tools_prefix` - Prefix for all tool names in `tools/list` and `tools/call` (default: `FESTI_MCP`)
- `mcp_host` - Bare hostname, with an optional port (no scheme, no path), of the MCP resource server, e.g. `mcp.example.com` (default: empty). A value with a scheme, a path, a quote or a space is refused: it is logged in `rpc_errors` and the server works as if the value is empty. The row must exist, also with an empty value: without it each MCP request gets 500. The `https://` scheme is added automatically. Pinned in config so the value never depends on the inbound request's `Host` header. Setting this also opts the deployment into OAuth: MCPServer emits `WWW-Authenticate: Bearer resource_metadata="https://<mcp_host>/.well-known/oauth-protected-resource"` on unauthenticated MCP requests so OAuth-capable clients (Claude Desktop, ChatGPT, Inspector) start the OAuth discovery flow. Leave empty for legacy `MCP_TOKEN`-only deployments — the challenge header is silently omitted. The host project must mount its own `/.well-known/oauth-protected-resource` handler (e.g. install an OAuth plugin like `MCPOAuth`).

You can update these settings in the database.

### Tool name prefix

When `mcp_tools_prefix` is set, tool names are built as **PREFIX** + **separator** + **RPC method name**. The separator is `__` (double underscore). Example: with prefix `FESTI_MCP`, the RPC method `onJsonExportToGoogleCalendar` is exposed as tool `FESTI_MCP__onJsonExportToGoogleCalendar`.

**Restriction:** The full tool name (prefix + separator + method) must match the MCP pattern `^[a-zA-Z0-9_-]{1,64}+$`. Only letters, digits, underscores, and hyphens are allowed. Do **not** use colons (`::`), spaces, dots, or other symbols in the prefix—they will break tool listing and calls.

**Recommendations:**

- If different MCP servers expose tools with the same name, the client cannot tell them apart and may call the wrong server (unpredictable behavior). Use a distinct prefix per server so tool names are unique (e.g. `FESTI_MCP__getUserInfo` vs `OTHER_SERVER__getUserInfo`).
- Store the prefix in uppercase (e.g. `FESTI_MCP`) for consistency with `tools/list` output.
- Set `mcp_tools_prefix` to empty only when you have a single MCP server or when this server is the only one exposing those tool names; otherwise use a prefix to avoid clashes.

## Creating MCP Tools from RPC Methods

Any RPC method in your application automatically becomes an MCP tool. Declare the method with `#[RpcAttribute]` (preferred) or the `@rpc` doc-tag.

**Preferred — attributes:**

```php
use Plugins\Rpc\Domain\Attribute\RpcAttribute;
use core\plugin\attribute\SectionAttribute;

class MyPlugin extends DisplayPlugin
{
    #[RpcAttribute('getUserInfo')]
    #[SectionAttribute('user_management')]
    public function getUserInfo(int $idUser, bool $includeDetails = false): array
    {
        return [
            'id' => $idUser,
            'name' => 'John Doe',
            // ...
        ];
    }
}
```

**Legacy — doc-tag:**

```php
class MyPlugin extends DisplayPlugin
{
    /**
     * @rpc getUserInfo
     * @param int $idUser
     * @param bool $includeDetails
     * @return array
     * @section user_management
     */
    public function getUserInfo(int $idUser, bool $includeDetails = false): array
    {
        // Your implementation
        return [
            'id' => $idUser,
            'name' => 'John Doe',
            // ...
        ];
    }
}
```

After syncing RPC methods, this will be available as an MCP tool named `getUserInfo` with:
- **Name**: `getUserInfo`
- **Description**: From the method's docblock or RPC method description
- **Input Schema**: Automatically generated from parameter types
- **Permissions**: Enforced via `@section` annotation

**Helping agents use tools:** The agent only sees each tool's name, description, and inputSchema from `tools/list`. Put usage guidance in the tool's **description** in `rpc_methods`. For **search-style** tools, describe the query format (e.g. space- or comma-separated terms), optional filter keys, and that the response has `items` and `total`. For **update/create-style** tools, document each parameter (e.g. what `requestIDs` means, which keys `data` can have, required vs optional fields) and what the tool returns. See [Tool usage guidance for agents](https://festi.dev/8.0/Plugins/MCPServer/docs/AgentToolGuidance/index.md) for examples of both patterns.

**Exposing a whole grid instead of one method:** A backend page that already renders a DGS can be turned into a CRUD tool with a single annotation, without writing per-operation RPC methods. See [Creating an MCP Tool from a DGS](#creating-an-mcp-tool-from-a-dgs).

**Safety annotations (Claude catalog):** For your server to be listed in the [Claude MCP Directory](https://support.claude.com/en/articles/12922490-remote-mcp-server-submission-guide), every tool must declare a safety hint — read-only or destructive. The plugin supports two declaration forms: PHP 8 **attributes** (`#[McpReadOnlyAttribute]` / `#[McpDestructiveAttribute]`, preferred) and **PHPDoc** tags (`@mcpReadOnly` / `@mcpDestructive`, legacy). Both flow through the same `McpAnnotationResolver`. See [Writing tools with required annotations](https://festi.dev/8.0/Plugins/MCPServer/docs/ToolAnnotations/index.md).

### How to annotate your RPC methods

Every method exposed as an MCP tool must carry exactly one safety hint so the tool gets the correct `readOnlyHint` / `destructiveHint` in `tools/list`. Pick a declaration form:

- **`#[McpReadOnlyAttribute]`** / **`@mcpReadOnly`** – use for tools that only read data (no creates, updates, deletes, or side effects like emails/webhooks).
- **`#[McpDestructiveAttribute]`** / **`@mcpDestructive`** – use for tools that create, update, or delete data, write files, or perform any side effect.

Optionally add **`#[McpOpenWorldAttribute]`** / **`@mcpOpenWorld`** to tools that write to arbitrary URLs/files/resources, so they report `openWorldHint: true` (default is `false` — bounded to our own product). It is independent of the read-only / destructive safety hint.

Optionally add **`#[McpIdempotentAttribute]`** / **`@mcpIdempotent`** to tools where repeating the same call with the same arguments leaves the target in the same state as one call, so they report `idempotentHint: true`. A tool that carries no marker publishes no `idempotentHint` at all, so existing `tools/list` output is unchanged.

Attribute and doc-tag forms can coexist across methods in the same plugin; per method, pick one form. The full guide with examples and when to use which is in [Writing MCP tools with required annotations](https://festi.dev/8.0/Plugins/MCPServer/docs/ToolAnnotations/index.md).

### Tool Naming Requirements

Tool names (RPC method names) must match the pattern: `^[a-zA-Z0-9_-]{1,64}+$`
- Only alphanumeric characters, underscores, and hyphens are allowed
- Maximum length: 64 characters
- Tool names must be unique across all plugins
- When `mcp_tools_prefix` is set, the exposed name is `PREFIX__methodName` (see [Tool name prefix](#tool-name-prefix))

### Parameter Types

The plugin automatically converts PHP types to JSON Schema:
- `int` → `integer`
- `float` → `number`
- `string` → `string`
- `bool` → `boolean`
- `array` → `object` (associative arrays) or `array` with items schema
- Typed arrays of primitives (`int[]`, `string[]`, `float[]`, `bool[]`) → `array` with `items` schema (e.g. `items: { type: "integer" }`)
- Custom classes → `object` with properties schema (using `JsonProperty` annotations)
- Union types (e.g., `int|string`) → `oneOf` schema
- Nullable types (e.g., `?string`, `string|null`) → schema with `null` in type array
- `mixed` → schema accepting all types (string, number, boolean, object, array, null)

### Parameter Defaults

MCP callers (LLMs, remote clients) often send only a subset of a tool's parameters. The dispatcher passes whatever the caller sent straight to your method as PHP 8 named arguments — any param the caller omitted resolves to the value you declared in the signature, with no nullability or in-method coercion needed. Write `int $limit = 50` and trust PHP; don't reach for `?int $limit = null` + `$limit ??= 50` just to absorb missing MCP args. **One caveat:** the docblock `@param $name` must match the actual signature parameter name, because the dispatcher splats named args — `@param int $count` paired with `int $limit` in the signature triggers a runtime "Unknown named parameter `$count`" error. (Under the older positional dispatcher this mismatch was silently absorbed.)

#### Advanced Type Handling

**Custom Classes (ValuesObject)**
Custom classes that extend `ValuesObject` are automatically converted to JSON Schema by inspecting `JsonProperty` annotations:

```php
use core\json\JsonProperty;
use ValuesObject;

class UserRequest extends ValuesObject
{
    #[JsonProperty("userId")]
    private int $idUser;

    #[JsonProperty("includeDetails")]
    private bool $includeDetails = false;

    // Getters and setters...
}
```

The schema generator will create a JSON Schema with properties matching the `JsonProperty` annotations.

**Arrays of primitives (int[], string[], float[], bool[])**

Typed arrays of primitives produce `type: "array"` with an `items` schema for the element type: `int[]` → `items: { type: "integer" }`, `string[]` → `items: { type: "string" }`, `float[]` → `items: { type: "number" }`, `bool[]` → `items: { type: "boolean" }`. So the LLM sees that the parameter is a list of integers, strings, etc. PHP reflection only gives `array` for method parameters, so to get this schema you need to set `params_types` in the database (e.g. in a migration) to `int[]`, `string[]`, etc. for the corresponding parameter.

**Arrays of objects (ClassName[])**

When a parameter type is a typed array (e.g. `CommitValuesObject[]`), the MCP tool schema gets `type: "array"` with an `items` schema generated from that class. Use a ValuesObject (or DTO) with `JsonProperty` on the fields you accept; only those properties appear in the schema and are used for deserialization. Set `params_types` in the database (e.g. via a migration) to the full class name with `[]`, e.g. `plugin\Commits\domain\model\CommitValuesObject[]`, because reflection only sees `array` and sync would otherwise not expose the item shape. See [QA: Describing RPC methods for LLMs](https://festi.dev/8.0/Plugins/MCPServer/docs/QA/index.md).

**Union Types**
Union types like `int|string` or `bool|null` are resolved by selecting the first non-null, non-mixed type. The resulting schema uses `oneOf` to represent the union.

**Nullable Types**
Nullable types are handled by:
- Stripping the `?` prefix or `|null` suffix
- Adding `null` to the type array in the schema
- Example: `?string` becomes `["string", "null"]`

**Parameter Name Extraction**
Parameter names are extracted from `@param` annotations in docblocks. If not found, default names like `param1`, `param2` are used.

For guidance on describing RPC methods so LLMs fill params correctly (typed params, `params_types`, `JsonProperty`, etc.), see [QA: Describing RPC methods for LLMs](https://festi.dev/8.0/Plugins/MCPServer/docs/QA/index.md).

### Permissions

RPC methods with `@section` annotations will have their permissions checked before execution. For detailed information about the permissions system, see the [Permissions documentation](https://festi.dev/8.0/Core/Permissions/index.md).

The permission system uses the following database tables:

- **`festi_sections`** - Defines permission sections (identified by the `@section` annotation)
- **`festi_section_actions`** - Maps plugin methods to sections and required permission masks
- **`festi_sections_user_permission`** - User-specific permissions (overrides user type permissions)
- **`festi_sections_user_types_permission`** - User type/role-based permissions

#### How Permission Checking Works

1. When an RPC method is called, the system looks up the method in `festi_section_actions` to find:
   - The associated section (`id_section`)
   - The required permission mask (2 = Read, 4 = Write, 6 = Execute)

2. The system then checks the user's permissions by querying:
   - `festi_sections_user_permission` for user-specific permissions (takes priority)
   - `festi_sections_user_types_permission` for role-based permissions

3. The user's granted mask must be greater than or equal to the required mask for the action.

#### Setting Up Permissions

To protect an RPC method, you need to:

1. **Add the `@section` annotation** to your RPC method:
```php
/**
 * @rpc deleteUser
 * @param int $idUser
 * @section user_management  // References a section in festi_sections
 * @return bool
 */
public function deleteUser(int $idUser): bool
{
    // Implementation
}
```

2. **Create the section** in `festi_sections` (if it doesn't exist):
```sql
INSERT INTO festi_sections (caption, ident, mask)
VALUES ('User Management', 'user_management', '6');
```

3. **Register the action** in `festi_section_actions`:
```sql
INSERT INTO festi_section_actions (id_section, plugin, method, mask, comment)
VALUES (
    (SELECT id FROM festi_sections WHERE ident = 'user_management'),
    'MyPlugin',
    'deleteUser',
    '6',  -- Execute permission required
    'Delete user action'
);
```

4. **Assign permissions** to users or user types:
```sql
-- For a specific user type
INSERT INTO festi_sections_user_types_permission (id_section, id_user_type, value)
VALUES (
    (SELECT id FROM festi_sections WHERE ident = 'user_management'),
    1,  -- Admin user type
    6   -- Execute permission
);

-- For a specific user (overrides user type permissions)
INSERT INTO festi_sections_user_permission (id_section, id_user, value)
VALUES (
    (SELECT id FROM festi_sections WHERE ident = 'user_management'),
    123,  -- User ID
    6     -- Execute permission
);
```

If a user attempts to call a tool without sufficient permissions, they will receive a `PermissionsException` error.

### Response Object Handling

RPC methods that accept a `Response` object as the first parameter (common in display methods) are automatically handled:

```php
/**
 * @rpc getProjects
 * @param Response $response
 * @return bool
 */
public function onDisplayList(Response &$response): bool
{
    $store = $this->createStoreInstance("projects");
    $store->onRequest($response);
    return true;
}
```

When such methods are called via MCP:
1. A `Response` object is automatically created and passed as the first parameter
2. The method's return value is ignored
3. The `Response` object's contents are extracted and returned as the tool result
4. This allows MCP tools to work seamlessly with existing display methods

### Error Handling

The plugin includes comprehensive error handling:

- **Tool Not Found**: Returns error if the requested tool name doesn't exist. A tool the host hid from this caller is answered the same way, so the refusal does not reveal that the tool exists.
- **Method Not Found**: Returns error if the RPC method cannot be found
- **Permission Denied**: Throws `PermissionsException` which is caught and logged
- **Bad arguments**: A missing required argument or an unusable argument value is answered by naming that argument (e.g. `Error: Missing required argument 'idReward'.`). Only a failure of the call to the tool method is named this way; the same error in the tool's own code is an internal error. An argument that the tool does not declare is not sent to the tool. The name and its declared type come from the tool's registry row, so no class name, path or stack reaches the caller. See [Governing a tool call](https://festi.dev/8.0/Plugins/MCPServer/docs/ToolCallEvents/index.md).
- **Internal Errors**: All exceptions are caught, logged to `IRpc::LOG_ERRORS`, and a user-friendly error message is returned

Errors are logged with context including the tool name and exception details for debugging.

## Structured output (`outputSchema` + `structuredContent`)

MCP `2025-06-18` (the protocol version this server pins — see [Configuration](#configuration)) adds **structured tool output**. MCPServer supports it automatically; you do not annotate anything:

- In `tools/list`, a tool with a known return shape publishes an `outputSchema` — a JSON Schema `object` describing its result.
- In `tools/call`, a successful result carries both the usual human-readable `content` text block **and** a machine-readable `structuredContent` object that conforms to that `outputSchema`. The text block is always emitted too, so clients that ignore `structuredContent` keep working unchanged.

### How the schema is derived

**RPC-method tools** — `SchemaBuilder::getOutput()` reads the method's declared return type:

| Return type | `outputSchema` root | `structuredContent` |
|---|---|---|
| ValuesObject class (`: UserValuesObject`) | object built from its `JsonProperty` annotations | the object as-is |
| Scalar (`: int`, `: string`, `: bool`, `: float`) | object with one `result` property | `{ "result": <value> }` |
| Typed array (`: UserValuesObject[]`) | object with one `result` property (array) | `{ "result": [ … ] }` |
| Nullable (`: ?UserValuesObject`) | as above, with `null` added to the type | same shape, may be `null` |
| `array` / `mixed` / `void` / no return type | *(omitted)* | *(omitted — only text content)* |

MCP requires the `outputSchema` root to be a JSON **object**, so non-object results (scalars, arrays) are wrapped under a single `result` key (`OutputSchema::WRAPPER_KEY`). A value-object class is already an object, so it passes through unwrapped.

A nullable value-object property (a `JsonProperty` setter that takes `?string`, `?int`, `?SomeValuesObject`, …) publishes `["<type>", "null"]` in `outputSchema`, also inside typed-array items, so a `null` value in `structuredContent` conforms. The output entry points are `ClassJsonSchemaGenerator::generateOutput()` and `ArrayJsonSchemaGenerator::getTypedArrayOutputProperty()`; both use `TypeMapper::getNullableSchema()`. `inputSchema` does not change: a nullable parameter or property keeps its plain type and is only left out of `required`, because some function-calling clients reject type lists in parameters.

**DGS tools** — return a fixed shape, so their schema is fixed too (`DgsToolDescription::getOutputSchema()`):

```json
{
  "type": "object",
  "properties": {
    "url":   { "type": "string" },
    "area":  { "type": "string" },
    "usage": { "type": "string" }
  },
  "required": ["url", "area", "usage"]
}
```

The `{ url, area, usage }` result (see [What sync stores and what the tool returns](#what-sync-stores-and-what-the-tool-returns)) is emitted verbatim as `structuredContent`.

### Example

`tools/call` result for a DGS tool:

```json
{
  "content": [
    { "type": "text", "text": "{\n  \"url\": \"/company/17086/settings/grade-groups/\", …\n}" }
  ],
  "structuredContent": {
    "url":   "/company/17086/settings/grade-groups/",
    "area":  "backend",
    "usage": "…step-by-step instructions for getSchemeByUrl + execUrl…"
  }
}
```

### Client / LLM support

`structuredContent` is consumed by MCP clients that speak `2025-06-18` — Claude Desktop, the Claude API MCP connector, and MCP Inspector. Clients on older protocol revisions simply ignore the extra field and read the `content` text block, so publishing an `outputSchema` breaks no one. Some clients also validate `structuredContent` against the published `outputSchema`, so keep a method's declared return type accurate — if the real result diverges from the declared shape, a validating client can reject the call.

## Governing a tool call from the host project

A tool a host plugin hides from a caller's `tools/list` is also refused at `tools/call`, with the
same answer an unknown tool name gets, and a gate that fails while deciding refuses the call
rather than letting it through. Around an accepted call the plugin dispatches
`BeforeToolCallEvent` (refuse the call, or answer it with a stored result) and
`AfterToolCallEvent` (audit trail, idempotency ledger). See [Governing a tool call](https://festi.dev/8.0/Plugins/MCPServer/docs/ToolCallEvents/index.md).

## Extending a tool definition from the host project

A host project that needs to publish its own metadata on a tool (risk level, approval policy, a canonical tool id) does not patch this plugin: it listens to `PrepareToolDefinitionEvent` and adds `_meta` entries and annotations for the tools it cares about. See [Extending tool definitions](https://festi.dev/8.0/Plugins/MCPServer/docs/ToolDefinitionExtension/index.md).

## Creating an MCP Tool from a DGS

Most admin screens are already DGS grids with full list/insert/edit/remove behaviour. Instead of writing a separate RPC method per operation, you expose the whole grid as one tool by tagging its existing page method. The tool does not return rows itself — it returns the page `url` and `area`, which the agent then drives with the generic `getSchemeByUrl` / `execUrl` tools (documented in the RPC plugin README, section *Working with DGS over RPC*).

### Declaring the tool

Add `#[McpDgsAttribute]` (preferred) or the `@mcpDgs` doc-tag to the page's display method — the same method that already carries `@rpc`, `@urlRule`, `@section`, and `@area`. The annotation value is a **url template**: the concrete form of the method's `@urlRule`, with a named `{token}` for each path parameter.

**Preferred — attribute:**

```php
use Plugins\Rpc\Domain\Attribute\RpcAttribute;
use Plugins\MCPServer\Domain\Attribute\McpDgsAttribute;
use Plugins\MCPServer\Domain\Attribute\McpTitleAttribute;
use core\plugin\attribute\AreaAttribute;
use core\plugin\attribute\SectionAttribute;
use core\plugin\attribute\UrlRouteAttribute;

#[RpcAttribute('getGradeLevels')]
#[McpDgsAttribute('/company/{idWorkspace}/settings/grade-groups/')]
#[McpTitleAttribute('Grade Levels - list and manage')]
#[UrlRouteAttribute('~^/company/([0-9]+)/settings/grade-groups/$~')]
#[SectionAttribute('GradeGroupsSections::MANAGE_WORKSPACE')]
#[AreaAttribute('backend')]
public function onDisplayList(Response &$response, int $idWorkspace): bool
{
    // renders the normal grid page for human users
}
```

**Legacy — doc-tag:**

```php
/**
 * Grade Levels management table for a school.
 *
 * @rpc getGradeLevels
 * @mcpDgs /company/{idWorkspace}/settings/grade-groups/
 * @mcpTitle Grade Levels - list and manage
 * @urlRule ~^/company/([0-9]+)/settings/grade-groups/$~
 * @section GradeGroupsSections::MANAGE_WORKSPACE
 * @area backend
 * @param Response $response The response object to render the list.
 * @param int $idWorkspace Workspace id; get it from getActiveWorkspacesByCurrentUser.
 * @return bool
 */
public function onDisplayList(Response &$response, int $idWorkspace): bool
```

### Url-template tokens

Each `{token}` in the template must match a method parameter name by spelling (`{idWorkspace}` ↔ `int $idWorkspace`). The tokens — not the `Response` parameter — become the tool's input schema, so the agent is asked for exactly the values needed to build the url. At call time `UrlTemplateBinder` substitutes each token with the same-named argument; a token with no matching argument fails with an actionable "Missing the … value" error.

### What sync stores and what the tool returns

On `syncRpcMethods`, the template is saved to `rpc_methods.url_template` and the tool is forced **read-only** — calling it has no side effects of its own; it only hands back a url.

In `tools/list` the tool's description is the method summary plus a centrally-owned workflow hint naming the two follow-up tools (`getSchemeByUrl`, `execUrl`). When called via `tools/call`, MCPServer intercepts the DGS tool **before** the method body runs and returns:

```json
{
  "url":   "/company/17086/settings/grade-groups/",
  "area":  "backend",
  "usage": "…step-by-step instructions for getSchemeByUrl + execUrl…"
}
```

The agent then introspects the page with `getSchemeByUrl` and reads/writes rows with `execUrl`. The display method body is never invoked over MCP — it still serves the normal HTML page for human users, and the DGS tool only reuses its url and `@section` permission.

### Naming

Name a DGS tool plainly after the entity (`get<Entity>`) and put the human-facing workflow in `@mcpTitle` (entity + the operations it unlocks, e.g. `list and manage`).

## Transport

The MCP endpoint speaks [Streamable HTTP](https://modelcontextprotocol.io/specification/2025-06-18/basic/transports) in its stateless subset: one POST in, one answer out.

| Request | Answer |
|---|---|
| `POST` with a JSON-RPC request | `application/json`, or one SSE event when the client cannot read JSON |
| `POST` with only notifications or responses | `202 Accepted`, empty body |
| `GET` | `405` + `Allow: POST` (this endpoint opens no server-initiated stream) |
| `DELETE` | `405` + `Allow: POST` (this endpoint issues no session) |
| `OPTIONS` | `204` CORS preflight, answered from the origin allow list before sign-in runs |

Not supported, by design: `Mcp-Session-Id` sessions, the server-initiated `GET` stream, resumable streams, and the legacy HTTP+SSE transport of protocol revision `2024-11-05`. A client that reads the 405s skips the stream and the delete and keeps working over POST alone. Holding a connection open belongs to the Festi Async daemon, not to this plugin.

The endpoint also validates `Origin` (the DNS-rebinding protection the specification requires), validates `MCP-Protocol-Version` (`400` for a revision it does not speak), decides per revision whether a batched body is accepted, and caps the request body with a `413`.

**Note on the shipped default.** `mcp_allowed_origins` ships empty, and with an empty list this endpoint performs none of the Origin validation the specification makes a MUST: the only barrier is authentication by an explicit token. **A host that signs a caller in from the ambient PHP session rather than from a token MUST configure the list.** See [Origin validation](https://festi.dev/8.0/Plugins/MCPServer/docs/Transport/index.md#origin-validation-dns-rebinding-protection).

**Everything defaults to today's behaviour.** A client that sends no `Accept`, no `MCP-Protocol-Version` and no `Origin`, and authenticates with `X-Authorization` or `?token=`, is answered exactly as it was before this transport work.

Four settings govern it: `mcp_protocol_versions`, `mcp_allowed_origins`, `mcp_max_request_size` and the older `mcp_protocol_version` (see [Configuration](#configuration)).

**nginx**: an event-stream answer must reach the client as it is written, so turn buffering off on the MCP location. The CORS preflight needs nothing here: the plugin answers it from the allow list.

```nginx
location = /mcp {
    fastcgi_pass php:9000;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME /app/src/mcp/mcp.php;
    fastcgi_param REQUEST_URI /;

    fastcgi_buffering off;
    gzip off;
}
```

**Host entry point**: authentication failures answer `401` with `WWW-Authenticate` only when the host routes *both* of its failure paths through `MCPServerPlugin::onException()` — the `onException` option of `bindRequest`, and an outer `try`/`catch` around it, because `signInByRpcByToken()` raises before the URL is bound. `install/mcp/mcp.php` does both; copy it rather than writing your own.

Full detail, including the preflight snippet and why the origin allow list ships empty: [./docs/Transport.md](https://festi.dev/8.0/Plugins/MCPServer/docs/Transport/index.md).

## MCP Protocol Methods

The plugin implements the following MCP protocol methods:

### Core Methods

- **`initialize`** - Initializes the MCP connection, returns server capabilities and information
- **`tools/list`** - Returns a list of all available tools (RPC methods)
- **`tools/call`** - Executes a tool by name with provided arguments
- **`resources/list`** - Returns available resources (currently returns a "tools" resource)
- **`prompts/list`** - Returns available prompts (currently empty, infrastructure ready for future use)

### Notifications

- **`notifications/initialized`** - Called after initialization is complete (currently no-op)
- **`notifications/cancelled`** - Called when a request is cancelled (currently no-op)

All methods follow the JSON-RPC 2.0 specification and are automatically registered when you sync RPC methods.

## Resources

The plugin currently exposes one resource:

- **`tools`** - Provides access to callable tools via `tools/list` and `tools/call` methods

Resources are defined in the `getResources()` method and can be extended to expose additional data sources for AI models.

## Prompts

The prompts feature is currently implemented but returns an empty list. The infrastructure is in place to add templated messages and workflows. To add prompts, modify the `getPrompts()` method in `MCPServerPlugin.php`.

## MCP HTTP Bridge

The `mcp-http-bridge.js` is a Node.js bridge that converts between stdio (used by Claude Desktop) and HTTP (used by your PHP MCP server). It acts as a transparent proxy, forwarding all MCP JSON-RPC messages between Claude Desktop and your HTTP-based MCP server.

### Command Line Options

The bridge supports the following command line arguments (order-independent):

- `--protocol <http|https>` - Protocol to use (default: `http`)
- `--host <hostname>` - Server hostname (default: `localhost`)
- `--port <port>` - Server port (default: `8080`)
- `--path <path>` - Server path/endpoint (default: `/`)

Arguments follow the logical URL structure: `protocol://host:port/path`.

The authentication token is read from the `MCP_TOKEN` environment variable (see [Authentication Token Setup](#authentication-token-setup)).

## Authentication Token Setup

The MCP bridge supports per-user authentication tokens. Each user needs their own token to identify themselves when using tools.

### Setting Up Your Token

The token is passed via the `MCP_TOKEN` environment variable, not as a command-line argument. This prevents the token from appearing in process lists or system logs.

For local server:
```bash
MCP_TOKEN=your-personal-token node mcp-http-bridge.js
```

For remote server:
```bash
MCP_TOKEN=your-personal-token node mcp-http-bridge.js --protocol http --host remote-server.com --port 8080
```

For HTTPS server:
```bash
MCP_TOKEN=your-personal-token node mcp-http-bridge.js --protocol https --host remote-server.com --port 443
```

For server with custom path:
```bash
MCP_TOKEN=your-personal-token node mcp-http-bridge.js --protocol http --host remote-server.com --port 8080 --path /rpc/v1/
```

## Testing with Claude for Desktop

To test your MCP server with Claude for Desktop, follow these steps:

1. **Install the MCP server**: Ensure you have your MCP server running locally or on a remote host.
2. **Set up your authentication token** (see above)
3. **Configure Claude for Desktop**: Open the configuration file for Claude and add your MCP server details:
    ```
    code ~/Library/Application\ Support/Claude/claude_desktop_config.json
    ```
   For local server:
    ```json
    {
      "mcpServers": {
        "festi-mcp": {
            "command": "node",
            "args": [
                "[PROJECT_PATH]/plugins/MCPServer/mcp-http-bridge.js"
            ],
            "env": {
                "MCP_TOKEN": "[YOUR-PERSONAL-TOKEN]"
            }
        }
      }
    }
    ```

   For remote server with token:
    ```json
    {
      "mcpServers": {
        "festi-mcp": {
            "command": "node",
            "args": [
                "[PROJECT_PATH]/plugins/MCPServer/mcp-http-bridge.js",
                "--protocol",
                "http",
                "--host",
                "[HOST]",
                "--port",
                "[PORT]"
            ],
            "env": {
                "MCP_TOKEN": "[YOUR-PERSONAL-TOKEN]"
            }
        }
      }
    }
    ```

   For HTTPS server:
    ```json
    {
      "mcpServers": {
        "festi-mcp": {
            "command": "node",
            "args": [
                "[PROJECT_PATH]/plugins/MCPServer/mcp-http-bridge.js",
                "--protocol",
                "https",
                "--host",
                "[HOST]",
                "--port",
                "[PORT]"
            ],
            "env": {
                "MCP_TOKEN": "[YOUR-PERSONAL-TOKEN]"
            }
        }
      }
    }
    ```

   For server with custom path:
    ```json
    {
      "mcpServers": {
        "festi-mcp": {
            "command": "node",
            "args": [
                "[PROJECT_PATH]/plugins/MCPServer/mcp-http-bridge.js",
                "--protocol",
                "http",
                "--host",
                "[HOST]",
                "--port",
                "[PORT]",
                "--path",
                "/rpc/v1/"
            ],
            "env": {
                "MCP_TOKEN": "[YOUR-PERSONAL-TOKEN]"
            }
        }
      }
    }
    ```

   When installed via Claude's MCP catalog, it will ask the user to provide a token:
    ```json
    {
        "mcpServers": {
            "festi-mcp": {
                "command": "node",
                "args": [
                    "[PROJECT_PATH]/plugins/MCPServer/mcp-http-bridge.js",
                    "--host",
                    "[HOST]",
                    "--port",
                    "[PORT]",
                    "--protocol",
                    "https"
                ],
                "env": {
                    "MCP_TOKEN": "${FESTI_MCP_TOKEN}"
                }
            }
        }
    }
    ```

Logs:

```
tail -n 20 -F ~/Library/Logs/Claude/mcp-server-festi-mcp.log
```

## Testing

### Manual Testing

Test the bridge directly:
```bash
node mcp-http-bridge.js
```

Test with custom options:
```bash
MCP_TOKEN=test-token node mcp-http-bridge.js --protocol http --host localhost --port 8080
```

Test with custom path:
```bash
MCP_TOKEN=test-token node mcp-http-bridge.js --protocol http --host localhost --port 8080 --path /rpc/v1/
```

```
http://localhost:8080/?rawRequest={%22method%22:%22initialize%22,%22params%22:{%22protocolVersion%22:%222024-11-05%22,%22capabilities%22:{},%22clientInfo%22:{%22name%22:%22claude-ai%22,%22version%22:%220.1.0%22}},%22jsonrpc%22:%222.0%22,%22id%22:0}

http://localhost:8080/?rawRequest=[{%22method%22:%22notifications/initialized%22,%22jsonrpc%22:%222.0%22}]
```



```
2025-05-31T23:30:43.570Z [info] [festi-mcp] Message from client: {"method":"notifications/initialized","jsonrpc":"2.0"}
2025-05-31T23:30:43.571Z [info] [festi-mcp] Message from client: {"method":"tools/list","params":{},"jsonrpc":"2.0","id":1}
2025-05-31T23:30:43.571Z [info] [festi-mcp] Message from client: {"method":"tools/list","params":{},"jsonrpc":"2.0","id":2}
2025-05-31T23:30:43.571Z [info] [festi-mcp] Message from client: {"method":"resources/list","params":{},"jsonrpc":"2.0","id":3}

{"method":"prompts/list","params":{},"jsonrpc":"2.0","id":4}

{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":4,"reason":"Error: MCP error -32001: Request timed out"}}
```

## tools/list permission override

By default `tools/list` shows a tool only when the caller's base (session) role is granted the
backing RPC method. A project plugin can override that decision — applying its own permission
logic — via `PrepareToolsListEvent`. MCPServer stays domain-agnostic and only offers the hook.

A listener that sets the granted tool identifiers and calls `setOverride(true)` takes over
completely: MCPServer renders exactly those tools and runs no permission check of its own. If no
listener overrides (or a listener throws), MCPServer keeps its default base-role filtering.

`Plugins\MCPServer\Domain\Event\PrepareToolsListEvent` (extends `FestiEvent`):

- `getRpcMethods(): array` — candidate tools as `toolIdentifier => MCPRpcMethodValuesObject`
- `setGrantedIdentifiers(string[])` / `setOverride(bool)` — the identifiers to render, and the
  flag that hands the decision to the listener

```php
$this->addEventListener(
    PrepareToolsListEvent::TYPE,
    function (PrepareToolsListEvent $event) {
        $grantedIdentifiers = /* decide from $event->getRpcMethods() */;

        $event->setGrantedIdentifiers($grantedIdentifiers);
        $event->setOverride(true);
    }
);
```

## Bearer-token authentication (OAuth 2.1)

MCPServer recognises `Authorization: Bearer <token>` on inbound MCP requests and delegates validation to a project plugin via the typed event `MCPBearerTokenLoginEvent`. The plugin itself stays IdP-agnostic — Google, Microsoft Entra, Okta, and so on all live in their own project plugin.

The entry point is `MCPServerPlugin::signInByRpcByToken()` — it overrides `RpcPlugin::signInByRpcByToken()`, dispatches `MCPBearerTokenLoginEvent` when an `Authorization: Bearer` header is present, and falls back to `parent::signInByRpcByToken()` for the legacy `X-Authorization` / GET-token path when no bearer is sent or no listener authenticates the event.

### Event contract

`Plugins\MCPServer\Domain\Event\MCPBearerTokenLoginEvent` (extends `FestiEvent`):

- `public const TYPE = 'mcpserver.on_bearer_token_login'`
- `getToken(): string` — raw bearer value (without the `Bearer ` prefix)
- `isAuthenticated(): bool` — whether a listener has already authenticated this bearer
- `markAuthenticated(): void` — call after a successful sign-in. Throws `SystemException` if a previous listener already marked the event, so a misconfigured second listener fails loudly instead of racing.

### Project listener (example stub)

```php
$this->addEventListener(
    MCPBearerTokenLoginEvent::TYPE,
    function (MCPBearerTokenLoginEvent $event) {
        $token = $event->getToken();

        // …validate $token against your IdP…
        // …resolve to a local user…
        // …sign them in via $this->core->getSystemPlugin()->signinByToken($accessToken)…

        $event->markAuthenticated();
    }
);
```

If no listener marks the event authenticated, MCPServer leaves the request un-authenticated and `RpcPlugin` raises a 401. The legacy `X-Authorization: <MCP_TOKEN>` path is independent and is not intercepted by this hook.

**Listeners must be synchronous** and call `markAuthenticated()` before returning — `MCPServerPlugin::signInByRpcByToken()` reads `isAuthenticated()` immediately after `dispatchEvent()` returns.

When no listener marks the bearer authenticated, MCPServer responds with **HTTP 401** plus the `WWW-Authenticate: Bearer resource_metadata="…"` header (when `mcp_host` is set — the resource-metadata URL is built from `mcp_host` rather than the request's `Host` header so it can be pinned independently). The 401 is required by the MCP Authorization spec — it's what triggers Claude Desktop / ChatGPT / Inspector to begin OAuth discovery on first connection. The override lives in `MCPServerPlugin::onException()` so the legacy 500 mapping from `RpcPlugin::onException()` doesn't override the auth-failure status.

## Further documentation

- [QA: Describing RPC methods for LLMs](https://festi.dev/8.0/Plugins/MCPServer/docs/QA/index.md) — How to describe RPC methods and parameters so LLMs (and other MCP clients) can fill tool arguments correctly (typed params, `params_types`, `JsonProperty`, `rpc_methods` in DB).
- [MCP Claude Server Registration Checklist](https://festi.dev/8.0/Plugins/MCPServer/docs/McpClaudeServerRegistrationChecklist/index.md) — Detailed checklist and reference for preparing and submitting your MCP server to the Claude Connectors Directory.
- [Writing tools with required annotations](https://festi.dev/8.0/Plugins/MCPServer/docs/ToolAnnotations/index.md) — How to add `#[McpReadOnlyAttribute]` / `#[McpDestructiveAttribute]` (or the legacy `@mcpReadOnly` / `@mcpDestructive` doc-tags) to your RPC methods so tools meet Claude catalog safety requirements.
- [Transport: Streamable HTTP (stateless subset)](https://festi.dev/8.0/Plugins/MCPServer/docs/Transport/index.md) — What the MCP endpoint serves and refuses, protocol version negotiation and validation, batching per revision, the event-stream answer, `Origin` validation and CORS, the request size cap, and what a host `mcp.php` and nginx location must do.
- [Tool result size limit (25,000 tokens)](https://festi.dev/8.0/Plugins/MCPServer/docs/ToolResultSizeLimit/index.md) — How to prevent oversized tool results: pagination, limit params, filtering, and server-side safeguard.
