跳转到主要内容

工具

Copilot CLI 的内置工具默认已启用。这里可以指定的是自定义工具。

基本使用方式

在 SessionConfig 的 tools 中指定工具的定义。 Tool::define() 是与其他语言版本的 defineTool 类似的辅助函数。 parameters 可以使用 Laravel 自身在 Laravel MCP 中使用的 JsonSchema。也可以不使用 JsonSchema,直接指定数组。
use Illuminate\Support\Facades\Artisan;
use Illuminate\JsonSchema\JsonSchema;
use Revolution\Copilot\Contracts\CopilotSession;
use Revolution\Copilot\Facades\Copilot;
use Revolution\Copilot\Types\SessionConfig;
use Revolution\Copilot\Types\Tool;
use Revolution\Copilot\Types\ToolResultObject;

use function Laravel\Prompts\{info, note, spin, warning};

Artisan::command('copilot:tools', function () {
    $facts = [
        'PHP' => 'A popular general-purpose scripting language that is especially suited to web development.',
        'Laravel' => 'A web application framework with expressive, elegant syntax.',
    ];

    $parameters = JsonSchema::object(
        properties: [
            'topic' => JsonSchema::string()
                ->description('Topic to look up (e.g., "PHP", "Laravel")')
                ->required(),
        ],
    )->toArray();

    $config = new SessionConfig(
        tools: [
            Tool::define(
                name: 'lookup_fact',
                description: 'Returns a fun fact about a given topic.',
                parameters: $parameters,
                handler: function (array $params, array $invocation) use ($facts): array {
                    $topic = $params['topic'] ?? '';

                    $fact = $facts[$topic] ?? null;

                    if (! $fact) {
                        return new ToolResultObject(
                            textResultForLlm: "No fact stored for {$topic}.",
                            resultType: 'failure',
                            sessionLog: "lookup_fact: missing topic {$topic}",
                            toolTelemetry: [],
                        );
                    }

                    return new ToolResultObject(
                        textResultForLlm: $fact,
                        resultType: 'success',
                        sessionLog: "lookup_fact: served {$topic}",
                        toolTelemetry: [],
                    );
                },
                overridesBuiltInTool: false,
                skipPermission: false, // 设为 true 时无需权限确认即可执行
                defer: 'auto', // 控制是始终预加载工具,还是延迟加载(通过工具搜索来延迟加载)。为 `"auto"` 时,工具会被延迟加载,并通过工具搜索显示。为 `"never"` 时,工具始终被预加载。可选。默认是 `"auto"`。
            ),
        ],
    );

    Copilot::start(function (CopilotSession $session) {
        info('Starting Copilot with tools: '.$session->id());

        $prompt = 'You can call the lookup_fact tool. Use lookup_fact to tell me something about Laravel.';

        warning($prompt);

        $response = spin(
            callback: fn () => $session->sendAndWait($prompt),
            message: 'Copilot thinking...',
        );

        note($response->content());
    }, config: $config);
});

skipPermission

指定 skipPermission: true 后,该工具可以在没有权限确认的情况下执行。
Tool::define(
    name: 'read_only_lookup',
    description: 'Read-only data lookup.',
    parameters: $parameters,
    handler: fn ($params) => ['result' => 'data'],
    skipPermission: true,
),

$invocation

工具处理器的第二个参数 $invocation 会传入以下字段。
[
    'sessionId'  => '...',
    'toolCallId' => '...',
    'toolName'   => 'lookup_fact',
    'arguments'  => [...], // 工具参数(与 $params 内容相同)
    // 仅当启用 OpenTelemetry 时包含
    'traceparent' => '...', // W3C Trace Context traceparent
    'tracestate'  => '...', // W3C Trace Context tracestate
]

协议详情

在 Protocol v3(当前默认)中,工具调用不再作为 JSON-RPC 请求,而是作为会话事件(external_tool.requested)广播。SDK 会内部处理该事件,并通过 session.tools.handlePendingToolCall RPC 进行响应。 SessionConfig 的使用方式不变。 只要向 tools 传入定义,协议差异会由 SDK 吸收。

MCP CallToolResult 的转换

要将 MCP 服务器工具的结果(CallToolResult)转换为 Copilot SDK 的 ToolResultObject,请使用 McpCallToolResult::convert()。 MCP 工具的结果是 text、image、resource 等 content 块的数组,而 Copilot SDK 期望的是 ToolResultObject 格式,因此需要转换。
use Revolution\Copilot\Support\McpCallToolResult;

// MCP CallToolResult 格式
$mcpResult = [
    'content' => [
        ['type' => 'text', 'text' => 'File contents here'],
        ['type' => 'image', 'data' => 'base64...', 'mimeType' => 'image/png'],
    ],
    'isError' => false,
];

// 转换为 Copilot SDK ToolResultObject 格式
$toolResult = McpCallToolResult::convert($mcpResult);
// $toolResult->textResultForLlm => 'File contents here'
// $toolResult->resultType => 'success'
// $toolResult->binaryResultsForLlm => [['data' => 'base64...', 'mimeType' => 'image/png', 'type' => 'image']]
最新信息请参考 GitHub 仓库
最后修改于 2026年7月13日