<?php
namespace boru\ai\Mcp;

use boru\ai\Runtime\ToolDefinition;
use boru\ai\Runtime\ToolExecutionContext;

class McpToolAdapter
{
    public static function toToolDefinition($serverName, array $tool, McpToolInvokerInterface $invoker)
    {
        if (!isset($tool['name']) || !is_string($tool['name']) || trim($tool['name']) === '') {
            throw new \InvalidArgumentException('MCP tool metadata requires a name');
        }

        $name = $tool['name'];
        $description = isset($tool['description']) && is_string($tool['description']) ? $tool['description'] : '';
        $schema = isset($tool['inputSchema']) && is_array($tool['inputSchema']) ? $tool['inputSchema'] : array(
            'type' => 'object',
            'properties' => array(),
        );

        $definition = new ToolDefinition();
        $definition->name($name)
            ->description($description)
            ->schema($schema)
            ->metadata(array(
                'mcp' => true,
                'mcp_server' => $serverName,
                'mcp_tool' => $name,
            ))
            ->callback(function (array $arguments, ToolExecutionContext $context = null, ToolDefinition $definition = null) use ($invoker, $serverName, $name) {
                return $invoker->invoke($serverName, $name, $arguments);
            });

        return $definition;
    }
}
