PHP code example of projectsaturnstudios / superconductor-core

1. Go to this page and download the library: Download projectsaturnstudios/superconductor-core library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

projectsaturnstudios / superconductor-core example snippets


namespace App\MCP\Tools;

use Superconductor\Capabilities\Tools\BaseTool;
use Superconductor\Support\Attributes\ToolCall;

#[ToolCall(
    tool: 'calculator',
    description: 'Calculate the sum of two numbers',
    inputSchema: [
        'type' => 'object',
        'properties' => [
            'a' => ['type' => 'number', 'description' => 'First number'],
            'b' => ['type' => 'number', 'description' => 'Second number']
        ],
        '][] = $text_content->toValue();
        }

        return $results;
    }

    private function execute(int $a, int $b): string
    {
        return "The sum of {$a} + {$b} = " . ($a + $b);
    }
}

// config/mcp.php - Update the capabilities.hardcoded.tools array
'features' => [
    'capabilities' => [
        'registrar' => [
            'available' => [
                'hardcoded' => [
                    'tools' => [
                        'calculator' => App\MCP\Tools\CalculatorTool::class,
                    ],
                    // ... other capabilities
                ],
            ],
        ],
    ],
],



return [
    'versions' => [
        'active' => '2025-03-26',
        'available' => [
            '2025-03-26' => true,
            '2024-11-05' => true,
        ],
    ],

    'session_managers' => [
        'session_class' => \Superconductor\Sessions\MCPSessionObject::class,
        'default' => 'cached',
        'available' => [
            'cached' => [
                'sessions_expire_in' => 300, // minutes
            ],
            'database' => [],
        ],
    ],

    'features' => [
        'capabilities' => [
            'registrar' => [
                'default' => 'hardcoded',
                'available' => [
                    'hardcoded' => [
                        'tools' => [
                            'echo' => \Superconductor\Capabilities\Tools\EchoTool::class,
                            'list_commands' => \Superconductor\Capabilities\Tools\ListCommandsTool::class,
                            // Remove the above tools and Add your custom tools here
                        ],
                        'resources' => [
                            'mcp://protocol-docs.txt' => \Superconductor\Capabilities\Resources\MCPProtocolDocsResource::class,
                            // Remove the above resources Add your custom resources here
                        ],
                        'prompts' => [
                            'some-vague-prompt' => \Superconductor\Capabilities\Prompts\SomeVaguePrompt::class,
                            // Remove the above prompts Add your custom prompts here
                        ],
                    ],
                ],
            ],
        ],
    ],

    'server' => [
        'details' => [
            'name' => env('MCP_SERVER', 'Superconductor'),
            'version' => env('MCP_SERVER_VERSION', '0.0.1'),
        ],
    ],
];

use Superconductor\Support\Facades\SchemaManager;

// Get the active protocol version
$version = config('mcp.versions.active'); // '2025-03-26'

// Check available versions
$available = config('mcp.versions.available');
// ['2025-03-26' => true, '2024-11-05' => true]

// Schema objects are automatically selected based on protocol version
// Tools, Resources, and Prompts use version-specific Data classes

// Superconductor\Schema\Definitions\V20250326\Tools\Tool 
// extends Superconductor\Schema\Definitions\V20241105\Tools\Tool
// This ensures backward compatibility while adding new features

use Superconductor\Support\Facades\SessionManager;

// Using the helper function (recommended)
generate_mcp_session('user-123');

// Or via the Facade
$session = SessionManager::createOrLoad('user-123');

// Sessions are automatically created and managed
// The session object extends AbstractMCPSession

   // config/mcp.php
   'features' => [
       'capabilities' => [
           'registrar' => [
               'available' => [
                   'hardcoded' => [
                       'tools' => [
                           'calculator' => App\MCP\Tools\CalculatorTool::class,
                           'weather' => App\MCP\Tools\WeatherTool::class,
                       ],
                       'resources' => [
                           'mcp://database' => App\MCP\Resources\DatabaseResource::class,
                           'mcp://logs' => App\MCP\Resources\LogsResource::class,
                       ],
                       'prompts' => [
                           'welcome' => App\MCP\Prompts\WelcomePrompt::class,
                       ],
                   ],
               ],
           ],
       ],
   ],
   

// Create a session (uses cached driver by default)
generate_mcp_session('demo-session');

// Get protocol version (from config, defaults to 2025-03-26)
$version = config('mcp.versions.active');

