Skip to content

add support for embedded resource response #224

Description

@Gummibeer

As resource links are already supported it would be nice to also support embedded resource responses.

Response::embeddedResource(
    resource: app(SessionSummaryResource::class),
    arguments: ['session_id' => $session_id],
)

I implemented it locally for my own needs as below - for the package it likely needs a little more variations in input. But that works nicely for prompts.

public static function embeddedResource(Resource $resource, array $arguments = []): self
{
    $uri = $resource->uri();
    if ($resource instanceof HasUriTemplate) {
        $uri = strtr(
            $uri,
            collect($arguments)->keyBy(fn (mixed $_, string $key): string => Str::of($key)->start('{')->finish('}'))->all(),
        );
    }

    $text = $resource->handle(new Request($arguments))->content();

    return new self(new EmbeddedResource(
        uri: $uri,
        text: $text,
        mimeType: $resource->mimeType(),
    ));
}
<?php

namespace App\Mcp\Content;

use Laravel\Mcp\Server\Concerns\HasMeta;
use Laravel\Mcp\Server\Contracts\Content;
use Laravel\Mcp\Server\Prompt;
use Laravel\Mcp\Server\Resource;
use Laravel\Mcp\Server\Tool;

class EmbeddedResource implements Content
{
    use HasMeta;

    public function __construct(
        protected string $uri,
        protected string $text,
        protected string $mimeType = 'text/plain',
    ) {}

    public function toTool(Tool $tool): array
    {
        return $this->toArray();
    }

    public function toPrompt(Prompt $prompt): array
    {
        return $this->toArray();
    }

    public function toResource(Resource $resource): array
    {
        return $this->toArray();
    }

    public function __toString(): string
    {
        return $this->text;
    }

    public function toArray(): array
    {
        return $this->mergeMeta([
            'type' => 'resource',
            'resource' => [
                'uri' => $this->uri,
                'text' => $this->text,
                'mimeType' => $this->mimeType,
            ],
        ]);
    }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions