feat: Add output schema support to MCP tools (#153)

This commit is contained in:
Sule-Balogun Olanrewaju 2026-01-11 20:14:48 +00:00 • committed by GitHub
commit c0938a19bd
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 605 additions and 55 deletions

View file

@ -222,6 +222,7 @@ class Discoverer
$name = $instance->name ?? ('__invoke' === $methodName ? $classShortName : $methodName);
$description = $instance->description ?? $this->docBlockParser->getSummary($docBlock) ?? null;
$inputSchema = $this->schemaGenerator->generate($method);
$outputSchema = $this->schemaGenerator->generateOutputSchema($method);
$tool = new Tool(
$name,
$inputSchema,
@ -229,6 +230,7 @@ class Discoverer
$instance->annotations,
$instance->icons,
$instance->meta,
$outputSchema,
);
$tools[$name] = new ToolReference($tool, [$className, $methodName], false);
++$discoveredCount['tools'];

View file

@ -11,6 +11,7 @@
namespace Mcp\Capability\Discovery;
use Mcp\Capability\Attribute\McpTool;
use Mcp\Capability\Attribute\Schema;
use Mcp\Exception\InvalidArgumentException;
use Mcp\Server\RequestContext;
@ -81,6 +82,27 @@ class SchemaGenerator
return $this->buildSchemaFromParameters($parametersInfo, $methodSchema);
}
/**
* Generates a JSON Schema object (as a PHP array) for a method's or function's return type.
*
* Only returns an outputSchema if explicitly provided in the McpTool attribute.
* Per MCP spec, outputSchema should only be present when explicitly provided.
*
* @return array<string, mixed>|null
*/
public function generateOutputSchema(\ReflectionMethod|\ReflectionFunction $reflection): ?array
{
// Only return outputSchema if explicitly provided in McpTool attribute
$mcpToolAttrs = $reflection->getAttributes(McpTool::class, \ReflectionAttribute::IS_INSTANCEOF);
if ($mcpToolAttrs) {
$mcpToolInstance = $mcpToolAttrs[0]->newInstance();
return $mcpToolInstance->outputSchema;
}
return null;
}
/**
* Extracts method-level or function-level Schema attribute.
*