Token导航 LogoToken导航TokenDH.com
laravel-Claude logo
运维云端未说明官方来源来源级核验

laravel-Claude

MCP Server

为Laravel框架提供的Anthropic Claude AI服务官方封装,支持多模态交互、工具执行和高级对话管理。

工具数

0

提示词数

0

GitHub Stars

4

资源数

0
PHPClaude云端部署Claude

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

作者 / 组织

goldenpathdigital

提供方

goldenpathdigital

最后核验

2026/5/17 20:22

快速接入

先看主来源和安装命令,再打开仓库或文档;下面只保留这个条目的关键接入事实。

详细介绍

Laravel克劳德

![CI](https://github.com/goldenpathdigital/laravel-claude/actions/workflows/ci.yml) ](https://packagist.org/packages/goldenpathdigital/laravel-claude) ](https://packagist.org/packages/goldenpathdigital/laravel-claude) ![License](https://packagist.org/packages/goldenpathdigital/laravel-claude)

Laravel官方包装器 Anthropic PHP SDK 具有一流的MCP连接器支持。

目录

- 直接访问SDK - API型号 - 消息批处理API - 文件API - 令牌计数 - 成本估算 - 流利的对话构建器 - 多回合对话 - 图像支持 - PDF文档 - 高级参数 - 流媒体 - 工具 - MCP连接器 - 延伸思维 - 快速缓存 - 结构化输出

- 可用断言 - 伪造工具使用响应

- 队列集成

特性

  • 官方SDK --包装材料 anthropic-ai/sdk,不是自定义HTTP实现
  • Laravel原生 --外观、配置、服务提供商、自动发现
  • 流利的API --可链接的对话构建器,支持图像
  • API全面覆盖 --消息、模型、批处理、文件、令牌计数
  • 工具系统 --使用流畅的构建器和自动执行循环定义工具
  • MCP连接器 --第一个Laravel包 主控程序 客户端支持
  • 流媒体 --Laravel事件的实时流媒体
  • 延伸思维 --使用预算令牌访问Claude的推理过程
  • 快速缓存 --通过缓存系统提示降低成本
  • 结构化输出 --响应的JSON模式验证
  • 队列集成 --使用重试处理在后台作业中处理对话
  • 测试工具Claude::fake() 使用断言助手

需求

  • PHP 8.2+
  • Laravel 10、11或12

安装

composer require goldenpathdigital/laravel-claude

发布配置文件:

php artisan vendor:publish --tag=claude-config

将API密钥添加到 .env:

ANTHROPIC_API_KEY=your-api-key

用法

直接访问SDK

use GoldenPathDigital\Claude\Facades\Claude;

$response = Claude::messages()->create([
    'model' => 'claude-sonnet-4-5-20250929',
    'max_tokens' => 1024,
    'messages' => [
        ['role' => 'user', 'content' => 'Hello, Claude!'],
    ],
]);

echo $response->content[0]->text;

API型号

列出并检索可用的Claude型号:

use GoldenPathDigital\Claude\Facades\Claude;

// List all available models
$models = Claude::models()->list([]);

foreach ($models as $model) {
    echo $model->id . ' - ' . $model->display_name;
}

// Get a specific model
$model = Claude::models()->retrieve('claude-sonnet-4-5-20250929', []);
echo $model->display_name;

消息批处理API

批量处理多条消息以实现高吞吐量工作负载:

use GoldenPathDigital\Claude\Facades\Claude;

// Create a batch
$batch = Claude::batches()->create([
    'requests' => [
        [
            'custom_id' => 'request-1',
            'params' => [
                'model' => 'claude-sonnet-4-5-20250929',
                'max_tokens' => 1024,
                'messages' => [['role' => 'user', 'content' => 'Hello!']],
            ],
        ],
        [
            'custom_id' => 'request-2',
            'params' => [
                'model' => 'claude-sonnet-4-5-20250929',
                'max_tokens' => 1024,
                'messages' => [['role' => 'user', 'content' => 'How are you?']],
            ],
        ],
    ],
]);

// Check batch status
$batch = Claude::batches()->retrieve($batch->id, []);
echo $batch->processing_status;

// List all batches
$batches = Claude::batches()->list([]);

// Get results when complete
$results = Claude::batches()->results($batch->id, []);

// Cancel a batch
Claude::batches()->cancel($batch->id, []);

// Delete a completed batch
Claude::batches()->delete($batch->id, []);

文件API

管理上传到Anthropic API的文件:

use GoldenPathDigital\Claude\Facades\Claude;

// List all files
$files = Claude::files()->list([]);

foreach ($files as $file) {
    echo $file->id . ' - ' . $file->filename;
}

// Get file metadata
$file = Claude::files()->retrieveMetadata($fileId, []);

// Delete a file
Claude::files()->delete($fileId, []);

令牌计数

在发送请求之前计算令牌:

use GoldenPathDigital\Claude\Facades\Claude;

$count = Claude::countTokens([
    'model' => 'claude-sonnet-4-5-20250929',
    'messages' => [
        ['role' => 'user', 'content' => 'Hello, how are you?'],
    ],
]);

echo "Input tokens: " . $count->input_tokens;

成本估算

根据代币使用情况估计API成本:

use GoldenPathDigital\Claude\Facades\Claude;

// Estimate cost for a request
$cost = Claude::estimateCost(
    inputTokens: 1000,
    outputTokens: 500,
    model: 'claude-sonnet-4-5-20250929'
);

echo $cost->formatted();        // "$0.010500"
echo $cost->total();            // 0.0105
echo $cost->inputCost;          // 0.003
echo $cost->outputCost;         // 0.0075
echo $cost->totalTokens();      // 1500

// Get pricing for a model
$pricing = Claude::getPricingForModel('claude-opus-4-20250514');
// ['input' => 15.00, 'output' => 75.00] (per million tokens)

流利的对话构建器

use GoldenPathDigital\Claude\Facades\Claude;

$response = Claude::conversation()
    ->model('claude-sonnet-4-5-20250929')
    ->system('You are a helpful assistant.')
    ->user('What is the capital of France?')
    ->maxTokens(1024)
    ->temperature(0.7)
    ->send();

echo $response->content[0]->text;

多回合对话

$conversation = Claude::conversation()
    ->system('You are a code reviewer.')
    ->user('Review this function: function add($a, $b) { return $a + $b; }')
    ->send();

// Continue the conversation
$followUp = $conversation
    ->user('What about error handling?')
    ->send();

图像支持

发送图像供Claude分析:

use GoldenPathDigital\Claude\Facades\Claude;

// Base64 encoded image
$imageData = base64_encode(file_get_contents('photo.jpg'));

$response = Claude::conversation()
    ->image($imageData, 'image/jpeg', 'What is in this image?')
    ->send();

// URL-based image
$response = Claude::conversation()
    ->imageUrl('https://example.com/image.png', 'Describe this diagram')
    ->send();

// Complex multi-modal messages
$response = Claude::conversation()
    ->user([
        ['type' => 'text', 'text' => 'Compare these two images:'],
        ['type' => 'image', 'source' => ['type' => 'url', 'url' => 'https://example.com/img1.jpg']],
        ['type' => 'image', 'source' => ['type' => 'url', 'url' => 'https://example.com/img2.jpg']],
    ])
    ->send();

PDF文档

分析PDF文档:

use GoldenPathDigital\Claude\Facades\Claude;

$pdfData = base64_encode(file_get_contents('contract.pdf'));

$response = Claude::conversation()
    ->pdf($pdfData, 'Extract the key terms from this contract')
    ->send();

高级参数

使用其他参数微调模型行为:

use GoldenPathDigital\Claude\Facades\Claude;

$response = Claude::conversation()
    ->model('claude-sonnet-4-5-20250929')
    ->system('You are a helpful assistant.')
    ->user('Write a haiku about coding.')
    ->maxTokens(1024)
    ->temperature(0.7)
    ->topK(40)                          // Limit token selection pool
    ->topP(0.9)                         // Nucleus sampling threshold
    ->stopSequences(['END', '---'])     // Custom stop sequences
    ->metadata(['user_id' => 'user_123']) // Usage tracking
    ->serviceTier('auto')               // 'auto' or 'standard_only'
    ->send();

流媒体

通过回调支持实时流式响应:

use GoldenPathDigital\Claude\Facades\Claude;

Claude::conversation()
    ->system('You are a helpful assistant.')
    ->user('Write a short poem about Laravel.')
    ->stream(function (string $text) {
        echo $text; // Output each chunk as it arrives
    });

或者收听Laravel活动:

use GoldenPathDigital\Claude\Events\StreamChunk;
use GoldenPathDigital\Claude\Events\StreamComplete;

Event::listen(StreamChunk::class, function (StreamChunk $event) {
    broadcast(new NewChunk($event->text)); // Real-time to frontend
});

Event::listen(StreamComplete::class, function (StreamComplete $event) {
    logger()->info('Stream complete', [
        'input_tokens' => $event->usage['input_tokens'],
        'output_tokens' => $event->usage['output_tokens'],
    ]);
});

工具

使用流畅的构建器定义工具,并让Claude自动执行它们:

use GoldenPathDigital\Claude\Facades\Claude;
use GoldenPathDigital\Claude\Tools\Tool;

$weatherTool = Tool::make('get_weather')
    ->description('Get the current weather for a location')
    ->parameter('location', 'string', 'City name', required: true)
    ->parameter('units', 'string', 'Temperature units', enum: ['celsius', 'fahrenheit'])
    ->handler(function (array $input) {
        // Call your weather API here
        return ['temperature' => 72, 'condition' => 'sunny'];
    });

$response = Claude::conversation()
    ->system('You are a helpful assistant with access to weather data.')
    ->user('What is the weather in Paris?')
    ->tools([$weatherTool])
    ->maxSteps(5) // Maximum tool execution iterations
    ->send();

echo $response->content[0]->text;
// "The current weather in Paris is 72 degrees and sunny."

MCP连接器

连接到远程 MCP服务器 通过Anthropic的连接器API:

use GoldenPathDigital\Claude\Facades\Claude;
use GoldenPathDigital\Claude\MCP\McpServer;

// Define MCP server inline
$zapier = McpServer::url('https://mcp.zapier.com/api/mcp/s/xxx')
    ->name('zapier')
    ->token(env('ZAPIER_MCP_TOKEN'))
    ->allowTools(['gmail_send', 'slack_post']); // Optional: restrict tools

$response = Claude::conversation()
    ->system('You are an assistant that can send emails and Slack messages.')
    ->user('Send a Slack message to #general saying hello')
    ->mcp([$zapier])
    ->send();

或者使用配置中预先配置的服务器:

// config/claude.php
'mcp_servers' => [
    'zapier' => [
        'url' => env('ZAPIER_MCP_URL'),
        'token' => env('ZAPIER_MCP_TOKEN'),
        'allowed_tools' => ['gmail_send', 'slack_post'],
    ],
],

// Usage - reference by config key
$response = Claude::conversation()
    ->mcp(['zapier']) // Loads from config
    ->user('Send an email to john@example.com')
    ->send();

延伸思维

为复杂问题启用克劳德的推理过程:

use GoldenPathDigital\Claude\Facades\Claude;

$response = Claude::conversation()
    ->model('claude-sonnet-4-5-20250929')
    ->extendedThinking(budgetTokens: 10000)
    ->user('Analyze the pros and cons of microservices vs monolith architecture.')
    ->send();

// Access thinking blocks in response
foreach ($response->content as $block) {
    if ($block->type === 'thinking') {
        logger()->info('Claude reasoning:', ['thinking' => $block->thinking]);
    }
    if ($block->type === 'text') {
        echo $block->text;
    }
}

快速缓存

通过缓存大型系统提示来降低成本:

use GoldenPathDigital\Claude\Facades\Claude;
use GoldenPathDigital\Claude\ValueObjects\CachedContent;

// Cache a long system prompt
$systemPrompt = CachedContent::make($longDocumentation)
    ->cache('ephemeral');

$response = Claude::conversation()
    ->system($systemPrompt)
    ->user('Summarize the key points.')
    ->send();

// Check cache usage in response
// $response->usage->cache_creation_input_tokens
// $response->usage->cache_read_input_tokens

结构化输出

获取根据JSON模式验证的响应:

use GoldenPathDigital\Claude\Facades\Claude;
use GoldenPathDigital\Claude\Conversation\ConversationBuilder;

$schema = [
    'type' => 'object',
    'properties' => [
        'parties' => ['type' => 'array', 'items' => ['type' => 'string']],
        'effective_date' => ['type' => 'string'],
        'term_length' => ['type' => 'string'],
        'key_obligations' => ['type' => 'array', 'items' => ['type' => 'string']],
    ],
    'required' => ['parties', 'effective_date'],
];

$response = Claude::conversation()
    ->user('Extract the key terms from this contract: ...')
    ->schema($schema, 'contract_terms')
    ->send();

// Extract structured data from the tool_use response
$data = ConversationBuilder::extractStructuredOutput($response);

echo $data['parties'][0]; // "Acme Corp"
echo $data['effective_date']; // "2025-01-01"

测试

使用 Claude::fake() 在测试中模拟响应:

use GoldenPathDigital\Claude\Facades\Claude;
use GoldenPathDigital\Claude\Testing\FakeResponse;

public function test_chatbot_responds()
{
    Claude::fake([
        FakeResponse::make('Hello! How can I help you today?'),
    ]);

    $response = Claude::conversation()
        ->user('Hi there!')
        ->send();

    $this->assertEquals('Hello! How can I help you today?', $response->content[0]->text);

    // Assert the request was sent
    Claude::assertSent(function (array $request) {
        return $request['messages'][0]['content'] === 'Hi there!';
    });
}

可用断言

// Assert any request was sent
Claude::assertSent();

// Assert with callback
Claude::assertSent(function (array $request) {
    return str_contains($request['messages'][0]['content'], 'hello');
});

// Assert nothing was sent
Claude::assertNothingSent();

// Assert specific count
Claude::assertSentCount(3);

伪造工具使用响应

Claude::fake([
    FakeResponse::withToolUse('get_weather', ['location' => 'Paris']),
    FakeResponse::make('The weather in Paris is sunny and 72 degrees.'),
]);

配置

// config/claude.php

return [
    // Authentication
    'api_key' => env('ANTHROPIC_API_KEY'),
    'auth_token' => env('ANTHROPIC_AUTH_TOKEN'),  // Alternative OAuth authentication
    
    // Custom endpoint (for proxies or enterprise)
    'base_url' => env('ANTHROPIC_BASE_URL'),
    
    // Defaults
    'default_model' => env('CLAUDE_MODEL', 'claude-sonnet-4-5-20250929'),
    'timeout' => env('CLAUDE_TIMEOUT', 30),
    'max_retries' => 2,
    
    // Beta features (auto-enabled headers)
    'beta_features' => [
        'mcp_connector' => true,
        'extended_thinking' => true,
        'prompt_caching' => true,
        'structured_outputs' => true,
    ],
    
    // Pre-configured MCP servers
    'mcp_servers' => [
        'zapier' => [
            'url' => env('ZAPIER_MCP_URL'),
            'token' => env('ZAPIER_MCP_TOKEN'),
        ],
    ],
    
    // Pricing per million tokens (for cost estimation)
    'pricing' => [
        'claude-opus' => ['input' => 15.00, 'output' => 75.00],
        'claude-sonnet' => ['input' => 3.00, 'output' => 15.00],
        'claude-haiku' => ['input' => 0.25, 'output' => 1.25],
    ],
];

队列集成

使用自动重试处理在后台作业中处理对话:

use GoldenPathDigital\Claude\Facades\Claude;
use GoldenPathDigital\Claude\Jobs\ProcessConversation;
use GoldenPathDigital\Claude\Contracts\ConversationCallback;
use Anthropic\Messages\Message;
use Throwable;

// Create a callback to handle the result
class DocumentAnalysisCallback implements ConversationCallback
{
    public function onSuccess(Message $response, array $context = []): void
    {
        $document = Document::find($context['document_id']);
        $document->update([
            'summary' => $response->content[0]->text,
            'analyzed_at' => now(),
        ]);
    }

    public function onFailure(Throwable $exception, array $context = []): void
    {
        Log::error('Document analysis failed', [
            'document_id' => $context['document_id'],
            'error' => $exception->getMessage(),
        ]);
    }
}

// Dispatch the conversation to the queue
ProcessConversation::dispatch(
    conversation: Claude::conversation()
        ->system('You are a document analyst. Summarize the key points.')
        ->user($documentContent),
    callbackClass: DocumentAnalysisCallback::class,
    context: ['document_id' => $document->id]
)->onQueue('ai');

该工作包括:

  • 自动重试:3次尝试,后退10秒
  • 回调模式:在专门的课程中处理成功/失败
  • 上下文传递:将任意数据传递给回调函数
  • 全功能支持:MCP服务器、扩展思维、缓存、结构化输出

备注:无法为队列作业序列化具有自定义处理程序(闭包)的工具。使用MCP服务器或基本对话进行排队处理。

运行测试

composer test

代码的风格

composer format

许可证

MIT许可证。看 许可证 了解详情。

目录标签

目录标签

PHPClaude云端部署本地部署AI集成Laravel扩展对话系统多模态处理工具执行

支持客户端

Claude

接入字段

传输方式(transport,传输协议)

未说明

鉴权方式(authType,认证方式)

oauth

工具数量(toolCount,工具数)

0

资源数量(resourceCount,资源数)

0

提示词数量(promptCount,提示词数)

0

权限和风险

未说明oauth部署方式未说明

接入前请确认传输方式、认证方式和部署位置,并根据实际工具能力限制访问范围。

安装前确认

不要直接授予不必要的文件、网络或账号权限;先核对安装命令和配置内容。

仍需确认:installCommand

来源信息

继续浏览同类 MCP