hunzhiwange/mcp-sdk-php
Composer 安装命令:
composer require hunzhiwange/mcp-sdk-php
包简介
Model Context Protocol SDK for PHP
README 文档
README
English | 中文
This package provides a PHP implementation of the Model Context Protocol, allowing applications to provide context for LLMs in a standardized way. It separates the concerns of providing context from the actual LLM interaction.
Overview
This PHP SDK implements the full MCP specification, making it easy to:
- Build MCP clients that can connect to any MCP server
- Create MCP servers that expose resources, prompts and tools
- Use standard transports like stdio and HTTP
- Handle all MCP protocol messages and lifecycle events
Based on the official Python SDK for the Model Context Protocol.
This SDK is primarily targeted at developers working on frontier AI integration solutions. Some functionality may be incomplete and implementations should undergo thorough testing and security review by experienced developers prior to production use.
Installation
You can install the package via composer:
composer require logiscape/mcp-sdk-php
Requirements
- PHP 8.1 or higher
- ext-curl
- ext-json
- ext-pcntl (optional, recommended for CLI environments)
- monolog/monolog (optional, used by example clients/servers for logging)
Basic Usage
Creating an MCP Server
Here's a complete example of creating an MCP server that provides prompts:
<?php // A basic example server with a list of prompts for testing require 'vendor/autoload.php'; use Mcp\Server\Server; use Mcp\Server\ServerRunner; use Mcp\Types\Prompt; use Mcp\Types\PromptArgument; use Mcp\Types\PromptMessage; use Mcp\Types\ListPromptsResult; use Mcp\Types\TextContent; use Mcp\Types\Role; use Mcp\Types\GetPromptResult; use Mcp\Types\GetPromptRequestParams; // Create a server instance $server = new Server('example-server'); // Register prompt handlers $server->registerHandler('prompts/list', function($params) { $prompt = new Prompt( name: 'example-prompt', description: 'An example prompt template', arguments: [ new PromptArgument( name: 'arg1', description: 'Example argument', required: true ) ] ); return new ListPromptsResult([$prompt]); }); $server->registerHandler('prompts/get', function(GetPromptRequestParams $params) { $name = $params->name; $arguments = $params->arguments; if ($name !== 'example-prompt') { throw new \InvalidArgumentException("Unknown prompt: {$name}"); } // Get argument value safely $argValue = $arguments ? $arguments->arg1 : 'none'; $prompt = new Prompt( name: 'example-prompt', description: 'An example prompt template', arguments: [ new PromptArgument( name: 'arg1', description: 'Example argument', required: true ) ] ); return new GetPromptResult( messages: [ new PromptMessage( role: Role::USER, content: new TextContent( text: "Example prompt text with argument: $argValue" ) ) ], description: 'Example prompt' ); }); // Create initialization options and run server $initOptions = $server->createInitializationOptions(); $runner = new ServerRunner($server, $initOptions); $runner->run();
Save this as example_server.php
Creating an MCP Client
Here's how to create a client that connects to the example server:
<?php // A basic example client that connects to example_server.php and outputs the prompts require 'vendor/autoload.php'; use Mcp\Client\Client; use Mcp\Client\Transport\StdioServerParameters; use Mcp\Types\TextContent; // Create server parameters for stdio connection $serverParams = new StdioServerParameters( command: 'php', // Executable args: ['example_server.php'], // File path to the server env: null // Optional environment variables ); // Create client instance $client = new Client(); try { echo("Starting to connect\n"); // Connect to the server using stdio transport $session = $client->connect( commandOrUrl: $serverParams->getCommand(), args: $serverParams->getArgs(), env: $serverParams->getEnv() ); echo("Starting to get available prompts\n"); // List available prompts $promptsResult = $session->listPrompts(); // Output the list of prompts if (!empty($promptsResult->prompts)) { echo "Available prompts:\n"; foreach ($promptsResult->prompts as $prompt) { echo " - Name: " . $prompt->name . "\n"; echo " Description: " . $prompt->description . "\n"; echo " Arguments:\n"; if (!empty($prompt->arguments)) { foreach ($prompt->arguments as $argument) { echo " - " . $argument->name . " (" . ($argument->required ? "required" : "optional") . "): " . $argument->description . "\n"; } } else { echo " (None)\n"; } } } else { echo "No prompts available.\n"; } } catch (\Exception $e) { echo "Error: " . $e->getMessage() . "\n"; exit(1); } finally { // Close the server connection if (isset($client)) { $client->close(); } }
Save this as example_client.php and run it:
php example_client.php
Advanced Examples
The "examples" directory includes addtional clients and servers for both the STDIO and HTTP transports. All examples are designed to run in the same directory where you installed the SDK.
Some examples use monolog for logging, which can be installed via composer:
composer require monolog/monolog
MCP Web Client
The "webclient" directory includes a web-based application for testing MCP servers. It was designed to demonstrate a MCP client capable of running in a typical web hosting environment.
Setting Up The Web Client
To setup the web client, upload the contents of "webclient" to a web directory, such as public_html on a cPanel server. Ensure that the MCP SDK for PHP is installed in that same directory by running the Composer command found in the Installation section of this README.
Using The Web Client
Once the web client has been uploaded to a web directory, navigate to index.php to open the interface. To connect to the included MCP test server, enter php in the Command field and test_server.php in the Arguments field and click Connect to Server. The interface allows you to test Prompts, Tools, and Resources. There is also a Debug Panel allowing you to view the JSON-RPC messages being sent between the Client and Server.
Web Client Notes And Limitations
This MCP Web Client is intended for developers to test MCP servers, and it is not recommended to be made publicly accessible as a web interface without additional testing for security, error handling, and resource management.
While MCP is usually implemented as a stateful session protocol, a typical PHP-based web hosting environment restricts long-running processes. To maximize compatibility, the MCP Web Client will initialize a new connection between the client and server for every request, and then close that connection after the request is complete.
Documentation
For detailed information about the Model Context Protocol, visit the official documentation.
2025-03-26 Implementation
We are currently implementing the 2025-03-26 revision of the MCP Spec.
Completed Tasks
- Implement protocol version negotiation
- Create classes for new spec features
- Add support for JSON-RPC batching
- Implement HTTP transport
To Do
- Implement authorization framework based on OAuth 2.1
- Explore the feasibility of supporting SSE in PHP environments
Credits
This PHP SDK was developed by:
- Josh Abbott
- Claude 3.5 Sonnet (Anthropic AI model)
Additional debugging and refactoring done by Josh Abbott using OpenAI ChatGPT o1 pro mode.
Based on the original Python SDK for the Model Context Protocol.
License
The MIT License (MIT). Please see License File for more information.
hunzhiwange/mcp-sdk-php 适用场景与选型建议
hunzhiwange/mcp-sdk-php 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 0 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 05 月 07 日, 在 PHP 生态内属于活跃度较高的组件。
我们在过去多个企业项目中使用过 hunzhiwange/mcp-sdk-php 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 hunzhiwange/mcp-sdk-php 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
统计信息
- 总下载量: 0
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 20
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-05-07