Skip to content

Commit 25bcb44

Browse files
Extend progress notification support (#163)
* Extend progress notification support * Address feedback and fix test --------- Co-authored-by: Stephen Toub <stoub@microsoft.com>
1 parent b12d728 commit 25bcb44

21 files changed

+175
-154
lines changed
Lines changed: 2 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
1-
using ModelContextProtocol.Protocol.Messages;
2-
using ModelContextProtocol.Protocol.Types;
1+
using ModelContextProtocol.Protocol.Types;
32

43
namespace ModelContextProtocol.Client;
54

65
/// <summary>
76
/// Represents an instance of an MCP client connecting to a specific server.
87
/// </summary>
9-
public interface IMcpClient : IAsyncDisposable
8+
public interface IMcpClient : IMcpEndpoint
109
{
1110
/// <summary>
1211
/// Gets the capabilities supported by the server.
@@ -24,40 +23,4 @@ public interface IMcpClient : IAsyncDisposable
2423
/// It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt.
2524
/// </summary>
2625
string? ServerInstructions { get; }
27-
28-
/// <summary>
29-
/// Adds a handler for server notifications of a specific method.
30-
/// </summary>
31-
/// <param name="method">The notification method to handle.</param>
32-
/// <param name="handler">The async handler function to process notifications.</param>
33-
/// <remarks>
34-
/// <para>
35-
/// Each method may have multiple handlers. Adding a handler for a method that already has one
36-
/// will not replace the existing handler.
37-
/// </para>
38-
/// <para>
39-
/// <see cref="NotificationMethods"> provides constants for common notification methods.</see>
40-
/// </para>
41-
/// </remarks>
42-
void AddNotificationHandler(string method, Func<JsonRpcNotification, Task> handler);
43-
44-
/// <summary>
45-
/// Sends a generic JSON-RPC request to the server.
46-
/// </summary>
47-
/// <typeparam name="TResult">The expected response type.</typeparam>
48-
/// <param name="request">The JSON-RPC request to send.</param>
49-
/// <param name="cancellationToken">A token to cancel the operation.</param>
50-
/// <returns>A task containing the server's response.</returns>
51-
/// <remarks>
52-
/// It is recommended to use the capability-specific methods that use this one in their implementation.
53-
/// Use this method for custom requests or those not yet covered explicitly.
54-
/// </remarks>
55-
Task<TResult> SendRequestAsync<TResult>(JsonRpcRequest request, CancellationToken cancellationToken = default) where TResult : class;
56-
57-
/// <summary>
58-
/// Sends a message to the server.
59-
/// </summary>
60-
/// <param name="message">The message.</param>
61-
/// <param name="cancellationToken">A token to cancel the operation.</param>
62-
Task SendMessageAsync(IJsonRpcMessage message, CancellationToken cancellationToken = default);
6326
}

src/ModelContextProtocol/Client/McpClient.cs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,10 @@ public McpClient(IClientTransport clientTransport, McpClientOptions options, Mcp
4242

4343
SetRequestHandler<CreateMessageRequestParams, CreateMessageResult>(
4444
RequestMethods.SamplingCreateMessage,
45-
(request, ct) => samplingHandler(request, ct));
45+
(request, cancellationToken) => samplingHandler(
46+
request,
47+
request?.Meta?.ProgressToken is { } token ? new TokenProgress(this, token) : NullProgress.Instance,
48+
cancellationToken));
4649
}
4750

4851
if (options.Capabilities?.Roots is { } rootsCapability)
@@ -54,7 +57,7 @@ public McpClient(IClientTransport clientTransport, McpClientOptions options, Mcp
5457

5558
SetRequestHandler<ListRootsRequestParams, ListRootsResult>(
5659
RequestMethods.RootsList,
57-
(request, ct) => rootsHandler(request, ct));
60+
(request, cancellationToken) => rootsHandler(request, cancellationToken));
5861
}
5962
}
6063

src/ModelContextProtocol/Client/McpClientExtensions.cs

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,7 @@
88

99
namespace ModelContextProtocol.Client;
1010

