PHP code example of code-wheel / mcp-http-security
1. Go to this page and download the library: Download code-wheel/mcp-http-security library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
code-wheel / mcp-http-security example snippets
use CodeWheel\McpSecurity\ApiKey\ApiKeyManager;
use CodeWheel\McpSecurity\ApiKey\Storage\FileStorage;
use CodeWheel\McpSecurity\Clock\SystemClock;
use CodeWheel\McpSecurity\Config\SecurityConfig;
use CodeWheel\McpSecurity\Middleware\SecurityMiddleware;
use CodeWheel\McpSecurity\Validation\RequestValidator;
// 1. Setup API Key Manager
$storage = new FileStorage('/var/data/mcp-api-keys.json');
$clock = new SystemClock();
$apiKeyManager = new ApiKeyManager(
storage: $storage,
clock: $clock,
pepper: getenv('MCP_API_KEY_PEPPER') ?: '',
);
// 2. Create a key
$result = $apiKeyManager->createKey(
label: 'Claude Code',
scopes: ['read', 'write'],
ttlSeconds: 86400 * 30, // 30 days
);
echo "API Key: {$result['api_key']}\n"; // Show once, store securely
// 3. Setup Request Validator
$validator = new RequestValidator(
allowedIps: ['127.0.0.1', '10.0.0.0/8'],
allowedOrigins: ['localhost', '*.example.com'],
);
// 4. Create Middleware
$middleware = new SecurityMiddleware(
apiKeyManager: $apiKeyManager,
requestValidator: $validator,
responseFactory: new HttpFactory(), // Any PSR-17 factory
config: new SecurityConfig(
$apiKey = $apiKeyManager->validate($tokenFromRequest);
if ($apiKey === null) {
// Invalid or expired
}
if ($apiKey->hasScope('write')) {
// Allow write operation
}
$apiKeyManager->revokeKey('abc123def456');
use CodeWheel\McpSecurity\ApiKey\Storage\FileStorage;
$storage = new FileStorage('/var/data/api-keys.json');
use CodeWheel\McpSecurity\ApiKey\Storage\PdoStorage;
$pdo = new PDO('mysql:host=localhost;dbname=app', 'user', 'pass');
$storage = new PdoStorage($pdo, 'mcp_api_keys');
$storage->ensureTable(); // Creates table if needed
use CodeWheel\McpSecurity\ApiKey\Storage\ArrayStorage;
$storage = new ArrayStorage();
use CodeWheel\McpSecurity\ApiKey\Storage\StorageInterface;
class RedisStorage implements StorageInterface
{
public function getAll(): array { /* ... */ }
public function setAll(array $keys): void { /* ... */ }
public function get(string $keyId): ?array { /* ... */ }
public function set(string $keyId, array $data): void { /* ... */ }
public function delete(string $keyId): bool { /* ... */ }
}
use CodeWheel\McpSecurity\Validation\IpValidator;
$validator = new IpValidator([
'127.0.0.1', // Single IP
'10.0.0.0/8', // CIDR range
'192.168.0.0/16', // Private network
'::1', // IPv6 localhost
]);
$validator->isAllowed('10.5.3.2'); // true
$validator->isAllowed('8.8.8.8'); // false
use CodeWheel\McpSecurity\Validation\OriginValidator;
$validator = new OriginValidator([
'localhost',
'example.com',
'*.example.com', // Wildcard: foo.example.com, bar.example.com
]);
$validator->isAllowed('api.example.com'); // true
$validator->isAllowed('evil.com'); // false
use CodeWheel\McpSecurity\Validation\RequestValidator;
$validator = new RequestValidator(
allowedIps: ['127.0.0.1', '10.0.0.0/8'],
allowedOrigins: ['localhost', '*.myapp.com'],
);
// With PSR-7 request
$validator->validate($request); // Throws ValidationException if invalid
$validator->isValid($request); // Returns bool
use CodeWheel\McpSecurity\Config\SecurityConfig;
$config = new SecurityConfig(
ization', // Bearer token header
apiKeyHeader: 'X-MCP-Api-Key', // Alternative header
scopesAttribute: 'mcp.scopes', // Request attribute for scopes
keyAttribute: 'mcp.key', // Request attribute for key info
silentFail: true, // Return 404 instead of 401/403
);
use CodeWheel\McpSecurity\Exception\AuthenticationException;
use CodeWheel\McpSecurity\Exception\AuthorizationException;
use CodeWheel\McpSecurity\Exception\RateLimitException;
use CodeWheel\McpSecurity\Exception\ValidationException;
try {
$middleware->process($request, $handler);
} catch (AuthenticationException $e) {
// 401 - Invalid or missing API key
} catch (AuthorizationException $e) {
// 403 - Insufficient scopes
echo "Required: " . implode(', ', $e->
$app->add($securityMiddleware);
// In a service provider
$this->app->singleton(SecurityMiddleware::class, function ($app) {
return new SecurityMiddleware(/* ... */);
});
// In Kernel.php
protected $middleware = [
\CodeWheel\McpSecurity\Middleware\SecurityMiddleware::class,
];
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.