Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 5 additions & 7 deletions src/Capability/Discovery/SchemaGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@

use Mcp\Capability\Attribute\McpTool;
use Mcp\Capability\Attribute\Schema;
use Mcp\Capability\Registry\InjectableParameters;
use Mcp\Exception\BadMethodCallException;
use Mcp\Exception\InvalidArgumentException;
use Mcp\Server\RequestContext;
use phpDocumentor\Reflection\DocBlock\Tags\Param;

/**
Expand Down Expand Up @@ -528,12 +528,10 @@ private function parseParametersInfo(\ReflectionMethod|\ReflectionFunction $refl
foreach ($reflection->getParameters() as $rp) {
$reflectionType = $rp->getType();

if ($reflectionType instanceof \ReflectionNamedType && !$reflectionType->isBuiltin()) {
$typeName = $reflectionType->getName();

if (is_a($typeName, RequestContext::class, true)) {
continue;
}
if ($reflectionType instanceof \ReflectionNamedType && !$reflectionType->isBuiltin()
&& InjectableParameters::supports($reflectionType->getName())
) {
continue;
}

$paramName = $rp->getName();
Expand Down
63 changes: 63 additions & 0 deletions src/Capability/Registry/InjectableParameters.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?php

/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Mcp\Capability\Registry;

use Mcp\Server\ClientGateway;
use Mcp\Server\RequestContext;

/**
* Single source of truth for handler parameter types the SDK injects itself.
*
* Both schema generation (which must exclude these parameters from the
* published inputSchema) and argument preparation (which must inject them)
* read this list, so the two cannot drift apart.
*
* @internal
*/
final class InjectableParameters
{
private const TYPES = [
RequestContext::class,
ClientGateway::class,
];

private function __construct()
{
}

public static function supports(string $typeName): bool
{
foreach (self::TYPES as $type) {
if (is_a($typeName, $type, true)) {
return true;
}
}

return false;
}

/**
* @param array<string, mixed> $arguments the raw argument bag including the internal "_session" and "_request" entries
*/
public static function resolve(string $typeName, array $arguments): ?object
{
if (RequestContext::class === $typeName && isset($arguments['_session'], $arguments['_request'])) {
return new RequestContext($arguments['_session'], $arguments['_request']);
}

if (ClientGateway::class === $typeName && isset($arguments['_session'])) {
return new ClientGateway($arguments['_session']);
}

return null;
}
}
14 changes: 3 additions & 11 deletions src/Capability/Registry/ReferenceHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@

use Mcp\Exception\InvalidArgumentException;
use Mcp\Exception\RegistryException;
use Mcp\Server\ClientGateway;
use Mcp\Server\RequestContext;
use Mcp\Server\Session\SessionInterface;
use Psr\Container\ContainerInterface;

