Commit graph csharp-sdk/tests/ModelContextProtocol.Tests/Client
Author SHA1 Message Date
Stephen Toub
2bcff315f8
Update content according to latest spec (#513)
* Update content according to latest spec

* Add Title to a bunch of types

* Add _meta to lots of types

* Address feedback, more cleanup, fix NAOT test failure
2025-06-16 19:39:41 -04:00
Eirik Tsarpalis
d7d9eab3f8
Pass session id's to MCP endpoints. (#466)
* Pass session id's to MCP endpoints.

* Update src/ModelContextProtocol/Client/McpClient.cs

Co-authored-by: Stephen Halter <halter73@gmail.com>

* Update src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs

Co-authored-by: Stephen Halter <halter73@gmail.com>

* Make init callback asynchronous.

* Address feedback.

---------

Co-authored-by: Stephen Halter <halter73@gmail.com>
2025-06-12 17:56:57 +03:00
Stephen Toub
106ab8064f
Clean up namespaces (#410)
No meaningful code changes, just lots of namespace shuffling to have fewer namespaces and to put things in better namespaces.
2025-05-14 14:50:26 -04:00
Stephen Toub
d86b3277d4
Add McpServer/ClientResource{Template} and friends (#391)
* Add McpServer/ClientResource{Template} and friends

This PR copies the same design used by tools and prompts to add McpServerResource, McpServerResourceAttribute, McpServerResourceTypeAttribute, McpClientResource, and then all of those for ResourceTemplate as well.

Unlike the others, [McpServerResource] is permitted not only on methods but also on properties. This convenience is afforded because such resources aren't parameterized, and thus can be easily modeled as properties, likely auto-props, e.g.
```C#
[McpServerResource]
public static BlobResourceContents MyAmazingData { get; } = Create();
```

Details about resources can be encoded into the attributes or provided via McpServerResource{Template}.Create methods. If not URI is explicitly defined, one is derived from the member name and arguments. For templates, this means manufacturing a URI template that includes variables for all non-DI parameters.

This also fixes a few issues discovered along the way:
- McpClientExtensions are updated to use `ValueTask<T>` instead of `Task<T>` where relevant.
- McpServerPrompt was missing handling for progress notifications; that's been rectified. It was also missing configuring the description on the ProtocolPrompt.
- Renamed IMcpServerPrimitive.Name to Id. For resources, names aren't unique.
- After going back and forth, updated McpServer to not fail for missing handlers and to instead register default handlers. It simplifies the implementation and makes it more consistent.
- Added a bunch of primitive types into the McpJsonUtilities JSON source generator context so that such primitives are usable with tools/prompts/resources without folks being required to add them into their own context for Native AOT. I think we should consider pushing this down to AIJsonUtilities, instead, and that will then flow up to McpJsonUtilities automatically.

* Address feedback
2025-05-09 18:21:11 -04:00
Stephen Halter
e3ff552824
Improve testing for StreamableHttpHandler and IdleTrackingBackgroundService (#345)
* Add idle session pruning tests
* Remove redundant CTS from StreamableHttpHandler
  * StreamableHttpServerTransport.HandlePostRequest already creates the equivelant CTS
    which DeleteRequest_CompletesSession_WhichCancelsLongRunningToolCalls verifies
* Fix accept header validation for GET
* Use InvalidOperationException for transport-not-connected errors in doc comments
* Fix flaky Cancellation_ThrowsCancellationException test
2025-04-24 10:49:02 -07:00
Stephen Halter
7dcba357d4
Add server-side Streamable HTTP transport support (#330)
- Changes IJsonRpcMessage to an abstract base class so RelatedTransport will always be available
- Streamable HTTP supports multiple concurrent HTTP request with their own indpendent SSE response streams
- RelatedTransport indicates the source or destination of the JsonRpcMessage

- Changes the default RequestId to a JSON number for better compatibility with MCP servers in the wild
2025-04-18 17:07:23 -07:00
Stephen Toub
7d77be68cf
Clean up (use of) McpException and McpTransportException (#321)
* Clean up (use of) McpException

* Replace McpTransportException with InvalidOperationException

* Add cancellation test
2025-04-18 09:25:29 -07:00
Stephen Toub
b0cd6541ce
Add WithTools/Prompts overloads that accept McpServerTool/Prompts (#319)
To avoid folks needing to know how you should be registering tool instances into DI.
2025-04-16 15:06:19 -04:00
Stephen Toub
227f440ab9
Support progress notifications with McpClientTool and McpClientExtensions.CallToolAsync (#312) 2025-04-16 09:03:07 -04:00
Stephen Toub
f4c87f5e2f
Wrap each request in a service scope (#276)
* Wrap each request in a service scope

* Change request/notification delegates to return ValueTask

* Address feedback
2025-04-11 19:19:12 -04:00
Eirik Tsarpalis
e3aa54eb3c
Disable STJ reflection for testing. (#266)
* Disable STJ reflection for testing.

* Remove params method and redundant overload.

---------

Co-authored-by: Stephen Toub <stoub@microsoft.com>
2025-04-10 16:02:00 +01:00
Stephen Toub
45dcfe07ca
Fix CreateMessageRule.Role to be of type Role (#264) 2025-04-10 10:51:41 -04:00
Stephen Toub
0c502c43af
Update M.E.AI to latest version (#241)
Co-authored-by: Eirik Tsarpalis <eirik.tsarpalis@gmail.com>
2025-04-09 09:03:24 +01:00
Tyler Kendrick
03e3094dcc
Fix and enhance cancellation operations across MCP Sessions. (#179)
* Propagate CancellationToken request cancellation to remote endpoint

* Refactor existing tests to have a shared base class

* Add cancellation tests

---------

Co-authored-by: Stephen Toub <stoub@microsoft.com>
2025-04-08 16:12:12 -04:00
Eirik Tsarpalis
3e21f3594a
Remove McpServerConfig and have McpClientFactory accept IClientTransport instances directly. (#230)
* Remove McpServerConfig and have McpClientFactory accept IClientTransport instances directly.

* Address feedback and use lists when representing stdio arguments.

* Use "Name" for transport descriptors and "EndpointName" for MCP clients and servers.

* Update code samples.

* Fix source file naming
2025-04-08 17:37:41 +01:00
Stephen Toub
3b83ad4103
Enable servers to log to the clients via ILogger (#229)
* Enable servers to log to the client via ILogger

* Address feedback
2025-04-07 23:16:42 -04:00
Stephen Toub
848c9df433
Allow notification handlers post-creation temporary registration (#223)
- We still allow notification handlers to be configured pre-creation, eliminating any race conditions that may result from missed notifications. But now we also allow for post-creation notification handler registration.
- Handlers may now also be removed. This permits temporary registrations that may be created in a scoped manner.
- Registration handling is thread-safe.
- Handlers are now cancelable.
- Exceptions from notification handlers trigger all normal exception handling in the dispatch pipeline.

This also:
- Adds a WithStreamServerTransport as a counterpart to WithStdioServerTransport. The latter was used in several tests in a hacky way, and that's now simplified via the former's existence.
2025-04-06 21:17:00 -04:00
Stephen Toub
d21d933876
Move notification handler registrations to capabilities (#207)
* Move notification handler registrations to capabilities

Currently request handlers are set on the capability objects, but notification handlers are set after construction via an AddNotificationHandler method on the IMcpEndpoint interface. This moves handler specification to be at construction as well. This makes it more consistent with request handlers, simplifies the IMcpEndpoint interface to just be about message sending, and avoids a concurrency bug that could occur if someone tried to add a handler while the endpoint was processing notifications.

* Address more feedback and further cleanup
2025-04-04 13:11:07 -04:00
Esteban Solano Granados
c70dde3feb
[UnitTests] Add more UTs (#139)
* + Tests for McpClientExtensions code

* + code coverage for ClientOptions/Capabilities code

---------

Co-authored-by: Esteban Solano <estebanso@microsoft.com>
Co-authored-by: Stephen Toub <stoub@microsoft.com>
2025-04-03 14:18:34 -04:00
Peder Holdgaard Pedersen
4ecb6bc240
Allow override of name and description of McpClientTool (#165) 2025-04-02 14:05:08 -07:00
Eirik Tsarpalis
f1af251c32
Allow JsonSerializerOptions parameters for user-defined and inputs and hardcode everything else to the source generator. (#182)
* Allow user-defined JsonSerializerOptions for user-defined and inputs and hardcode everything else to the source generator.

* Add validation for user-defined JsonSerializerOptions.

* Remove out of date comment.

* Address feedback and add tests
2025-04-02 18:43:54 +01:00
Stephen Toub
b12d728700
Fix pagination handling in McpServer (#177)
- We were adding tools/prompts from the collections on every request. If multiple requests came in with different cursors, we'd re-add the same tools each time.
- We were defeating the purpose of pagination by doing all of the aggregation in the server. If a custom handler returns a paginated result, we should instead propagate that back to the client, who can choose to get more results when needed.
2025-04-01 09:54:19 -04:00
Stephen Toub
96fa96c1b2
Split StdioClient/ServerTransports into Stdio : Stream (#172) 2025-03-31 18:44:54 -04:00
Stephen Toub
5d3fb65b11
Add McpServerPrompt / McpClientPrompt and friends (#126) 2025-03-31 09:54:40 -04:00
Stephen Halter
2ab9db0878
Refactor transports to help enable graceful shutdown (#142)
- This also paves the way for better multi-session support
- We should definitely rethink names for the transport API
- For now, I kept the names similar as possible, so we can
  focus on the API shape

Co-authored-by: Stephen Toub <stoub@microsoft.com>
2025-03-30 17:10:14 -07:00
Stephen Toub
62e92fa154
Add ToolAnnotations support (#124)
* Add ToolAnnotations support

* Address feedback
2025-03-28 11:08:29 -04:00
Stephen Halter
4a53f6f6d0
List tools from DI once (#115)
* List tools from DI once

- Follow best practice to not mutate options outside of IConfigureOptions
- Long-term, we should move the repeated work from SetToolsHandler into
  an IPostConfigureOptions service or IMcpServerConnectionFactory

* Add Can_Create_Multiple_Servers_From_Options_And_List_Registered_Tools

* Flip stdin and stdout in StreamClientTransport

* s/McpToolType/McpServerToolType

* Clarify stdin and stdout refers to server process in StreamClientTransport

* fixup
2025-03-27 07:26:14 -04:00
Stephen Toub
caca2ae61d
Overhaul tool handling (#89)
* Overhaul tool handling

- Renames [McpTool{Type}] to [McpServerTool{Type}], in order to distinguish representations of tools on the server from tools on the client.
- Enables [McpServerTool] methods to have arguments injected from DI, as well as a specific set of types from the implementation directly, like IMcpServer.
- Renames WithTools to WithToolsFromAssembly.
- All of the WithToolsXx methods now publish each individual McpServerTool into DI; other code can do so as well. The options setup code gathers all of the tools from DI and combines them into a collection which is then stored in McpServerOptions and used to construct the server.
- The server tools specified via DI as well as manually-provided handlers, using CallToolHandler as a fallback in case the requested tool doesn't exist in the tools collection, and ListToolsHandler augments the information for whatever tools exist.
- The tools are stored in McpServerOptions in a new McpServerToolCollection type, which is a thread-safe container that exposes add/removal notification. Adding/removing tools triggers a change notification that in turn sends a notification to the client about a tools update.
- The ServerOptions are exposed from the server instance.
- Removed cursor-based APIs from McpClientExtensions.
- Changed McpClientExtensions APIs to return `Task<IList<...>` rather than `IAsyncEnumerable<...>`.

I'm sure this will need to evolve further before we're "done", but it's a significant improvement from where we are now. One area I'm not super happy with is the notifying collection; that might work ok for a stdio server, where you can grab the created collection from the server's options and mutate it, but I don't know how well that's going to work for sse servers.

* Make McpServerTool{Collection} extensible

* Fix README.md example

* Add notifications test

* Address feedback
2025-03-25 15:32:46 -04:00
Stephen Toub
729e688b25
Make client config optional to McpClientFactory.CreateAsync (#65)
* Make client config optional to McpClientFactory.CreateAsync

Unless you're specifying capabilities (sampling/rooting) or need a specific client name/version, the client information can be inferred from the assembly, simplifying the getting-started experience.

* Cache default options

* Update src/ModelContextProtocol/Client/McpClientFactory.cs

Co-authored-by: Eirik Tsarpalis <eirik.tsarpalis@gmail.com>

---------

Co-authored-by: Eirik Tsarpalis <eirik.tsarpalis@gmail.com>
2025-03-24 11:01:13 -04:00
Stephen Toub
27ba8b1b6a
Upgrade to xunit.v3 (#8)
* Upgrade to xunit.v3

* Use Assert.Skip where applicable.

---------

Co-authored-by: Eirik Tsarpalis <eirik.tsarpalis@gmail.com>
2025-03-20 16:19:35 +02:00
Stephen Toub
555933a06e
Ensure all test client instances are cleaned up (#3) 2025-03-19 17:27:49 -04:00
Eirik Tsarpalis
c9ed453745 Rename project and namespaces 2025-03-19 15:02:38 +02:00