| 1 | package MCP::Server::KnowledgeStore::ResourceTemplates; | ||
| 2 | our $VERSION = '0.001'; | ||
| 3 | 1 | ▶ | use v5.38; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 4 | 0 | ▶ | use Mojo::Base 'MCP::Server', -signatures; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 5 | |||
| 6 | # ABSTRACT: MCP server support for resource templates and tool-call logging | ||
| 7 | |||
| 8 | use Carp qw(croak); | ||
| 9 | use List::Util qw(first); | ||
| 10 | use Mojo::JSON qw(to_json); | ||
| 11 | use Scalar::Util qw(blessed); | ||
| 12 | use constant { | ||
| 13 | INTERNAL_ERROR => -32603, | ||
| 14 | NOT_FOUND => -32001, | ||
| 15 | INVALID_PARAMS => -32602, | ||
| 16 | }; | ||
| 17 | |||
| 18 | sub handle ($self, $request, $context) { | ||
| 19 | return $self->SUPER::handle($request, $context) | ||
| 20 | unless ref $request eq 'HASH' | ||
| 21 | && ($request->{method} // '') eq 'tools/call'; | ||
| 22 | |||
| 23 | my $params = ref $request->{params} eq 'HASH' ? $request->{params} : {}; | ||
| 24 | my $name = $params->{name} // ''; | ||
| 25 | my $args = ref $params->{arguments} eq 'HASH' ? $params->{arguments} : {}; | ||
| 26 | my $principal = _log_label($context->principal // 'anonymous'); | ||
| 27 | my $tool_name = _log_label($name); | ||
| 28 | |||
| 29 | $self->log->trace( | ||
| 30 | "[$principal] tools/call request [" . to_json($request) . ']'); | ||
| 31 | |||
| 32 | unless (first { $_->name eq $name } @{ $self->_tools($context) }) { | ||
| 33 | $self->log->warn("[$principal] called unknown tool [$tool_name]"); | ||
| 34 | return $self->SUPER::handle($request, $context); | ||
| 35 | } | ||
| 36 | |||
| 37 | $self->log->info("[$principal] called [$tool_name]"); | ||
| 38 | $self->log->debug( | ||
| 39 | "[$principal] called [$tool_name] with [" . to_json($args) . ']'); | ||
| 40 | |||
| 41 | my $response = $self->SUPER::handle($request, $context); | ||
| 42 | if (blessed($response) && $response->isa('Mojo::Promise')) { | ||
| 43 | return $response->then( | ||
| 44 | sub ($reply) { | ||
| 45 | $self->_log_tool_reply($principal, $tool_name, $reply); | ||
| 46 | return $reply; | ||
| 47 | } | ||
| 48 | ); | ||
| 49 | } | ||
| 50 | |||
| 51 | $self->_log_tool_reply($principal, $tool_name, $response); | ||
| 52 | return $response; | ||
| 53 | } | ||
| 54 | |||
| 55 | sub _log_label ($value) { | ||
| 56 | $value =~ s/([\[\]\\\r\n])/sprintf '\\x{%02x}', ord $1/ge; | ||
| 57 | return $value; | ||
| 58 | } | ||
| 59 | |||
| 60 | sub _log_tool_reply ($self, $principal, $name, $reply) { | ||
| 61 | my $failed = ref $reply eq 'HASH' | ||
| 62 | && (exists $reply->{error} | ||
| 63 | || ref $reply->{result} eq 'HASH' && $reply->{result}{isError}); | ||
| 64 | my $debug = $self->log->is_level('debug'); | ||
| 65 | my $error = $failed && $self->log->is_level('error'); | ||
| 66 | return unless $debug || $error; | ||
| 67 | |||
| 68 | my $json = to_json($reply); | ||
| 69 | $self->log->trace("[$principal] tools/call reply [$json]"); | ||
| 70 | $self->log->debug("[$principal] call [$name] reply [$json]"); | ||
| 71 | $self->log->error("[$principal] call [$name] failed [$json]") if $error; | ||
| 72 | return; | ||
| 73 | } | ||
| 74 | |||
| 75 | sub log_transport_rejection ($self, $principal, $request, $reply) { | ||
| 76 | $principal = _log_label($principal // 'anonymous'); | ||
| 77 | $request = {} unless ref $request eq 'HASH'; | ||
| 78 | $reply = {} unless ref $reply eq 'HASH'; | ||
| 79 | |||
| 80 | my $params = ref $request->{params} eq 'HASH' ? $request->{params} : {}; | ||
| 81 | my $name = _log_label($params->{name} // $request->{method} // 'unknown'); | ||
| 82 | my $args = ref $params->{arguments} eq 'HASH' ? $params->{arguments} : {}; | ||
| 83 | my $reason | ||
| 84 | = ref $reply->{error} eq 'HASH' | ||
| 85 | ? $reply->{error}{message} // 'unknown transport error' | ||
| 86 | : 'HTTP transport rejected the request'; | ||
| 87 | $reason = _log_label($reason); | ||
| 88 | |||
| 89 | $self->log->warn("[$principal] MCP call [$name] rejected [$reason]"); | ||
| 90 | $self->log->debug("[$principal] MCP call [$name] with [" | ||
| 91 | . to_json($args) | ||
| 92 | . '] reply [' | ||
| 93 | . to_json($reply) | ||
| 94 | . ']'); | ||
| 95 | $self->log->trace("[$principal] rejected MCP request [" | ||
| 96 | . to_json($request) | ||
| 97 | . '] reply [' | ||
| 98 | . to_json($reply) | ||
| 99 | . ']'); | ||
| 100 | return; | ||
| 101 | } | ||
| 102 | |||
| 103 | # Resource templates that this server supports | ||
| 104 | # Each template has: | ||
| 105 | # - uri_template: URI with {param} placeholders | ||
| 106 | # - description: Human-readable description | ||
| 107 | # - mime_type: MIME type for responses | ||
| 108 | # - code: Callback to generate the resource content | ||
| 109 | # - name: Template name | ||
| 110 | |||
| 111 | sub add_template ($self, %args) { | ||
| 112 | my $template = { | ||
| 113 | uri_template => $args{uri_template} // croak('uri_template is required'), | ||
| 114 | name => $args{name} // croak('name is required'), | ||
| 115 | description => $args{description} // 'Resource template', | ||
| 116 | mime_type => $args{mime_type} // 'text/plain', | ||
| 117 | code => $args{code} // croak('code is required'), | ||
| 118 | }; | ||
| 119 | push @{ $self->{_resource_templates} //= [] }, $template; | ||
| 120 | return $template; | ||
| 121 | } | ||
| 122 | |||
| 123 | # Parse a URI template and extract parameters | ||
| 124 | # Returns: hashref of {param_name => value, ...} or undef if no match | ||
| 125 | sub _parse_template ($self, $uri_template, $uri) { | ||
| 126 | |||
| 127 | # Convert template to regex pattern | ||
| 128 | # First, escape all regex special characters in literal parts | ||
| 129 | my $pattern = ''; | ||
| 130 | my $pos = 0; | ||
| 131 | my @param_names; | ||
| 132 | |||
| 133 | while ($uri_template =~ /\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g) { | ||
| 134 | my $before | ||
| 135 | = substr($uri_template, $pos, pos($uri_template) - $pos - length($&)); | ||
| 136 | my $param = $1; | ||
| 137 | |||
| 138 | # Escape the literal text before the parameter | ||
| 139 | $before =~ s/([\.\+\*\?\|\(\)\[\]\{\}])/\\$1/g; | ||
| 140 | $pattern .= $before . '([^\/?#]+)'; | ||
| 141 | |||
| 142 | push @param_names, $param; | ||
| 143 | $pos = pos($uri_template); | ||
| 144 | } | ||
| 145 | |||
| 146 | # Add the remaining literal text after the last parameter | ||
| 147 | my $after = substr($uri_template, $pos); | ||
| 148 | $after =~ s/([\.\+\*\?\|\(\)\[\]\{\}])/\\$1/g; | ||
| 149 | $pattern .= $after; | ||
| 150 | |||
| 151 | $pattern = "\\A$pattern\\z"; | ||
| 152 | |||
| 153 | if ($uri =~ /$pattern/) { | ||
| 154 | my %params; | ||
| 155 | |||
| 156 | # Values are in $1, $2, etc. - extract them from the match | ||
| 157 | my @values = ($1, $2, $3, $4, $5, $6); | ||
| 158 | @params{@param_names} = @values; | ||
| 159 | return \%params; | ||
| 160 | } | ||
| 161 | return undef; | ||
| 162 | } | ||
| 163 | |||
| 164 | # Find matching template for a given URI | ||
| 165 | # Returns: ($template, $params_hashref) or (undef, undef) if no match | ||
| 166 | sub _match_template ($self, $uri) { | ||
| 167 | my @templates = @{ $self->{_resource_templates} // [] }; | ||
| 168 | for my $template (@templates) { | ||
| 169 | if (my $params = $self->_parse_template($template->{uri_template}, $uri)) { | ||
| 170 | return ($template, $params); | ||
| 171 | } | ||
| 172 | } | ||
| 173 | return (undef, undef); | ||
| 174 | } | ||
| 175 | |||
| 176 | # Override _resources to include template-based resources | ||
| 177 | sub _resources ($self, $context) { | ||
| 178 | my @resources = $self->SUPER::_resources($context); | ||
| 179 | |||
| 180 | # Add resource template descriptions | ||
| 181 | my @templates = @{ $self->{_resource_templates} // [] }; | ||
| 182 | for my $template (@templates) { | ||
| 183 | |||
| 184 | # We use the template as-is for listing | ||
| 185 | # The actual URI will have placeholders | ||
| 186 | push @resources, { | ||
| 187 | uri => $template->{uri_template}, | ||
| 188 | name => $template->{name}, | ||
| 189 | description => $template->{description}, | ||
| 190 | mimeType => $template->{mime_type}, | ||
| 191 | |||
| 192 | # Mark as template | ||
| 193 | _is_template => 1, | ||
| 194 | }; | ||
| 195 | } | ||
| 196 | |||
| 197 | return @resources; | ||
| 198 | } | ||
| 199 | |||
| 200 | # Override _handle_resources_read to support templates | ||
| 201 | sub _handle_resources_read ($self, $params, $id, $context) { | ||
| 202 | my $uri = $params->{uri} // ''; | ||
| 203 | |||
| 204 | # First check regular resources | ||
| 205 | if (my $resource | ||
| 206 | = first { $_->uri eq $uri } @{ $self->_resources($context) }) | ||
| 207 | { | ||
| 208 | return $self->SUPER::_handle_resources_read($params, $id, $context); | ||
| 209 | } | ||
| 210 | |||
| 211 | # Then check resource templates | ||
| 212 | if (my ($template, $params) = $self->_match_template($uri)) { | ||
| 213 | |||
| 214 | # Check scope - templates don't have scopes in this simple implementation | ||
| 215 | # If the template had scopes, we'd check them here | ||
| 216 | |||
| 217 | # Call the template code with the extracted parameters | ||
| 218 | my $result; | ||
| 219 | eval { $result = $template->{code}->($template, $params, $context); }; | ||
| 220 | |||
| 221 | if ($@) { | ||
| 222 | my $err | ||
| 223 | = $self->_jsonrpc_error(INVALID_PARAMS, "Resource template error: $@", | ||
| 224 | $id); | ||
| 225 | $context->status(400) if $context->can('status'); | ||
| 226 | return $err; | ||
| 227 | } | ||
| 228 | |||
| 229 | if (!defined $result) { | ||
| 230 | my $err | ||
| 231 | = $self->_jsonrpc_error(NOT_FOUND, "Resource not found: $uri", $id); | ||
| 232 | $context->status(404) if $context->can('status'); | ||
| 233 | return $err; | ||
| 234 | } | ||
| 235 | |||
| 236 | # Handle the result | ||
| 237 | if (ref $result eq 'HASH' && exists $result->{contents}) { | ||
| 238 | return $result; | ||
| 239 | } | ||
| 240 | |||
| 241 | # Wrap scalar text in text_resource format | ||
| 242 | return { contents => | ||
| 243 | [{ uri => $uri, mimeType => $template->{mime_type}, text => $result }] | ||
| 244 | }; | ||
| 245 | } | ||
| 246 | |||
| 247 | # No match found | ||
| 248 | my $err | ||
| 249 | = $self->_jsonrpc_error(INVALID_PARAMS, "Resource '$uri' not found", $id); | ||
| 250 | $context->status(404) if $context->can('status'); | ||
| 251 | return $err; | ||
| 252 | } | ||
| 253 | |||
| 254 | # Helper to create JSON-RPC error responses | ||
| 255 | sub _jsonrpc_error ($self, $code, $message, $id) { | ||
| 256 | return { | ||
| 257 | jsonrpc => '2.0', | ||
| 258 | error => { code => $code, message => $message }, | ||
| 259 | id => $id | ||
| 260 | }; | ||
| 261 | } | ||
| 262 | |||
| 263 | 1; | ||
| 264 | |||
| 265 | __END__ | ||