PHPackages                             swisnl/agents-sdk - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. swisnl/agents-sdk

ActiveLibrary[Framework](/categories/framework)

swisnl/agents-sdk
=================

A lightweight yet powerful framework for building multi-agent workflows inspired by the OpenAi Agents SDK

0.11.0(2mo ago)226.8k—6.3%2MITPHPPHP ^8.2CI passing

Since Mar 20Pushed 1mo ago6 watchersCompare

[ Source](https://github.com/swisnl/agents-sdk)[ Packagist](https://packagist.org/packages/swisnl/agents-sdk)[ Docs](https://github.com/swisnl/agents-sdk)[ RSS](/packages/swisnl-agents-sdk/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (12)Versions (39)Used By (0)

Agents SDK for PHP
==================

[](#agents-sdk-for-php)

A lightweight yet powerful framework for building multi-agent workflows in PHP, inspired by the OpenAI Agents SDK.

[![PHP from Packagist](https://camo.githubusercontent.com/d57cafc1a61b547b8624df451d8bf667401b094dae69ddb6b6b9cc9bb33d91bc/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f737769736e6c2f6167656e74732d73646b2e737667)](https://packagist.org/packages/swisnl/agents-sdk)[![Latest Version on Packagist](https://camo.githubusercontent.com/1967ef01cf0440f2579096764592878b6bbd3b05103069d190ec1527c491575d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f737769736e6c2f6167656e74732d73646b2e737667)](https://packagist.org/packages/swisnl/agents-sdk)[![Software License](https://camo.githubusercontent.com/28849274b605cd1caf6f2f7e729a0abc0afed2d0952412dc2c2fdf8e2ebffe17/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f737769736e6c2f6167656e74732d73646b2e737667)](LICENSE.md)[![Buy us a tree](https://camo.githubusercontent.com/195a3f79c3c2f91a69498ad26c1d8a7eeaf5771da0007200f409f5d438a515c4/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f54726565776172652d2546302539462538432542332d6c69676874677265656e2e737667)](https://plant.treeware.earth/swisnl/agents-sdk)[![Build Status](https://camo.githubusercontent.com/c79e68406543d17ed062c51269df2619b299b3432f9ac2bf9fa598fc8ff2d7f1/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f737769736e6c2f6167656e74732d73646b2f72756e2d74657374732e796d6c3f6c6162656c3d7465737473266272616e63683d6d6173746572)](https://github.com/swisnl/agents-sdk/actions/workflows/run-tests.yml)[![Made by SWIS](https://camo.githubusercontent.com/8c541545402619860a7346c32a176d63a2b75eb8ebb85590d06a26b62417d260/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f2546302539462539412538302d6d6164652532306279253230535749532d2532333037333741392e737667)](https://www.swis.nl)

Overview
--------

[](#overview)

Agents SDK provides an elegant abstraction for creating AI agent systems in PHP, allowing you to:

- Build specialized agents for different tasks
- Connect agents using a handoff mechanism
- Define and use custom tools for external operations
- Stream LLM responses for real-time interactions
- Monitor agent behavior with observers and traces
- Serialize and deserialize conversations for state management
- Connect to external tools using the Model Context Protocol (MCP)
- Use both the Responses- and Chat Completions API

The SDK is designed to be flexible, extensible, and easy to use while providing a robust foundation for building complex multi-agent based systems.

Installation
------------

[](#installation)

```
composer require swisnl/agents-sdk
```

Basic Usage
-----------

[](#basic-usage)

Here's a simple example of creating and running an Agent that can use a Tool for retrieving weather information:

```
use Swis\Agents\Agent;
use Swis\Agents\Orchestrator;
use Swis\Agents\Tool;
use Swis\Agents\Tool\Required;
use Swis\Agents\Tool\ToolParameter;

// Define a custom tool
class WeatherTool extends Tool
{
    #[ToolParameter('The name of the city.'), Required]
    public string $city;

    protected ?string $toolDescription = 'Gets the current weather by city.';

    public function __invoke(): ?string
    {
        // Implementation to fetch weather data
        return "Current weather in {$this->city}: Sunny, 22°C";
    }
}

// Create an agent with the tool
$agent = new Agent(
    name: 'Weather Assistant',
    description: 'Provides weather information',
    instruction: 'You help users with weather-related questions. Use the WeatherTool to get accurate data.',
    tools: [new WeatherTool()]
);

// Set up the orchestrator
$orchestrator = new Orchestrator();

// Process a user message
$orchestrator->withUserInstruction('What\'s the weather like in Amsterdam?');

// Run the agent and get the response
$response = $orchestrator->run($agent);
echo $response;

// Or use streaming for real-time responses
$orchestrator->runStreamed($agent, function ($token) {
    echo $token;
});
```

Creating Agents
---------------

[](#creating-agents)

Agents are the core components of the SDK. They encapsulate a specific role or capability and can use tools to perform actions.

```
$agent = new Agent(
    name: 'Agent Name',             // Required: Unique identifier for the agent
    description: 'Description',     // Optional: Brief description of the agent's capabilities
    instruction: 'System prompt',   // Optional: Detailed instructions for the agent
    tools: [$tool1, $tool2],        // Optional: Array of tools the agent can use
    handoffs: [$otherAgent]         // Optional: Other agents this agent can hand off to
);
```

Using Chat Completions API
--------------------------

[](#using-chat-completions-api)

By default, agents will use the Responses API. You can control what endpoint the agent will use by giving it the correct Transporter.

Note that Native Tools are only supported by the Responses API.

```
$agent = new Agent(
    name: 'Agent Name',
    transporter: new ChatCompletionsTransporter()
);

// Or
$agent->withTransporter(new ChatCompletionsTransporter());
```

Defining Tools
--------------

[](#defining-tools)

Tools are capabilities that agents can use to perform actions. To create a custom tool:

1. Extend the `Tool` class
2. Define parameters using attributes
3. Implement the `__invoke` method with your tool's logic

```
class SearchTool extends Tool
{
    #[ToolParameter('The search query.'), Required]
    public string $query;

    #[ToolParameter('The number of results to return.')]
    public int $limit = 5;

    protected ?string $toolDescription = 'Searches for information.';

    public function __invoke(): ?string
    {
        // Implementation logic here
        return json_encode([
            'results' => [/* search results */]
        ]);
    }
}
```

```
// Examples with array and object parameters
class ProductSearchTool extends Tool
{
    #[ToolParameter('The product categories to search in.', itemsType: 'string')]
    public array $categories = [];

    #[ToolParameter('Filters to apply to the search.', objectClass: SearchFilter:class)]
    public object $filters;

    protected ?string $toolDescription = 'Searches for products with advanced filtering.';

    ...
}

class SearchFilter
{
    #[ToolParameter('The property to filter.'), Required]
    public string $property;

    #[ToolParameter('The value of the filter.'), Required]
    public string $values;;

    #[ToolParameter('The operator of the filter.')]
    #[Enum(['eq', 'neq', 'gt', 'lt', 'gte', 'lte'])]
    public string $operator = 'eq';

    protected ?string $toolDescription = 'Searches for products with advanced filtering.';

    ...
}
```

MCP Tool Support
----------------

[](#mcp-tool-support)

The SDK supports the Model Context Protocol (MCP) through the `McpConnection` class, allowing you to integrate external data sources and tools with your agents.

### What is MCP?

[](#what-is-mcp)

MCP (Model Context Protocol) is an open protocol that enables seamless integration between LLM applications and external data sources and tools. It provides a standardized way to connect LLMs with the context they need, offering:

- Dynamic discovery of available tools
- Tool filtering to restrict which tools are available to agents
- Remote tool invocation

### Using MCP

[](#using-mcp)

It's recommended to use the `swis/mcp-client` package for MCP client implementations.

```
composer require swisnl/mcp-client
```

To use MCP tools with your agents:

```
use Swis\Agents\Agent;
use Swis\Agents\Mcp\McpConnection;
use Swis\McpClient\Client;

// Create an MCP connection
$mcpConnection = McpConnection::forSse('http://localhost:3000');

// Optionally restrict which tools are available
$mcpConnection->withTools('calculator', 'weather');

// Optionally expose MCP tools under alternate names for the agent
$mcpConnection->withAlternateToolNames([
    'get_current_weather' => 'weather',
]);

// Optionally expose MCP tools with alternate descriptions for the agent
$mcpConnection->withAlternateToolDescriptions([
    'get_current_weather' => 'Get current weather conditions by location.',
]);

// Create an agent with the MCP connection
$agent = new Agent(
    name: 'Assistant with MCP Tools',
    description: 'An assistant that can use external MCP tools',
    mcpConnections: [$mcpConnection]
);
```

### Advanced MCP Usage

[](#advanced-mcp-usage)

The SDK supports advanced MCP features:

- Tool caching with PSR-6 compatible cache adapters
- Process-based MCP clients for local tools
- Metadata that can be sent with each MCP call

Example with a local MCP server:

```
// Create a connection to a local MCP server with process management
[$mcpConnection, $process] = McpConnection::forProcess(
    command: 'node path/to/mcp-server.js',
    autoRestartAmount: 5
);

// Add caching support
$mcpConnection->withCache($psr6CacheImplementation)
    ->withCacheTtl(1800); // 30 minute cache

// Add metadata that will be sent with each MCP call
$mcpConnection->withMeta(['traceparent' => '0000-0000-00-00x']);
```

Multi-Agent Systems
-------------------

[](#multi-agent-systems)

The SDK supports creating systems of specialized agents that can hand off tasks to each other:

```
// Create specialized agents
$weatherAgent = new Agent(
    name: 'Weather Agent',
    // ... configuration
);

$travelAgent = new Agent(
    name: 'Travel Agent',
    // ... configuration
    handoffs: [$weatherAgent]  // Travel agent can hand off to Weather agent
);

// Main triage agent
$triageAgent = new Agent(
    name: 'Triage Agent',
    description: 'Routes user requests to the appropriate specialized agent',
    handoffs: [$weatherAgent, $travelAgent]
);
```

Orchestration
-------------

[](#orchestration)

The `Orchestrator` class manages the conversation flow and agent execution:

```
$orchestrator = new Orchestrator();

// Add a user message
$orchestrator->withUserInstruction("I need help with planning a trip to Amsterdam");

// Run with a specific agent
$response = $orchestrator->run($triageAgent);

// Or stream the response
$orchestrator->runStreamed($triageAgent, function ($token) {
    echo $token;
});
```

Observability
-------------

[](#observability)

The SDK provides an observer pattern to monitor agent behavior:

```
$orchestrator->withAgentObserver(new class extends AgentObserver {
    public function beforeHandoff(AgentInterface $agent, AgentInterface $handoffToAgent, RunContext $context): void
    {
        echo "Handing off from {$agent->name()} to {$handoffToAgent->name()}\n";
    }

    public function onToolCall(AgentInterface $agent, Tool $tool, ToolCall $toolCall, RunContext $context): void
    {
        echo "Agent {$agent->name()} called tool: {$toolCall->tool}\n";
    }
});
```

Tracing
-------

[](#tracing)

The SDK includes built-in tracing support using OpenAI Tracing format by default. This helps with debugging and monitoring agent execution.

### Disabling Tracing

[](#disabling-tracing)

You can disable tracing in two ways:

1. On a per-orchestrator basis:

```
$orchestrator = new Orchestrator();
$orchestrator->disableTracing();
```

2. Globally via environment variable:

```
AGENTS_SDK_DISABLE_TRACING=true

```

Disabling tracing can be useful in production environments or when you don't need the debugging information.

Example Implementations
-----------------------

[](#example-implementations)

The repository includes examples for common use cases:

- `CustomerServiceAgent`: A multi-agent system for customer service with handoffs
- `WeatherAgent`: A simple agent that fetches weather information

Run the examples using:

```
php examples/play.php
```

Conversation Serialization
--------------------------

[](#conversation-serialization)

The SDK provides a way to serialize and deserialize conversation state, allowing you to continue conversations at a later time:

```
use Swis\Agents\Helpers\ConversationSerializer;

// After running some conversation with an orchestrator
$data = ConversationSerializer::serializeFromOrchestrator($orchestrator);
saveToStorage($data); // Your storage implementation

// Later, when you want to continue the conversation
$data = retrieveFromStorage(); // Your retrieval implementation

// Create a new orchestrator with the serialized conversation
$orchestrator = new Orchestrator();
$orchestrator->withContextFromData($data);

$agent = new Agent(/* Create your agent */);

// Continue the conversation
$orchestrator->withUserInstruction('New message');
$response = $orchestrator->run($agent);
```

Requirements
------------

[](#requirements)

- PHP 8.2 or higher
- OpenAI API key for LLM access (or other OpenAI compatible API)
- Composer for dependency management

Testing
-------

[](#testing)

The SDK includes a test suite built with PHPUnit. To run the tests:

```
# Install dependencies
composer install

# Run the tests
composer run test
```

### Test Structure

[](#test-structure)

- **Unit Tests**: Test individual components in isolation
- **Integration Tests**: Test the full agent workflow with actual API calls (skipped by default)

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

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

Credits
-------

[](#credits)

- [Joris Meijer](https://github.com/jormeijer)
- [Björn Brala](https://github.com/bbrala)
- [All Contributors](../../contributors)

License
-------

[](#license)

This package is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).

This package is [Treeware](https://treeware.earth). If you use it in production, then we ask that you [**buy the world a tree**](https://plant.treeware.earth/swisnl/agents-sdk) to thank us for our work. By contributing to the Treeware forest you’ll be creating employment for local families and restoring wildlife habitats.

SWIS ❤️ Open Source
-------------------

[](#swis-heart-open-source)

[SWIS](https://www.swis.nl) is a web agency from Leiden, the Netherlands. We love working with open source software.

###  Health Score

50

—

FairBetter than 96% of packages

Maintenance86

Actively maintained with recent releases

Popularity35

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 61.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~19 days

Recently: every ~30 days

Total

18

Last Release

88d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/8734305?v=4)[SWIS](/maintainers/swisnl)[@swisnl](https://github.com/swisnl)

---

Top Contributors

[![jormeijer](https://avatars.githubusercontent.com/u/8984962?v=4)](https://github.com/jormeijer "jormeijer (74 commits)")[![bbrala](https://avatars.githubusercontent.com/u/3294970?v=4)](https://github.com/bbrala "bbrala (24 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (13 commits)")[![JaZo](https://avatars.githubusercontent.com/u/3475007?v=4)](https://github.com/JaZo "JaZo (7 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (2 commits)")

---

Tags

swisnlagents-sdk

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/swisnl-agents-sdk/health.svg)

```
[![Health](https://phpackages.com/badges/swisnl-agents-sdk/health.svg)](https://phpackages.com/packages/swisnl-agents-sdk)
```

###  Alternatives

[laravel/framework

The Laravel Framework.

34.7k509.9M17.0k](/packages/laravel-framework)[symfony/symfony

The Symfony PHP framework

31.3k86.3M2.2k](/packages/symfony-symfony)[shopware/platform

The Shopware e-commerce core

3.3k1.5M3](/packages/shopware-platform)[magento/community-edition

Magento 2 (Open Source)

12.1k52.1k10](/packages/magento-community-edition)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

595.2M386](/packages/shopware-core)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