// List available capabilities using helper functions
$tools = list_tools();
$resources = list_resources();
$prompts = list_prompts();

// Or specify a protocol version
$tools = list_tools('2024-11-05');

namespace App\MCP\Tools;

use Superconductor\Capabilities\Tools\BaseTool;
use Superconductor\Support\Attributes\ToolCall;

#[ToolCall(
    tool: 'weather_lookup',
    description: 'Get current weather for a location',
    inputSchema: [
        'type' => 'object',
        'properties' => [
            'location' => ['type' => 'string', 'description' => 'City name'],
            'unit' => ['type' => 'string', 'enum' => ['celsius', 'fahrenheit'], 'default' => 'celsius']
        ],
        '        return $results;
    }
    
    private function execute(string $location, string $unit = 'celsius'): string
    {
        // Your implementation here
        $weather = $this->fetchWeatherData($location, $unit);
        
        return "Weather in {$location}: {$weather['temperature']}°{$unit[0]} - {$weather['condition']}";
    }
    
    private function fetchWeatherData(string $location, string $unit): array
    {
        // Integrate with your weather API
        return [
            'temperature' => 22,
            'condition' => 'sunny',
        ];
    }
}

#[ToolCall(
    tool: 'database_query',
    description: 'Execute safe database queries',
    inputSchema: [
        'type' => 'object',
        'properties' => [
            'table' => ['type' => 'string', 'description' => 'Table name'],
            'conditions' => ['type' => 'object', 'description' => 'Query conditions'],
            'limit' => ['type' => 'integer', 'default' => 10, 'maximum' => 100]
        ],
        '(json_encode($content, JSON_PRETTY_PRINT));
            $results['content'][] = $text_content->toValue();
        } catch (\Exception $e) {
            $results['isError'] = true;
            $text_content_class = $incoming_message::getTextContextObj();
            $text_content = new $text_content_class("Error: " . $e->getMessage());
            $results['content'][] = $text_content->toValue();
        }

        return $results;
    }
    
    private function execute(string $table, array $conditions = [], int $limit = 10): array
    {
        // Validate table name against whitelist
        $allowedTables = ['users', 'posts', 'comments'];
        if (!in_array($table, $allowedTables)) {
            throw new \InvalidArgumentException("Table '{$table}' is not allowed");
        }
        
        $query = DB::table($table)->limit($limit);
        
        foreach ($conditions as $field => $value) {
            $query->where($field, $value);
        }
        
        return $query->get()->toArray();
    }
}

namespace App\MCP\Resources;

use Superconductor\Capabilities\Resources\BaseResource;
use Superconductor\Support\Attributes\ReadableResource;

#[ReadableResource(
    uri: 'mcp://application-logs',
    name: 'Application Logs',
    description: 'Recent application log entries',
    mimeType: 'text/plain'
)]
class LogsResource extends BaseResource
{
    public function handle($incoming_message): array
    {
        $results = [
            'contents' => [],
        ];

        if ($content = $this->execute()) {
            $uri = $this->getResourceAttribute()->uri;
            $text_content_class = $incoming_message::getTextResourceContextObj();
            $text_content = new $text_content_class($uri, $content, 'text/plain');
            $results['contents'][] = $text_content->toValue();
        }

        return $results;
    }
    
    private function execute(): string
    {
        $logFile = storage_path('logs/laravel.log');
        
        if (!file_exists($logFile)) {
            return 'No log file found';
        }
        
        // Return last 100 lines
        $lines = file($logFile);
        $recentLines = array_slice($lines, -100);
        
        return implode('', $recentLines);
    }
}

#[ReadableResource(
    uri: 'database://users/{id}',
    name: 'User Profile',
    description: 'User profile information'
)]
class UserProfileResource extends Resource
{
    public function read(int $id): array
    {
        $user = User::findOrFail($id);
        
        return [
            'id' => $user->id,
            'name' => $user->name,
            'email' => $user->email,
            'created_at' => $user->created_at->toISOString(),
            'profile' => $user->profile?->toArray(),
        ];
    }
    
    public function getMimeType(): string
    {
        return 'application/json';
    }
}

namespace App\MCP\Prompts;

use Superconductor\Capabilities\Prompts\BasePrompt;
use Superconductor\Support\Attributes\ActionablePrompt;