Expand Down Expand Up @@ -106,15 +104,9 @@ private function prepareArguments(\ReflectionFunctionAbstract $reflection, array
// Check if parameter is a special injectable type
$type = $parameter->getType();
if ($type instanceof \ReflectionNamedType && !$type->isBuiltin()) {
$typeName = $type->getName();

if (RequestContext::class === $typeName && isset($arguments['_session'], $arguments['_request'])) {
$finalArgs[$paramPosition] = new RequestContext($arguments['_session'], $arguments['_request']);
continue;
}

if (ClientGateway::class === $typeName && isset($arguments['_session'])) {
$finalArgs[$paramPosition] = new ClientGateway($arguments['_session']);
$injected = InjectableParameters::resolve($type->getName(), $arguments);
if (null !== $injected) {
$finalArgs[$paramPosition] = $injected;
continue;
}
}
Expand Down
16 changes: 16 additions & 0 deletions tests/Integration/Fixture/sampling.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Mcp\Exception\ClientException;
use Mcp\Schema\Content\TextContent;
use Mcp\Server;
use Mcp\Server\ClientGateway;
use Mcp\Server\RequestContext;
use Mcp\Server\Transport\StdioTransport;

Expand All @@ -38,5 +39,20 @@ static function (RequestContext $context, string $text): string {
name: 'summarize',
description: 'Summarizes text by asking the client to sample.',
)
->addTool(
static function (ClientGateway $client, string $text): string {
try {
$result = $client->sample($text, maxTokens: 64);
} catch (ClientException $e) {
return $e->getMessage();
}

assert($result->content instanceof TextContent);

return sprintf('%s said: %s', $result->model, $result->content->text);
},
name: 'summarize_via_gateway',
description: 'Summarizes text through a directly injected gateway.',
)
->build()
->run(new StdioTransport());
23 changes: 23 additions & 0 deletions tests/Integration/SamplingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,29 @@ public function testPromptReachesTheClient(): void
$this->assertSame(64, $seen[0]->maxTokens);
}

#[TestDox('a gateway parameter is injected, not published in the schema')]
public function testGatewayParameterIsInjectedNotPublished(): void
{
$client = $this->connect('sampling', $this->clientSampling());

$tool = null;
foreach ($client->listTools()->tools as $candidate) {
if ('summarize_via_gateway' === $candidate->name) {
$tool = $candidate;
}
}

$this->assertNotNull($tool);
$this->assertArrayNotHasKey('client', $tool->inputSchema['properties']);
$this->assertArrayHasKey('text', $tool->inputSchema['properties']);
$this->assertSame(['text'], $tool->inputSchema['required']);

$result = $client->callTool('summarize_via_gateway', ['text' => 'a long report']);

$this->assertInstanceOf(TextContent::class, $result->content[0]);
$this->assertSame('test-model said: a long report', $result->content[0]->text);
}

#[TestDox('a client that cannot sample refuses instead of stalling the tool')]
public function testClientWithoutSamplingRefuses(): void
{
Expand Down
9 changes: 9 additions & 0 deletions tests/Unit/Capability/Discovery/SchemaGeneratorFixture.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@

use Mcp\Capability\Attribute\McpTool;
use Mcp\Capability\Attribute\Schema;
use Mcp\Server\ClientGateway;
use Mcp\Server\RequestContext;
use Mcp\Tests\Unit\Fixtures\Enum\BackedIntEnum;
use Mcp\Tests\Unit\Fixtures\Enum\BackedStringEnum;
use Mcp\Tests\Unit\Fixtures\Enum\UnitEnum;
Expand Down Expand Up @@ -519,6 +521,13 @@ public function withParameterNamedRequest(string $_request): void
{
}

/**
* @param string $query The search query
*/
public function withInjectableParameters(string $query, ClientGateway $gateway, RequestContext $context, int $limit = 10): void
{
}

// ===== OUTPUT SCHEMA FIXTURES =====
#[McpTool(
outputSchema: [
Expand Down
11 changes: 11 additions & 0 deletions tests/Unit/Capability/Discovery/SchemaGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,17 @@ public function testInfersParameterTypeAsAnyIfOnlyConstraintsAreGiven(): void
$this->assertEquals(['inferredParam'], $schema['required']);
}

public function testExcludesInjectableParameterTypesFromSchema(): void
{
$method = new \ReflectionMethod(SchemaGeneratorFixture::class, 'withInjectableParameters');
$schema = $this->schemaGenerator->generate($method);
$this->assertArrayNotHasKey('gateway', $schema['properties']);
$this->assertArrayNotHasKey('context', $schema['properties']);
$this->assertEquals(['type' => 'string', 'description' => 'The search query'], $schema['properties']['query']);
$this->assertEquals(['type' => 'integer', 'default' => 10], $schema['properties']['limit']);
$this->assertEquals(['query'], $schema['required']);
}

public static function methodsWithForbiddenParameter(): array
{
return [
Expand Down
26 changes: 26 additions & 0 deletions tests/Unit/Capability/Registry/ReferenceHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,32 @@ public function read(string $uri, ClientGateway $gateway): mixed
$this->assertInstanceOf(ClientGateway::class, $resourceHandler->receivedGateway);
}

public function testHandleInjectsClientGatewayIntoReflectedHandler(): void
{
$session = $this->createMock(SessionInterface::class);
$session->method('getId')->willReturn(Uuid::v4());

$handler = new class {
public ?ClientGateway $receivedGateway = null;

public function search(string $query, ClientGateway $gateway): string
{
$this->receivedGateway = $gateway;

return 'found: '.$query;
}
};

$result = (new ReferenceHandler())->handle(new ElementReference([$handler, 'search']), [
'_session' => $session,
'_request' => new \stdClass(),
'query' => 'foo',
]);

$this->assertSame('found: foo', $result);
$this->assertInstanceOf(ClientGateway::class, $handler->receivedGateway);
}

public function testHandleStillReflectsOrdinaryClosuresAndDoesNotInjectArgumentBag(): void
{
$session = $this->createMock(SessionInterface::class);
Expand Down