Remove ability to use parameter name _session and _request (#206)

* Remove ability to use parameter name _session and _request

These are reserved for internal use. This will fix https://github.com/modelcontextprotocol/php-sdk/issues/168

* fix cs

* add changelog

* add test
This commit is contained in:
Tobias Nyholm 2025-12-27 23:16:44 +01:00 • committed by GitHub
commit abd0ddf13d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 40 additions and 0 deletions

View file

@ -2,6 +2,11 @@
All notable changes to `mcp/sdk` will be documented in this file.
0.2.2
-----
* Throw exception when trying to inject parameter with the unsupported names `$_session` or `$_request`.
0.2.1
-----

View file

@ -12,6 +12,7 @@
namespace Mcp\Capability\Discovery;
use Mcp\Capability\Attribute\Schema;
use Mcp\Exception\InvalidArgumentException;
use Mcp\Server\RequestContext;
use phpDocumentor\Reflection\DocBlock\Tags\Param;
@ -421,6 +422,9 @@ class SchemaGenerator
}
$paramName = $rp->getName();
if (\in_array(strtolower($paramName), ['_session', '_request'], true)) {
throw new InvalidArgumentException(\sprintf('Handler method "%s::%s" has parameter named "%s" which is not allowed. Please change the name of that parameter.', $reflection->class, $reflection->name, $paramName));
}
$paramTag = $paramTags['$'.$paramName] ?? null;
$typeString = $this->getParameterTypeString($rp, $paramTag);

View file

@ -412,4 +412,16 @@ class SchemaGeneratorFixture
$inferredParam,
): void {
}
public function withParameterNamedSession(string $_session): void
{
}
public function withParameterNamedSessionWithWeirdCase(string $_sesSion): void
{
}
public function withParameterNamedRequest(string $_request): void
{
}
}

View file

@ -13,6 +13,8 @@ namespace Mcp\Tests\Unit\Capability\Discovery;
use Mcp\Capability\Discovery\DocBlockParser;
use Mcp\Capability\Discovery\SchemaGenerator;
use Mcp\Exception\InvalidArgumentException;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
final class SchemaGeneratorTest extends TestCase
@ -327,4 +329,21 @@ final class SchemaGeneratorTest extends TestCase
$this->assertEquals(['description' => 'Some parameter', 'minLength' => 3], $schema['properties']['inferredParam']);
$this->assertEquals(['inferredParam'], $schema['required']);
}
public static function methodsWithForbiddenParameter(): array
{
return [
['withParameterNamedSession'],
['withParameterNamedSessionWithWeirdCase'],
['withParameterNamedRequest'],
];
}
#[DataProvider('methodsWithForbiddenParameter')]
public function testGenerateWithForbiddenParameterNames(string $methodName)
{
$method = new \ReflectionMethod(SchemaGeneratorFixture::class, $methodName);
$this->expectException(InvalidArgumentException::class);
$this->schemaGenerator->generate($method);
}
}