#[ActionablePrompt(
    name: 'welcome_user',
    description: 'Welcome new users to the application',
    arguments: [
        [
            'name' => 'name',
            'description' => 'The user\'s name',
            '    'messages' => []
        ];
        
        if ($content = $this->execute(...$incoming_message->params['arguments'])) {
            $results['messages'] = $content;
        }

        return $results;
    }
    
    private function execute(string $name, ?string $role = null): array
    {
        $greeting = "Welcome to our application, {$name}!";
        
        if ($role) {
            $greeting .= " You're logged in as {$role}.";
        }
        
        $greeting .= "\n\nHere are some things you can do:\n";
        $greeting .= "- Check your dashboard\n";
        $greeting .= "- Update your profile\n";
        $greeting .= "- Explore our features";
        
        return [
            [
                'role' => 'assistant',
                'content' => [
                    'type' => 'text',
                    'text' => $greeting,
                ]
            ]
        ];
    }
}

#[ActionablePrompt(
    name: 'code_review',
    description: 'Generate code review guidelines',
    arguments: [
        [
            'name' => 'language',
            'description' => 'Programming language',
            'sePrompt
{
    public function handle($incoming_message): array
    {
        $results = [
            'description' => 'Code review guidelines',
            'messages' => []
        ];
        
        if ($content = $this->execute(...$incoming_message->params['arguments'])) {
            $results['messages'] = $content;
        }

        return $results;
    }
    
    private function execute(string $language, string $complexity = 'medium'): array
    {
        $guidelines = $this->getBaseGuidelines($language);
        $specific = $this->getComplexityGuidelines($complexity);
        
        $text = "# Code Review Guidelines for {$language}\n\n" .
               "## General Guidelines\n{$guidelines}\n\n" .
               "## {$complexity} Complexity Considerations\n{$specific}";
        
        return [
            [
                'role' => 'assistant',
                'content' => [
                    'type' => 'text',
                    'text' => $text,
                ]
            ]
        ];
    }
    
    private function getBaseGuidelines(string $language): string
    {
        return match($language) {
            'php' => "- Follow PSR standards\n- Check for proper error handling\n- Verify input validation",
            'javascript' => "- Check for proper async/await usage\n- Verify error boundaries\n- Review type safety",
            default => "- Follow language conventions\n- Check for proper error handling\n- Verify code clarity",
        };
    }
    
    private function getComplexityGuidelines(string $complexity): string
    {
        return match($complexity) {
            'simple' => "- Focus on readability\n- Check basic functionality",
            'complex' => "- Review architecture decisions\n- Check performance implications\n- Verify testing coverage",
            default => "- Balance readability and functionality\n- Check for proper abstractions",
        };
    }
}

// List capabilities using helper functions
$tools = list_tools();           // Get all available tools
$resources = list_resources();   // Get all available resources  
$prompts = list_prompts();       // Get all available prompts

// Specify protocol version
$tools = list_tools('2024-11-05');

use Tests\TestCase;

class MCPCapabilityTest extends TestCase
{
    public function test_tool_execution()
    {
        // Test your tools using the helper functions
        $tools = list_tools();
        $this->assertNotEmpty($tools);
        
        // Test specific tool functionality
        // Implementation depends on your transport layer
    }
    
    public function test_resource_access()
    {
        $resources = list_resources();
        $this->assertNotEmpty($resources);
    }
    
    public function test_prompt_generation()
    {
        $prompts = list_prompts();
        $this->assertNotEmpty($prompts);
    }
}

## Contributing

We welcome contributions to Superconductor! Whether it's improving documentation, fixing bugs, or adding new features, your help is appreciated.

### Development Setup

1. Clone the repository
2. Install dependencies: `composer install`
3. Run tests: `composer test`
4. Run static analysis: `composer analyse`

### Contribution Guidelines

- Follow PSR-12 coding standards
- Write tests for new features
- Update documentation as needed
- Ensure backward compatibility

## Security

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

### Security Considerations

- **Validate all tool inputs** - Never trust user-provided arguments
- **Implement proper authorization** - Check user permissions before executing tools
- **Sanitize resource access** - Prevent path traversal and unauthorized file access
- **Rate limiting** - Implement appropriate rate limits for resource-intensive operations

## License

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

---

**Ready to supercharge your Laravel app with MCP?**

bash
php artisan vendor:publish --tag=mcp 
bash
   php artisan vendor:publish --tag=mcp