laravel Ai MCP的使用

MCP(Model Context Protocol)模型上下文协议,统一标准化大模型交互请求格式,可对接自建 MCP 服务、第三方 AI 网关。
Laravel 无官方 MCP 驱动,下面实现通用 MCP 客户端封装,包含同步对话、流式输出、工具调用示例。

composer require guzzlehttp/guzzle

MCP AI 服务配置

MCP_API_URL=http://127.0.0.1:8080/mcp/v1/chat
MCP_API_KEY=sk-mcp-demo-123456
MCP_MODEL=deepseek-v3
MCP_TIMEOUT=60

env('MCP_API_URL'), 'key' => env('MCP_API_KEY'), 'model' => env('MCP_MODEL'), 'timeout' => env('MCP_TIMEOUT', 60), ]; ``` config = config('mcp'); $this->client = new Client([ 'timeout' => $this->config['timeout'], 'headers' => [ 'Authorization' => 'Bearer ' . $this->config['key'], 'Content-Type' => 'application/json', ] ]); } /** * 同步对话 - 一次性返回完整AI结果 * @param array $messages 对话消息 [["role"=>"user","content"=>"xxx"]] * @param array $context 业务上下文 * @param float $temperature 随机性 0~1 * @return array */ public function chatSync(array $messages, array $context = [], float $temperature = 0.7): array { $payload = [ 'model' => $this->config['model'], 'messages' => $messages, 'context' => $context, 'stream' => false, 'temperature' => $temperature, 'max_tokens' => 1024 ]; try { $response = $this->client->post($this->config['url'], ['json' => $payload]); return json_decode($response->getBody()->getContents(), true); } catch (\Exception $e) { Log::error("MCP同步请求失败:" . $e->getMessage(), $payload); throw new \Exception("AI服务调用异常:" . $e->getMessage()); } } /** * 流式输出对话(SSE) */ public function chatStream(array $messages, array $context = []): \GuzzleHttp\Psr7\Stream { $payload = [ 'model' => $this->config['model'], 'messages' => $messages, 'context' => $context, 'stream' => true, 'temperature' => 0.7 ]; $response = $this->client->post($this->config['url'], [ 'json' => $payload, 'stream' => true ]); return $response->getBody(); } } ```
posted @ 2026-07-12 16:07  xp创客  阅读(2)  评论(0)    收藏  举报