mcpField
S
Symfony Mcp Server

Symfony Mcp Server

本地服务
github.com/klapaudius生产力3216 周前更新

关于 Symfony Mcp Server

Symfony MCP Server 是一个 Symfony 包,用于构建基于 Model Context Protocol 的服务端。它通过 SSE 与 StreamableHTTP 提供通信,面向需要在 Symfony 应用中暴露工具、提示词与资源的开发者。

主要功能

  1. 01工具、提示词与资源支持
  2. 02Sampling 机制,允许工具调用 AI 模型
  3. 03长任务的进度通知
  4. 04文本、图像、音频与资源多种输出
  5. 05基于 Pub/Sub 的适配器架构

适用场景

  1. 01将 Symfony 业务逻辑暴露给 AI 客户端
  2. 02构建带有 AI 推理步骤的工具
  3. 03为长时间运行的操作提供实时进度反馈

MCP 相关

该包作为 MCP 服务运行,通过 SSE 与 StreamableHTTP 端点向 Claude Desktop 等 MCP 客户端提供工具、提示词与资源。当前版本暂不支持 Discovery、Roots 与 Elicitation。

配置

本地服务的配置在各客户端中通用,复制后粘贴到客户端的 MCP 配置文件即可。

mcp.json · 通用配置
{
"mcpServers": {
"symfony": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/inspector"
]
}
}
}
启动命令npx -y @modelcontextprotocol/inspector

本地服务需要在你的电脑上安装运行环境(如 Node.js 18+)。各客户端的配置文件位置不同,请参考客户端文档。

安装包
npm@modelcontextprotocol/inspector

工具

还没有获取到工具列表

本地服务需要在你的电脑上运行后才能读取工具,维护者暂未提供工具列表。

详细介绍

Symfony MCP 服务

一个强大的 Symfony 软件包,可无缝构建模型上下文协议服务,并 构建智能 AI Agent。
将您的 Symfony 应用转变为强大的 AI 驱动系统

构建状态 覆盖率 许可证 最新稳定版本 总下载量

🤖 在 Symfony 应用中释放 AI Agent 的强大力量

Symfony MCP Server 让您能够构建智能、具备上下文感知能力的 AI Agent,它们可以推理、做出决策,并与应用的业务逻辑交互。通过实现模型上下文协议(MCP),您的 Symfony 应用将成为用于复杂 AI 驱动自动化和智能功能的平台。

🎯 为什么使用 Symfony MCP Server 构建 Agent?

将静态工具转变为智能 Agent:

  • 🧠 AI 驱动的推理:工具可以在执行过程中咨询大模型,做出明智决策
  • 🔄 动态适应:Agent 会根据上下文和实时分析调整行为
  • 💡 复杂问题求解:将复杂任务拆解,并在 AI 的协助下逐步解决
  • 🎨 创意生成:生成能够随用户需求演进的内容和解决方案

企业级安全性:

  • 🔒 安全传输方式:在生产环境中使用 StreamableHTTP 和 SSE,而不是 STDIO
  • 🛡️ 受保护的 API:在开放 AI 能力的同时确保内部系统安全
  • 🎛️ 精细化控制:管理各个层级的身份验证、授权和访问权限

主要功能:

  • 🛠️ 工具:创建强大的可执行函数,供大模型调用以与您的应用交互
  • 💬 提示词:定义对话开场白和模板,引导 AI 的行为与交互
  • 📚 资源:开放结构化数据和文档,供 AI 阅读和推理
  • 🧠 采样:让工具能够在执行过程中咨询 AI 模型,以便智能决策
  • 📊 进度流:为长时间运行的操作实时发送进度通知
  • 🎨 多模态结果:支持工具返回文本、图像、音频和资源
  • 🔌 灵活架构:采用基于适配器的设计,并使用 Pub/Sub 消息传递,支持可扩展部署

🚀 Agent 优先功能

🧪 采样:Agent 式行为的核心(v1.4.0+)

将您的工具转变为能够思考和推理的自主 Agent:

class IntelligentAnalyzer implements SamplingAwareToolInterface
{
    private SamplingClient $samplingClient;

    public function execute(array $arguments): ToolResultInterface
    {
        // Check if sampling is available
        if ($this->samplingClient !== null && $this->samplingClient->isEnabled()) {
            try {
                // Let AI analyze and reason about complex data
                $response = $this->samplingClient->createTextRequest(
                    "Analyze this data and suggest optimizations: {$arguments['data']}",
                    new ModelPreferences(
                        [['name' => 'claude-3-sonnet']],
                        0.3, // costPriority
                        0.8, // intelligencePriority
                        0.2  // speedPriority
                    ),
                    'You are a data analysis expert.',
                    2000
                );
                
                // Execute actions based on AI reasoning
                return new TextToolResult($response->getContent()->getText());
            } catch (\Exception $e) {
                // Fallback to basic analysis
                return new TextToolResult('Basic analysis: Data structure appears valid.');
            }
        }
        
        return new TextToolResult('Advanced analysis requires AI capabilities.');
    }
    
    public function setSamplingClient(SamplingClient $samplingClient): void
    {
        $this->samplingClient = $samplingClient;
    }
}
🛠️ 工具系统:构建 Agent 的基石

创建强大的工具,供 AI Agent 编排使用:

  • StreamableToolInterface:为长时间运行的操作实时更新进度
  • 多结果支持:返回文本、图像、音频或资源
  • 进度通知:在复杂的 Agent 操作期间向用户通报进度
  • 动态工具发现:Agent 可根据功能发现并使用工具
🎭 用于 Agent 行为的提示词工程

通过复杂的提示词系统定义 Agent 的个性和行为:

  • 上下文感知提示词:根据应用状态引导 Agent 行为
  • 多模态支持:支持文本、图像、音频和基于资源的提示词
  • 动态提示词生成:根据用户交互进行调整的提示词
📚 用于 Agent 记忆的资源管理

让 Agent 访问结构化知识:

  • 动态资源加载:Agent 可以访问并推理你的数据
  • 基于模板的资源:根据上下文即时生成资源
  • 多提供方支持:文件系统、数据库、API 或自定义提供方

🎯 真实场景中的 Agent 示例

🔍 智能代码审查 Agent
class CodeReviewAgent implements SamplingAwareToolInterface
{
    private SamplingClient $samplingClient;

    public function execute(array $arguments): ToolResultInterface
    {
        // Check if sampling is available
        if ($this->samplingClient !== null && $this->samplingClient->isEnabled()) {
            try {
                // AI analyzes code for patterns, security, and best practices
                $review = $this->samplingClient->createTextRequest(
                    "Review this code for security vulnerabilities, performance issues, and suggest improvements: {$arguments['code']}",
                    new ModelPreferences(
                        [['name' => 'claude-3-sonnet']],
                        0.2, // costPriority
                        0.8, // intelligencePriority
                        0.2  // speedPriority
                    ),
                    'You are a senior code reviewer with expertise in security and performance.',
                    2000
                );
                
                // Generate actionable recommendations
                return new TextToolResult($this->formatReview($review->getContent()->getText()));
            } catch (\Exception $e) {
                // Fallback to basic analysis
                return new TextToolResult('Basic code review: Structure appears valid.');
            }
        }
        
        return new TextToolResult('Advanced code review requires AI capabilities.');
    }
    
    public function setSamplingClient(SamplingClient $samplingClient): void
    {
        $this->samplingClient = $samplingClient;
    }
}
📊 数据分析 Agent
class DataInsightAgent implements SamplingAwareToolInterface, StreamableToolInterface
{
    private SamplingClient $samplingClient;
    private ?ProgressNotifierInterface $progressNotifier = null;

