用 ThinkPHP 构建 MCP Server:让 AI Agent 安全调用企业 PHP 业务系统
拥抱 2026 模型上下文协议(Model Context Protocol),零重写盘活存量 PHP 业务资产
MCP(Model Context Protocol,模型上下文协议) 已经成为连接 AI 智能体与外部业务系统的事实标准。过去每接入一个新 AI 客户端,后端都要写一套定制胶水接口;而现在只要让现有的 ThinkPHP 系统暴露标准 MCP 端点,无论是桌面端 AI 助手还是企业内部 Agent,都能以统一协议安全发现并调用你的业务工具。
一、ThinkPHP 作为 MCP Server 的架构蓝图
在企业落地中,最稳妥的模式是将 ThinkPHP 的 Service 层按最小权限原则映射为 MCP Tools(工具) 与 Resources(只读资源):
tools/list:向 AI 返回系统开放的工具清单及其 JSON Schema 参数定义;tools/call:接收 AI 发起的结构化调用请求,经鉴权与 Validate 强校验后执行具体 PHP 业务并返回结果;- 安全守卫(Guardrails):所有写操作强制二次确认或仅开放只读查询与工单草稿创建,绝不向模型暴露原生 SQL 执行入口。
二、ThinkPHP MCP 控制器核心实现示例
<?php
namespace app\controller;
use app\service\OrderQueryService;
use think\Request;
use think\Response;
class McpServer
{
public function handle(Request $request, OrderQueryService $orders): Response
{
$rpc = $request->post();
$id = isset($rpc['id']) ? $rpc['id'] : null;
$method = isset($rpc['method']) ? (string)$rpc['method'] : '';
$params = isset($rpc['params']) && is_array($rpc['params']) ? $rpc['params'] : [];
if ($method === 'tools/list') {
return json([
'jsonrpc' => '2.0',
'id' => $id,
'result' => [
'tools' => [
[
'name' => 'query_order_status',
'description' => '按订单号查询当前物流与支付状态(只读)',
'inputSchema' => [
'type' => 'object',
'properties' => [
'order_no' => ['type' => 'string', 'description' => '订单编号,如 ORD20261125001'],
],
'required' => ['order_no'],
],
],
],
],
]);
}
if ($method === 'tools/call') {
$toolName = isset($params['name']) ? $params['name'] : '';
$args = isset($params['arguments']) ? $params['arguments'] : [];
if ($toolName === 'query_order_status') {
$orderNo = isset($args['order_no']) ? trim((string)$args['order_no']) : '';
if (!preg_match('/^ORD[0-9]{10,20}$/', $orderNo)) {
return $this->rpcError($id, -32602, '订单号格式不合法');
}
$info = $orders->findByOrderNo($orderNo, (int)$request->tenantId);
return json([
'jsonrpc' => '2.0',
'id' => $id,
'result' => [
'content' => [
['type' => 'text', 'text' => json_encode($info, JSON_UNESCAPED_UNICODE)],
],
],
]);
}
}
return $this->rpcError($id, -32601, 'Method not found');
}
private function rpcError($id, int $code, string $message): Response
{
return json([
'jsonrpc' => '2.0',
'id' => $id,
'error' => ['code' => $code, 'message' => $message],
]);
}
}
三、生产安全治理三道防线
- 租户隔离注入:
tenantId/uid必须由 ThinkPHP 中间件从 Bearer Token 解析后注入 Request,绝不允许由 AI 传入的arguments决定数据归属,防止提示词注入导致的越权读取; - 全链路审计日志:将每次
tools/call的调用者、工具名、脱敏参数、耗时与返回状态写入审计表,便于追踪 Agent 行为; - 超时与熔断:对耗时较长的外部依赖设置严格超时,避免慢接口拖垮整个智能体任务链。
版权与技术声明:本文由 PHP技术博客 (www.zoneself.org) 原创整理与验证,欢迎技术交流学习,转载请注明出处。代码示例请结合目标 PHP 版本与生产环境安全规范部署。