PHP code example of errogaht / doctrine-mcp-bundle
1. Go to this page and download the library: Download errogaht/doctrine-mcp-bundle 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/ */
namespace App\Entity;
use App\Mcp\Scope\OrderScope;
use Doctrine\ORM\Mapping as ORM;
use Errogaht\DoctrineMcpBundle\Attribute\FilterOperator;
use Errogaht\DoctrineMcpBundle\Attribute\McpEntity;
use Errogaht\DoctrineMcpBundle\Attribute\McpField;
use Errogaht\DoctrineMcpBundle\Attribute\McpOperation;
#[ORM\Entity]
#[McpEntity(
name: 'Order',
description: 'An order owned by the current business.',
operations: [McpOperation::Read, McpOperation::Update],
scopes: [OrderScope::class],
permissions: ['update' => 'ORDER_EDIT'],
)]
final class Order
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
#[McpField(description: 'The order identifier.')]
private ?int $id = null;
#[ORM\Column(length: 255)]
#[McpField(
description: 'The delivery address while the order is editable.',
updatable: true,
operators: [FilterOperator::Eq, FilterOperator::Contains],
sortable: true,
)]
private string $deliveryAddress = '';
#[ORM\Column(length: 32)]
#[McpField(description: 'The order workflow status.')]
private string $status = 'new';
#[ORM\Column]
#[McpField(readable: false, serverControlled: true, sensitive: true)]
private int $businessId;
// Getters and setters are omitted from this documentation example.
}
namespace App\Mcp\Scope;
use App\Entity\Order;
use Doctrine\ORM\QueryBuilder;
use Errogaht\DoctrineMcpBundle\Attribute\McpOperation;
use Errogaht\DoctrineMcpBundle\Metadata\EntityDefinition;
use Errogaht\DoctrineMcpBundle\Scope\EntityScopeInterface;
use Errogaht\DoctrineMcpBundle\Security\ActorContext;
/** Restricts orders to the actor's business and enforces editable workflow states. */
final class OrderScope implements EntityScopeInterface
{
public function apply(
QueryBuilder $query,
string $alias,
EntityDefinition $entity,
McpOperation $operation,
ActorContext $actor,
): void {
$businessId = $actor->user->getBusiness()->getId();
$query
->andWhere($alias.'.businessId = :mcp_business_id')
->setParameter('mcp_business_id', $businessId);
if (McpOperation::Update === $operation) {
$query
->andWhere($alias.'.status = :mcp_editable_status')
->setParameter('mcp_editable_status', 'new');
}
}
public function initialize(object $entity, EntityDefinition $definition, ActorContext $actor): void
{
if ($entity instanceof Order) {
// Tenant ownership is controlled by the server, never by MCP input.
$entity->setBusinessId($actor->user->getBusiness()->getId());
}
}
public function assert(
object $entity,
EntityDefinition $definition,
McpOperation $operation,
ActorContext $actor,
): void {
if ($entity instanceof Order && $entity->getBusinessId() !== $actor->user->getBusiness()->getId()) {
throw new \DomainException('Cross-business mutation rejected.');
}
}
}
use Errogaht\DoctrineMcpBundle\Scope\UnrestrictedScope;
#[McpEntity(scopes: [UnrestrictedScope::class])]
final class PublicCountry
{
// ...
}
#[McpEntity(
operations: [McpOperation::Read, McpOperation::Update, McpOperation::Delete],
scopes: [OrderScope::class],
permissions: [
'read' => 'ORDER_VIEW',
'update' => 'ORDER_EDIT',
'delete' => 'ORDER_DELETE',
],
)]
final class Order
{
// ...
}
namespace App\Mcp;
use Errogaht\DoctrineMcpBundle\Security\ActorContext;
use Errogaht\DoctrineMcpBundle\Security\ActorProviderInterface;
use Errogaht\DoctrineMcpBundle\Security\UnauthenticatedActorException;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\User\UserInterface;
/** Maps the authenticated application user into the stable MCP security context. */
final class ActorProvider implements ActorProviderInterface
{
public function __construct(private readonly Security $security)
{
}
public function current(): ActorContext
{
$user = $this->security->getUser();
if (!$user instanceof UserInterface) {
throw new UnauthenticatedActorException('Authentication is
namespace App\Mcp\Reference;
use Errogaht\DoctrineMcpBundle\Reference\ReferencePage;
use Errogaht\DoctrineMcpBundle\Reference\ReferenceProviderInterface;
use Errogaht\DoctrineMcpBundle\Security\ActorContext;
/** Provides agent-readable time-zone choices without exposing an internal table. */
final class TimezoneReferenceProvider implements ReferenceProviderInterface
{
public function name(): string
{
return 'timezones';
}
public function values(ActorContext $actor, ?string $query, int $limit, ?string $cursor): ReferencePage
{
$values = array_filter(
\DateTimeZone::listIdentifiers(),
static fn (string $timezone): bool => null === $query || str_contains(strtolower($timezone), strtolower($query)),
);
$items = array_map(
static fn (string $timezone): array => ['value' => $timezone, 'label' => $timezone],
array_slice(array_values($values), 0, $limit),
);
return new ReferencePage($items);
}
}
namespace App\Mcp\Mutation;
use App\Entity\Order;
use App\Service\OrderManager;
use Errogaht\DoctrineMcpBundle\Metadata\EntityDefinition;
use Errogaht\DoctrineMcpBundle\Mutation\EntityMutationHandlerInterface;
use Errogaht\DoctrineMcpBundle\Security\ActorContext;
/** Routes MCP mutations through the same domain service used by the application. */
final class OrderMutationHandler implements EntityMutationHandlerInterface
{
public function __construct(private readonly OrderManager $orders)
{
}
public function create(EntityDefinition $definition, array $values, ActorContext $actor, bool $dryRun): object
{
return $this->orders->createForMcp($values, $actor->user, $dryRun);
}
public function update(object $entity, EntityDefinition $definition, array $changes, ActorContext $actor, bool $dryRun): object
{
if (!$entity instanceof Order) {
throw new \LogicException('Unexpected MCP entity.');
}
return $this->orders->updateForMcp($entity, $changes, $actor->user, $dryRun);
}
public function delete(object $entity, EntityDefinition $definition, ActorContext $actor, bool $dryRun): void
{
$this->orders->deleteForMcp($entity, $actor->user, $dryRun);
}
}
#[McpEntity(
operations: [McpOperation::Read, McpOperation::Create, McpOperation::Update],
scopes: [OrderScope::class],
handler: OrderMutationHandler::class,
)]
final class Order
{
// ...
}
namespace App\Mcp;
use App\Service\OrderReportService;
use Mcp\Capability\Attribute\McpTool;
use Mcp\Schema\ToolAnnotations;
/** Provides an aggregate report that does not map to generic entity CRUD. */
final class OrderReportTools
{
public function __construct(private readonly OrderReportService $reports)
{
}
/** @return array{orders: int, revenue: float} */
#[McpTool(
name: 'orders_daily_summary',
description: 'Return the current actor\'s order summary for an ISO-8601 date.',
annotations: new ToolAnnotations(readOnlyHint: true, idempotentHint: true),
)]
public function dailySummary(string $date): array
{
return $this->reports->dailySummary(new \DateTimeImmutable($date));
}
}
namespace App\Mcp;
use Mcp\Capability\Attribute\McpPrompt;
use Mcp\Capability\Attribute\McpResource;
use Mcp\Capability\Attribute\McpResourceTemplate;
/** Publishes application guidance through standard MCP capabilities. */
final class ApplicationCapabilities
{
#[McpResource(
uri: 'docs://orders/policy',
name: 'order_policy',
description: 'Current order editing policy.',
mimeType: 'text/markdown',
)]
public function orderPolicy(): string
{
return 'Orders can be edited before they enter delivery.';
}
#[McpResourceTemplate(
uriTemplate: 'docs://orders/{locale}/policy',
name: 'localized_order_policy',
description: 'Localized order editing policy.',
mimeType: 'text/markdown',
)]
public function localizedOrderPolicy(string $locale): string
{
return sprintf('Order policy for locale %s.', $locale);
}
#[McpPrompt(
name: 'prepare_order_summary',
description: 'Prepare a concise customer-facing order summary.',
)]
public function prepareOrderSummary(string $orderId): string
{
return sprintf('Summarize order %s using only data available to the current actor.', $orderId);
}
}
namespace App\Mcp\Audit;
use Errogaht\DoctrineMcpBundle\Audit\AuditSinkInterface;
/** Persists sanitized MCP mutation records in the application's audit store. */
final class DoctrineAuditSink implements AuditSinkInterface
{
public function record(array $record): void
{
// Persist the already-sanitized record in an append-only store.
}
}
bash
php bin/console doctrine-mcp:validate
php bin/console doctrine-mcp:debug Order