11-
/// <summary>
12-
/// Provides extensions for operating on MCP clients.
13-
/// </summary>
11+
/// <summary>Provides extension methods for interacting with an <see cref="IMcpClient"/>.</summary>
1412
public static class McpClientExtensions
1513
{
1614
/// <summary>
@@ -531,17 +529,33 @@ internal static CreateMessageResult ToCreateMessageResult(this ChatResponse chat
531529
/// </summary>
532530
/// <param name="chatClient">The <see cref="IChatClient"/> with which to satisfy sampling requests.</param>
533531
/// <returns>The created handler delegate.</returns>
534-
public static Func<CreateMessageRequestParams?, CancellationToken, Task<CreateMessageResult>> CreateSamplingHandler(this IChatClient chatClient)
532+
public static Func<CreateMessageRequestParams?, IProgress<ProgressNotificationValue>, CancellationToken, Task<CreateMessageResult>> CreateSamplingHandler(
533+
this IChatClient chatClient)
535534
{
536535
Throw.IfNull(chatClient);
537536

538-
return async (requestParams, cancellationToken) =>
537+
return async (requestParams, progress, cancellationToken) =>
539538
{
540539
Throw.IfNull(requestParams);
541540

542541
var (messages, options) = requestParams.ToChatClientArguments();
543-
var response = await chatClient.GetResponseAsync(messages, options, cancellationToken).ConfigureAwait(false);
544-
return response.ToCreateMessageResult();
542+
var progressToken = requestParams.Meta?.ProgressToken;
543+
544+
List<ChatResponseUpdate> updates = [];
545+
await foreach (var update in chatClient.GetStreamingResponseAsync(messages, options, cancellationToken))
546+
{
547+
updates.Add(update);
548+
549+
if (progressToken is not null)
550+
{
551+
progress.Report(new()
552+
{
553+
Progress = updates.Count,
554+
});
555+
}
556+
}
557+
558+
return updates.ToChatResponse().ToCreateMessageResult();
545559
};
546560
}
547561

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
using ModelContextProtocol.Protocol.Messages;
2+
3+
namespace ModelContextProtocol;
4+
5+
/// <summary>Represents a client or server MCP endpoint.</summary>
6+
public interface IMcpEndpoint : IAsyncDisposable
7+
{
8+
/// <summary>Sends a generic JSON-RPC request to the connected endpoint.</summary>
9+
/// <typeparam name="TResult">The expected response type.</typeparam>
10+
/// <param name="request">The JSON-RPC request to send.</param>
11+
/// <param name="cancellationToken">A token to cancel the operation.</param>
12+
/// <returns>A task containing the client's response.</returns>
13+
Task<TResult> SendRequestAsync<TResult>(JsonRpcRequest request, CancellationToken cancellationToken = default) where TResult : class;
14+
15+
/// <summary>Sends a message to the connected endpoint.</summary>
16+
/// <param name="message">The message.</param>
17+
/// <param name="cancellationToken">A token to cancel the operation.</param>
18+
Task SendMessageAsync(IJsonRpcMessage message, CancellationToken cancellationToken = default);
19+
20+
/// <summary>
21+
/// Adds a handler for server notifications of a specific method.
22+
/// </summary>
23+
/// <param name="method">The notification method to handle.</param>
24+
/// <param name="handler">The async handler function to process notifications.</param>
25+
/// <remarks>
26+
/// <para>
27+
/// Each method may have multiple handlers. Adding a handler for a method that already has one
28+
/// will not replace the existing handler.
29+
/// </para>
30+
/// <para>
31+
/// <see cref="NotificationMethods"> provides constants for common notification methods.</see>
32+
/// </para>
33+
/// </remarks>
34+
void AddNotificationHandler(string method, Func<JsonRpcNotification, Task> handler);
35+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
using ModelContextProtocol.Protocol.Messages;
2+
using ModelContextProtocol.Utils;
3+
4+
namespace ModelContextProtocol;
5+
6+
/// <summary>Provides extension methods for interacting with an <see cref="IMcpEndpoint"/>.</summary>
7+
public static class McpEndpointExtensions
8+
{
9+
/// <summary>Notifies the connected endpoint of progress.</summary>
10+
/// <param name="endpoint">The endpoint issueing the notification.</param>
11+
/// <param name="progressToken">The <see cref="ProgressToken"/> identifying the operation.</param>
12+
/// <param name="progress">The progress update to send.</param>
13+
/// <param name="cancellationToken">A token to cancel the operation.</param>
14+
/// <returns>A task representing the completion of the operation.</returns>
15+
/// <exception cref="ArgumentNullException"><paramref name="endpoint"/> is <see langword="null"/>.</exception>
16+
public static Task NotifyProgressAsync(
17+
this IMcpEndpoint endpoint,
18+
ProgressToken progressToken,
19+
ProgressNotificationValue progress,
20+
CancellationToken cancellationToken = default)
21+
{
22+
Throw.IfNull(endpoint);
23+
24+
return endpoint.SendMessageAsync(new JsonRpcNotification()
25+
{
26+
Method = NotificationMethods.ProgressNotification,
27+
Params = new ProgressNotification()
28+
{
29+
ProgressToken = progressToken,
30+
Progress = progress,
31+
},
32+
}, cancellationToken);
33+
}
34+
}

src/ModelContextProtocol/Protocol/Types/Capabilities.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ public class SamplingCapability
5555

5656
/// <summary>Gets or sets the handler for sampling requests.</summary>
5757
[JsonIgnore]
58-
public Func<CreateMessageRequestParams?, CancellationToken, Task<CreateMessageResult>>? SamplingHandler { get; set; }
58+
public Func<CreateMessageRequestParams?, IProgress<ProgressNotificationValue>, CancellationToken, Task<CreateMessageResult>>? SamplingHandler { get; set; }
5959
}
6060

6161
/// <summary>

src/ModelContextProtocol/Protocol/Types/ListPromptsRequestParams.cs

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,4 @@
44
/// Sent from the client to request a list of prompts and prompt templates the server has.
55
/// <see href="https://github.com/modelcontextprotocol/specification/blob/main/schema/">See the schema for details</see>
66
/// </summary>
7-
public class ListPromptsRequestParams
8-
{
9-
/// <summary>
10-
/// An opaque token representing the current pagination position.
11-
/// If provided, the server should return results starting after this cursor.
12-
/// </summary>
13-
[System.Text.Json.Serialization.JsonPropertyName("cursor")]
14-
public string? Cursor { get; init; }
15-
}
7+
public class ListPromptsRequestParams : PaginatedRequestParams;

src/ModelContextProtocol/Protocol/Types/ListResourceTemplatesRequestParams.cs

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,4 @@
44
/// Sent from the client to request a list of resource templates the server has.
55
/// <see href="https://github.com/modelcontextprotocol/specification/blob/main/schema/">See the schema for details</see>
66
/// </summary>
7-
public class ListResourceTemplatesRequestParams
8-
{
9-
/// <summary>
10-
/// An opaque token representing the current pagination position.
11-
/// If provided, the server should return results starting after this cursor.
12-
/// </summary>
13-
[System.Text.Json.Serialization.JsonPropertyName("cursor")]
14-
public string? Cursor { get; init; }
15-
}
7+
public class ListResourceTemplatesRequestParams : PaginatedRequestParams;

src/ModelContextProtocol/Protocol/Types/ListResourcesRequestParams.cs

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,4 @@
44
/// Sent from the client to request a list of resources the server has.
55
/// <see href="https://github.com/modelcontextprotocol/specification/blob/main/schema/">See the schema for details</see>
66
/// </summary>
7-
public class ListResourcesRequestParams
8-
{
9-
/// <summary>
10-
/// An opaque token representing the current pagination position.
11-
/// If provided, the server should return results starting after this cursor.
12-
/// </summary>
13-
[System.Text.Json.Serialization.JsonPropertyName("cursor")]
14-
public string? Cursor { get; init; }
15-
}
7+
public class ListResourcesRequestParams : PaginatedRequestParams;

src/ModelContextProtocol/Protocol/Types/ListRootsRequestParams.cs

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,4 @@ namespace ModelContextProtocol.Protocol.Types;
66
/// A request from the server to get a list of root URIs from the client.
77
/// <see href="https://github.com/modelcontextprotocol/specification/blob/main/schema/">See the schema for details</see>
88
/// </summary>
9-
public class ListRootsRequestParams
10-
{
11-
/// <summary>
12-
/// Optional progress token for out-of-band progress notifications.
13-
/// </summary>
14-
[System.Text.Json.Serialization.JsonPropertyName("progressToken")]
15-
public ProgressToken? ProgressToken { get; init; }
16-
}
9+
public class ListRootsRequestParams : RequestParams;

src/ModelContextProtocol/Protocol/Types/ListToolsRequestParams.cs

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,4 @@
44
/// Sent from the client to request a list of tools the server has.
55
/// <see href="https://github.com/modelcontextprotocol/specification/blob/main/schema/">See the schema for details</see>
66
/// </summary>
7-
public class ListToolsRequestParams
8-
{
9-
/// <summary>
10-
/// An opaque token representing the current pagination position.
11-
/// If provided, the server should return results starting after this cursor.
12-
/// </summary>
13-
[System.Text.Json.Serialization.JsonPropertyName("cursor")]
14-
public string? Cursor { get; init; }
15-
}
7+
public class ListToolsRequestParams : PaginatedRequestParams;
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
namespace ModelContextProtocol.Protocol.Types;
2+
3+
/// <summary>
4+
/// Used as a base class for paginated requests.
5+
/// <see href="https://github.com/modelcontextprotocol/specification/blob/main/schema/2024-11-05/schema.json">See the schema for details</see>
6+
/// </summary>
7+
public class PaginatedRequestParams : RequestParams
8+
{
9+
/// <summary>
10+
/// An opaque token representing the current pagination position.
11+
/// If provided, the server should return results starting after this cursor.
12+
/// </summary>
13+
[System.Text.Json.Serialization.JsonPropertyName("cursor")]
14+
public string? Cursor { get; init; }
15+
}

src/ModelContextProtocol/Protocol/Types/Tool.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ public JsonElement InputSchema
3838
{
3939
if (!McpJsonUtilities.IsValidMcpToolSchema(value))
4040
{
41-
throw new ArgumentException("The specified document is not a valid MPC tool JSON schema.", nameof(InputSchema));
41+
throw new ArgumentException("The specified document is not a valid MCP tool JSON schema.", nameof(InputSchema));
4242
}
4343

4444
_inputSchema = value;
Lines changed: 2 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
1-
using ModelContextProtocol.Protocol.Messages;
2-
using ModelContextProtocol.Protocol.Types;
1+
using ModelContextProtocol.Protocol.Types;
32

43
namespace ModelContextProtocol.Server;
54

65
/// <summary>
76
/// Represents a server that can communicate with a client using the MCP protocol.
87
/// </summary>
9-
public interface IMcpServer : IAsyncDisposable
8+
public interface IMcpServer : IMcpEndpoint
109
{
1110
/// <summary>
1211
/// Gets the capabilities supported by the client.
@@ -26,42 +25,8 @@ public interface IMcpServer : IAsyncDisposable
2625
/// </summary>
2726
IServiceProvider? Services { get; }
2827

29-
/// <summary>
30-
/// Adds a handler for client notifications of a specific method.
31-
/// </summary>
32-
/// <param name="method">The notification method to handle.</param>
33-
/// <param name="handler">The async handler function to process notifications.</param>
34-
/// <remarks>
35-
/// <para>
36-
/// Each method may have multiple handlers. Adding a handler for a method that already has one
37-
/// will not replace the existing handler.
38-
/// </para>
39-
/// <para>
40-
/// <see cref="NotificationMethods"> provides constants for common notification methods.</see>
41-
/// </para>
42-
/// </remarks>
43-
void AddNotificationHandler(string method, Func<JsonRpcNotification, Task> handler);
44-
4528
/// <summary>
4629
/// Runs the server, listening for and handling client requests.
4730
/// </summary>
4831
Task RunAsync(CancellationToken cancellationToken = default);
49-
50-
/// <summary>
51-
/// Sends a generic JSON-RPC request to the client.
52-
/// NB! This is a temporary method that is available to send not yet implemented feature messages.
53-
/// Once all MCP features are implemented this will be made private, as it is purely a convenience for those who wish to implement features ahead of the library.
54-
/// </summary>
55-
/// <typeparam name="TResult">The expected response type.</typeparam>
56-
/// <param name="request">The JSON-RPC request to send.</param>
57-
/// <param name="cancellationToken">A token to cancel the operation.</param>
58-
/// <returns>A task containing the client's response.</returns>
59-
Task<TResult> SendRequestAsync<TResult>(JsonRpcRequest request, CancellationToken cancellationToken = default) where TResult : class;
60-
61-
/// <summary>
62-
/// Sends a message to the client.
63-
/// </summary>
64-
/// <param name="message">The message.</param>
65-
/// <param name="cancellationToken">A token to cancel the operation.</param>
66-
Task SendMessageAsync(IJsonRpcMessage message, CancellationToken cancellationToken = default);
6732
}

src/ModelContextProtocol/Server/McpServer.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,6 @@ public McpServer(ITransport transport, McpServerOptions options, ILoggerFactory?
6868
});
6969

7070
SetToolsHandler(options);
71-
7271
SetInitializeHandler(options);
7372
SetCompletionHandler(options);
7473
SetPingHandler();

src/ModelContextProtocol/Server/McpServerExtensions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
namespace ModelContextProtocol.Server;
99

10-
/// <inheritdoc />
10+
/// <summary>Provides extension methods for interacting with an <see cref="IMcpServer"/>.</summary>
1111
public static class McpServerExtensions
1212
{
1313
/// <summary>

0 commit comments

Comments
 (0)