    public function execute(array $arguments): ToolResultInterface
    {
        // Check if sampling is available
        if ($this->samplingClient !== null && $this->samplingClient->isEnabled()) {
            try {
                // Multi-step reasoning process
                $steps = [
                    'Identify patterns and anomalies',
                    'Generate statistical insights',
                    'Create visualizations',
                    'Recommend actions'
                ];
                $this->progressNotifier?->sendProgress(
                    progress: 0,
                    total: count($steps)+1,
                    message: "Analyzing dataset..."
                );
                
                $insights = [];
                foreach ($steps as $i => $step) {
                    $response = $this->samplingClient->createTextRequest(
                        "$step for this data: {$arguments['data']}",
                        new ModelPreferences(
                            [['name' => 'claude-3-sonnet']],
                            0.2, // costPriority
                            0.8, // intelligencePriority
                            0.2  // speedPriority
                        ),
                        'You are a data analysis expert.',
                        2000
                    );
                    $insights[] = $response->getContent()->getText();
                    $this->progressNotifier?->sendProgress(
                        progress: $i+1,
                        total: count($steps)+1,
                        message: $step
                    );
                }
                
                return new TextToolResult($this->compileReport($insights));
            } catch (\Exception $e) {
                return new TextToolResult('Basic data analysis: Dataset appears well-formed.');
            }
        }
        
        return new TextToolResult('Advanced data analysis requires AI capabilities.');
    }
    
    public function setSamplingClient(SamplingClient $samplingClient): void
    {
        $this->samplingClient = $samplingClient;
    }
    
    public function setProgressNotifier(ProgressNotifierInterface $progressNotifier): void
    {
        $this->progressNotifier = $progressNotifier;
    }
}
🤝 客户支持 Agent
class SupportAgent implements SamplingAwareToolInterface
{
    private SamplingClient $samplingClient;

    public function execute(array $arguments): ToolResultInterface
    {
        // Check if sampling is available
        if ($this->samplingClient !== null && $this->samplingClient->isEnabled()) {
            try {
                // Load customer context
                $context = $this->loadCustomerHistory($arguments['customer_id']);
                
                // AI determines best response strategy
                $response = $this->samplingClient->createTextRequest(
                    "Customer issue: {$arguments['issue']}\nHistory: $context\nDetermine the best resolution approach.",
                    new ModelPreferences(
                        [['name' => 'claude-3-sonnet']],
                        0.2, // costPriority
                        0.8, // intelligencePriority
                        0.2  // speedPriority
                    ),
                    'You are an expert customer support agent.',
                    2000
                );
                
                // Send back the strategy for user approval
                return new TextToolResult($response->getContent()->getText());
            } catch (\Exception $e) {
                return new TextToolResult('Standard support response: We will review your issue and respond within 24 hours.');
            }
        }
        
        return new TextToolResult('Personalized support requires AI capabilities.');
    }
    
    public function setSamplingClient(SamplingClient $samplingClient): void
    {
        $this->samplingClient = $samplingClient;
    }
}

🚀 快速开始:构建你的第一个 Agent

1. 要求
  • PHP >=8.2
  • Symfony >=6.4
2. 安装 Symfony MCP 服务
创建配置文件 config/packages/klp_mcp_server.yaml 并粘贴以下内容:
```yaml
klp_mcp_server:
    enabled: true
    server:
        name: 'My MCP Server'
        version: '1.0.0'
    default_path: 'mcp'
    ping:
        enabled: true  # Read the warning section in the default configuration file before disable it
        interval: 30
    server_providers: ['streamable_http','sse']
    sse_adapter: 'cache'
    adapters:
        cache:
            prefix: 'mcp_sse_'
            ttl: 100
    tools:
        - KLP\KlpMcpServer\Services\ToolService\Examples\CodeAnalyzerTool     # Agentic tool sample
        - KLP\KlpMcpServer\Services\ToolService\Examples\HelloWorldTool
        - KLP\KlpMcpServer\Services\ToolService\Examples\ProfileGeneratorTool
        - KLP\KlpMcpServer\Services\ToolService\Examples\SearchResultsTool
        - KLP\KlpMcpServer\Services\ToolService\Examples\StreamingDataTool
        - KLP\KlpMcpServer\Services\ToolService\Examples\VersionCheckTool
    prompts:
        - KLP\KlpMcpServer\Services\PromptService\Examples\CodeReviewPrompt   # Agentic prompt sample
        - KLP\KlpMcpServer\Services\PromptService\Examples\HelloWorldPrompt
    resources:
        - KLP\KlpMcpServer\Services\ResourceService\Examples\HelloWorldResource
        - KLP\KlpMcpServer\Services\ResourceService\Examples\ProjectSummaryResource # Agentic resource sample
    resources_templates:
        - KLP\KlpMcpServer\Services\ResourceService\Examples\DynamicAnalysisResource # Agentic resource template sample
        - KLP\KlpMcpServer\Services\ResourceService\Examples\McpDocumentationResource
```

