|
| 1 | +using ModelContextProtocol.Client; |
| 2 | +using ModelContextProtocol.Protocol; |
| 3 | +using System.Text.Json; |
| 4 | + |
| 5 | +namespace ModelContextProtocol.Extensions.Skills; |
| 6 | + |
| 7 | +/// <summary> |
| 8 | +/// Extension methods for <see cref="McpClient"/> to discover, retrieve, and verify skills served under the |
| 9 | +/// MCP Skills extension (SEP-2640). |
| 10 | +/// </summary> |
| 11 | +public static class McpSkillsClientExtensions |
| 12 | +{ |
| 13 | + /// <summary> |
| 14 | + /// Gets whether the server declared the MCP Skills extension in its capabilities. |
| 15 | + /// </summary> |
| 16 | + /// <param name="client">The client.</param> |
| 17 | + /// <returns><see langword="true"/> if the server serves <c>skills/list</c> and <c>skills/get</c>; otherwise, <see langword="false"/>.</returns> |
| 18 | + /// <exception cref="ArgumentNullException"><paramref name="client"/> is <see langword="null"/>.</exception> |
| 19 | + /// <remarks> |
| 20 | + /// Clients must issue <c>skills/list</c> and <c>skills/get</c> only after observing the server's declaration. |
| 21 | + /// The other methods in this class throw <see cref="InvalidOperationException"/> when it is absent. |
| 22 | + /// </remarks> |
| 23 | + public static bool SupportsSkills(this McpClient client) |
| 24 | + { |
| 25 | +#if NET |
| 26 | + ArgumentNullException.ThrowIfNull(client); |
| 27 | +#else |
| 28 | + if (client is null) throw new ArgumentNullException(nameof(client)); |
| 29 | +#endif |
| 30 | + |
| 31 | + return client.ServerCapabilities?.Extensions?.ContainsKey(SkillsProtocol.ExtensionId) == true; |
| 32 | + } |
| 33 | + |
| 34 | + /// <summary> |
| 35 | + /// Retrieves the entries of every skill the server lists, following pagination to the end. |
| 36 | + /// </summary> |
| 37 | + /// <param name="client">The client.</param> |
| 38 | + /// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param> |
| 39 | + /// <returns>The listed skills.</returns> |
| 40 | + /// <exception cref="ArgumentNullException"><paramref name="client"/> is <see langword="null"/>.</exception> |
| 41 | + /// <exception cref="InvalidOperationException">The server did not declare the MCP Skills extension.</exception> |
| 42 | + /// <exception cref="McpException">The request failed or the server returned an error response.</exception> |
| 43 | + /// <remarks> |
| 44 | + /// <para> |
| 45 | + /// The listing may be empty or partial: a server whose catalog is large or generated may list fewer skills than |
| 46 | + /// it serves. Do not treat an empty listing as proof that a server has no skills; a skill's entry can always be |
| 47 | + /// retrieved by URI with <see cref="GetSkillAsync(McpClient, string, CancellationToken)"/>. |
| 48 | + /// </para> |
| 49 | + /// <para> |
| 50 | + /// This overload aggregates every page and does not surface the per-result caching hints. To read those, use |
| 51 | + /// <see cref="ListSkillsAsync(McpClient, ListSkillsRequestParams, CancellationToken)"/>, which returns one page at a time. |
| 52 | + /// </para> |
| 53 | + /// </remarks> |
| 54 | + public static async ValueTask<IList<Skill>> ListSkillsAsync(this McpClient client, CancellationToken cancellationToken = default) |
| 55 | + { |
| 56 | + List<Skill>? skills = null; |
| 57 | + ListSkillsRequestParams requestParams = new(); |
| 58 | + do |
| 59 | + { |
| 60 | + var page = await ListSkillsAsync(client, requestParams, cancellationToken).ConfigureAwait(false); |
| 61 | + skills ??= new(page.Skills.Count); |
| 62 | + skills.AddRange(page.Skills); |
| 63 | + requestParams.Cursor = page.NextCursor; |
| 64 | + } |
| 65 | + while (requestParams.Cursor is not null); |
| 66 | + |
| 67 | + return skills; |
| 68 | + } |
| 69 | + |
| 70 | + /// <summary> |
| 71 | + /// Retrieves one page of the skills the server lists. |
| 72 | + /// </summary> |
| 73 | + /// <param name="client">The client.</param> |
| 74 | + /// <param name="requestParams">The request parameters, including the cursor of the page to retrieve.</param> |
| 75 | + /// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param> |
| 76 | + /// <returns>The page, as returned by the server.</returns> |
| 77 | + /// <exception cref="ArgumentNullException"><paramref name="client"/> or <paramref name="requestParams"/> is <see langword="null"/>.</exception> |
| 78 | + /// <exception cref="InvalidOperationException">The server did not declare the MCP Skills extension.</exception> |
| 79 | + /// <exception cref="McpException">The request failed or the server returned an error response.</exception> |
| 80 | + public static async ValueTask<ListSkillsResult> ListSkillsAsync( |
| 81 | + this McpClient client, |
| 82 | + ListSkillsRequestParams requestParams, |
| 83 | + CancellationToken cancellationToken = default) |
| 84 | + { |
| 85 | +#if NET |
| 86 | + ArgumentNullException.ThrowIfNull(client); |
| 87 | + ArgumentNullException.ThrowIfNull(requestParams); |
| 88 | +#else |
| 89 | + if (client is null) throw new ArgumentNullException(nameof(client)); |
| 90 | + if (requestParams is null) throw new ArgumentNullException(nameof(requestParams)); |
| 91 | +#endif |
| 92 | + |
| 93 | + ThrowIfSkillsNotSupported(client, nameof(ListSkillsAsync)); |
| 94 | + |
| 95 | + JsonRpcRequest request = new() |
| 96 | + { |
| 97 | + Method = SkillsProtocol.MethodSkillsList, |
| 98 | + Params = JsonSerializer.SerializeToNode(requestParams, McpSkillsJsonContext.Default.ListSkillsRequestParams), |
| 99 | + }; |
| 100 | + |
| 101 | + JsonRpcResponse response = await client.SendRequestAsync(request, cancellationToken).ConfigureAwait(false); |
| 102 | + return response.Result?.Deserialize(McpSkillsJsonContext.Default.ListSkillsResult) ?? |
| 103 | + throw new JsonException($"Unexpected JSON result in the response to '{SkillsProtocol.MethodSkillsList}'."); |
| 104 | + } |
| 105 | + |
| 106 | + /// <summary> |
| 107 | + /// Retrieves the entry for a single skill by the URI of its <c>SKILL.md</c>. |
| 108 | + /// </summary> |
| 109 | + /// <param name="client">The client.</param> |
| 110 | + /// <param name="uri">The URI of the skill's <c>SKILL.md</c>.</param> |
| 111 | + /// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param> |
| 112 | + /// <returns>The skill's entry.</returns> |
| 113 | + /// <exception cref="ArgumentNullException"><paramref name="client"/> or <paramref name="uri"/> is <see langword="null"/>.</exception> |
| 114 | + /// <exception cref="InvalidOperationException">The server did not declare the MCP Skills extension.</exception> |
| 115 | + /// <exception cref="McpException"> |
| 116 | + /// The request failed or the server returned an error response, including <see cref="McpErrorCode.InvalidParams"/> |
| 117 | + /// when the server serves no skill at <paramref name="uri"/>. |
| 118 | + /// </exception> |
| 119 | + /// <remarks> |
| 120 | + /// A server answers for every skill it serves, whether or not the skill appears in its listing. Use this to |
| 121 | + /// confirm a URI referenced from server instructions or another skill, and to refresh one skill's manifest |
| 122 | + /// without re-enumerating the catalog. |
| 123 | + /// </remarks> |
| 124 | + public static async ValueTask<Skill> GetSkillAsync(this McpClient client, string uri, CancellationToken cancellationToken = default) |
| 125 | + { |
| 126 | +#if NET |
| 127 | + ArgumentNullException.ThrowIfNull(uri); |
| 128 | +#else |
| 129 | + if (uri is null) throw new ArgumentNullException(nameof(uri)); |
| 130 | +#endif |
| 131 | + |
| 132 | + var result = await GetSkillAsync(client, new GetSkillRequestParams { Uri = uri }, cancellationToken).ConfigureAwait(false); |
| 133 | + return result.Skill; |
| 134 | + } |
| 135 | + |
| 136 | + /// <summary> |
| 137 | + /// Retrieves the entry for a single skill using explicit request parameters. |
| 138 | + /// </summary> |
| 139 | + /// <param name="client">The client.</param> |
| 140 | + /// <param name="requestParams">The request parameters.</param> |
| 141 | + /// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param> |
| 142 | + /// <returns>The result, as returned by the server.</returns> |
| 143 | + /// <exception cref="ArgumentNullException"><paramref name="client"/> or <paramref name="requestParams"/> is <see langword="null"/>.</exception> |
| 144 | + /// <exception cref="InvalidOperationException">The server did not declare the MCP Skills extension.</exception> |
| 145 | + /// <exception cref="McpException">The request failed or the server returned an error response.</exception> |
| 146 | + public static async ValueTask<GetSkillResult> GetSkillAsync( |
| 147 | + this McpClient client, |
| 148 | + GetSkillRequestParams requestParams, |
| 149 | + CancellationToken cancellationToken = default) |
| 150 | + { |
| 151 | +#if NET |
| 152 | + ArgumentNullException.ThrowIfNull(client); |
| 153 | + ArgumentNullException.ThrowIfNull(requestParams); |
| 154 | +#else |
| 155 | + if (client is null) throw new ArgumentNullException(nameof(client)); |
| 156 | + if (requestParams is null) throw new ArgumentNullException(nameof(requestParams)); |
| 157 | +#endif |
| 158 | + |
| 159 | + ThrowIfSkillsNotSupported(client, nameof(GetSkillAsync)); |
| 160 | + |
| 161 | + JsonRpcRequest request = new() |
| 162 | + { |
| 163 | + Method = SkillsProtocol.MethodSkillsGet, |
| 164 | + Params = JsonSerializer.SerializeToNode(requestParams, McpSkillsJsonContext.Default.GetSkillRequestParams), |
| 165 | + }; |
| 166 | + |
| 167 | + JsonRpcResponse response = await client.SendRequestAsync(request, cancellationToken).ConfigureAwait(false); |
| 168 | + return response.Result?.Deserialize(McpSkillsJsonContext.Default.GetSkillResult) ?? |
| 169 | + throw new JsonException($"Unexpected JSON result in the response to '{SkillsProtocol.MethodSkillsGet}'."); |
| 170 | + } |
| 171 | + |
| 172 | + /// <summary> |
| 173 | + /// Reads one of a skill's files through <c>resources/read</c> and verifies the content against the skill's manifest. |
| 174 | + /// </summary> |
| 175 | + /// <param name="client">The client.</param> |
| 176 | + /// <param name="skill">The skill entry being acted on.</param> |
| 177 | + /// <param name="uri">The URI of the file to read. It must be listed in <paramref name="skill"/>'s manifest.</param> |
| 178 | + /// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param> |
| 179 | + /// <returns>The verified contents.</returns> |
| 180 | + /// <exception cref="ArgumentNullException">An argument is <see langword="null"/>.</exception> |
| 181 | + /// <exception cref="InvalidOperationException"> |
| 182 | + /// <paramref name="skill"/>'s manifest is <see cref="SkillResources.Dynamic"/>. Such a skill offers no content |
| 183 | + /// integrity; read its files with <see cref="McpClient.ReadResourceAsync(string, RequestOptions?, CancellationToken)"/> |
| 184 | + /// only if the host has decided to load unverifiable skills. |
| 185 | + /// </exception> |
| 186 | + /// <exception cref="SkillVerificationException"> |
| 187 | + /// <paramref name="uri"/> is not listed in the manifest, or the content's size or digest does not match its entry. |
| 188 | + /// </exception> |
| 189 | + /// <exception cref="McpException">The request failed or the server returned an error response.</exception> |
| 190 | + /// <remarks> |
| 191 | + /// An unlisted file is treated as a verification failure before any request is sent, because the manifest is |
| 192 | + /// complete and an unlisted file is a change to the skill. To read it, refresh the entry with |
| 193 | + /// <see cref="GetSkillAsync(McpClient, string, CancellationToken)"/> and proceed from the new manifest. |
| 194 | + /// </remarks> |
| 195 | + public static async ValueTask<ReadResourceResult> ReadSkillResourceAsync( |
| 196 | + this McpClient client, |
| 197 | + Skill skill, |
| 198 | + string uri, |
| 199 | + CancellationToken cancellationToken = default) |
| 200 | + { |
| 201 | +#if NET |
| 202 | + ArgumentNullException.ThrowIfNull(client); |
| 203 | + ArgumentNullException.ThrowIfNull(skill); |
| 204 | + ArgumentNullException.ThrowIfNull(uri); |
| 205 | +#else |
| 206 | + if (client is null) throw new ArgumentNullException(nameof(client)); |
| 207 | + if (skill is null) throw new ArgumentNullException(nameof(skill)); |
| 208 | + if (uri is null) throw new ArgumentNullException(nameof(uri)); |
| 209 | +#endif |
| 210 | + |
| 211 | + if (skill.Resources.IsDynamic) |
| 212 | + { |
| 213 | + throw new InvalidOperationException( |
| 214 | + $"Skill '{skill.Uri}' declares dynamic resources, which carry no digests and cannot be verified. " + |
| 215 | + $"Use {nameof(McpClient.ReadResourceAsync)} directly if unverifiable content is acceptable."); |
| 216 | + } |
| 217 | + |
| 218 | + if (SkillVerifier.FindResource(skill, uri) is null) |
| 219 | + { |
| 220 | + throw new SkillVerificationException( |
| 221 | + $"'{uri}' is not listed in the manifest of skill '{skill.Uri}'. An unlisted file is a change to the skill; " + |
| 222 | + "refresh the entry with skills/get before reading it."); |
| 223 | + } |
| 224 | + |
| 225 | + var result = await client.ReadResourceAsync(uri, cancellationToken: cancellationToken).ConfigureAwait(false); |
| 226 | + SkillVerifier.Verify(skill, result); |
| 227 | + return result; |
| 228 | + } |
| 229 | + |
| 230 | + private static void ThrowIfSkillsNotSupported(McpClient client, string operationName) |
| 231 | + { |
| 232 | + if (!SupportsSkills(client)) |
| 233 | + { |
| 234 | + throw new InvalidOperationException( |
| 235 | + $"'{operationName}' requires the server to declare the '{SkillsProtocol.ExtensionId}' extension in its capabilities, and it did not."); |
| 236 | + } |
| 237 | + } |
| 238 | +} |
0 commit comments