如需更详细的说明,可以打开默认配置文件 此处链接。

通过 Composer 安装软件包:
composer require klapaudius/symfony-mcp-server
在 config/routes.yaml 中添加路由
klp_mcp_server:
    resource: '@KlpMcpServerBundle/Resources/config/routes.php'
    type: php

全部完成! 完成此设置后,你的项目将包含 3 个新的 API 端点:

  • 面向 MCP 客户端的流式端点:GET /{default_path}/sse
  • 请求提交端点:POST /{default_path}/messages
  • 可流式传输的 HTTP 端点:GET|POST /{default_path}
Docker 设置(可选)

该项目包含用于开发的 Docker 设置,其中包括 Nginx、带有 Redis 扩展的 PHP-FPM,以及 Redis 服务器。

有关如何设置和使用 Docker 容器的详细说明,请参阅开发指南。

3. 创建你的第一个工具
# Generate a new tool
php bin/console make:mcp-tool MyCustomTool

# Test your tool locally
php bin/console mcp:test-tool MyCustomTool --input='{"task":"analyze this code"}'
4. 使用 Inspector 进行可视化

你可以使用 Model Context Protocol Inspector 来可视化和测试 MCP 工具:

# Run the MCP Inspector without installation
npx @modelcontextprotocol/inspector node build/index.js

通常会在 localhost:6274 打开一个 Web 界面。要测试 MCP 服务:

5. 连接 AI 客户端

现在,你的 Agent 可以通过以下方式访问:

  • 🤖 Claude Desktop / Claude.ai
  • 🧠 自定义 AI 应用
  • 🔗 任何兼容 MCP 的客户端

🏗️ 面向 Agent 构建者的架构

安全的 Agent 通信
  • StreamableHTTP:直接、安全地在 Agent 与客户端之间通信
  • SSE (Server-Sent Events):为长时间运行的 Agent 任务提供实时更新
  • No STDIO:符合企业安全要求,不暴露系统
可扩展的 Agent 基础设施
  • Pub/Sub Messaging:同时处理多个 Agent 会话
  • Redis/Cache Adapters:水平扩展你的 Agent 平台
  • Progress Streaming:为复杂的 Agent 操作提供实时反馈
Agent 开发工具
  • MCP Inspector:可视化并调试 Agent 行为
  • Test Commands:快速开发和测试 Agent
当前可用的 MCP 功能
资源提示词工具发现采样根引导
✅✅✅❌✅❌❌

🎓 Agent 开发资源

🌟 加入 Agent 革命

使用 Symfony MCP Server 构建新一代 AI 驱动应用。你的工具不再只是函数——它们是能够推理、学习和进化的智能 Agent。

社区

📜 许可证

MIT 许可证 - 自由构建!

📰 引用本项目的 MCP 注册目录


由 Boris AUBE 和贡献者倾情打造 - 灵感来自 OP.GG/laravel-mcp-server

评论

支持 Markdown

第一次接触 MCP?

从协议是什么,到在客户端里装上第一个服务,这几条回答覆盖了大多数入门问题。

一个开放协议,规定了 AI 应用如何以统一方式连接外部工具与数据源。客户端负责与模型对话,MCP 服务负责提供工具、资源和提示模板,两者通过标准消息通信,同一个服务可以被不同客户端复用。