* 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
* Adds test to show where trace IDs are encoded
Signed-off-by: Adrian Cole <adrian.cole@elastic.co>
* update impl to params._meta
Signed-off-by: Adrian Cole <adrian.cole@elastic.co>
---------
Signed-off-by: Adrian Cole <adrian.cole@elastic.co>
* Add SchemaCreateOptions in McpServerToolCreateOptions
* Use TransformSchemaNode for SchemaCreateOptions testing
* Add SchemaCreateOptions in McpServerPromptCreateOptions also
* 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
- 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
* Simplify ModelContextProtocol.AspNetCore README
* Add StreamableHttpHandler
* Use "docker info" in CheckIsDockerAvailable
* Call WithHttpTransport in samples, tests and README
* Cleanup test namespaces
* Add CanConnect_WithMcpClient_AfterCustomizingRoute test
* Simplify relative URI handling
* Handle request made directly to the MapMcp route pattern
* Add Messages_FromNewUser_AreRejected test
* Fix README
* Shorten UserIdClaim ValueTuple names
* Remove MaxReconnectAttempts and ReconnectDelay from SseClientTransportOptions
- Add proper AdditionalHeaders support
* Separate ASP.NET Core tests into a distinct project and make the main test project netfx compatible.
* Fix merge conflicts.
* Update tests/ModelContextProtocol.Tests/ModelContextProtocol.Tests.csproj
Co-authored-by: Stephen Halter <halter73@gmail.com>
* Revert "Fix merge conflicts."
This reverts commit 852169b96786bad2144795540fa164e20b4b197e.
* Fix merge conflicts
---------
Co-authored-by: Stephen Halter <halter73@gmail.com>
* 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>
* 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
* Add route pattern parameter to MapMcp
* Add configureOptionsAsync
* Use Kestrel for all in-memory HTTP tests
* Use ApplicationStopping token for SSE responses
* Use RegisterNotificationHandler in MapMcp tests
* Work around SocketsHttpHandler bug where it doesn't call DispseAsync on the stream returned by the ConnectCallback
- 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.
* 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
* Reduce dependencies to 8.x versions of packages
When building for netstandard2.0 or net8.0, the ModelContextProtocol library now only depends on 8.x versions of nuget packages, rather than using the newer 9.x versions. The exception to this are packages that don't have 8.x versions.
This also introduces a net9.0 tfm. When building for net9.0, it'll use 9.x versions of packages.
The PR temporarily removes the Microsoft.Extensions.AI.nupkg reference (the Microsoft.Extensions.AI.Abstractions reference is still very much there). The latest Microsoft.Extensions.AI package on nuget has a System.Text.Json 9.x reference, but the next build to be published drops that down to 8.x as well. Once that build is published, the dependency will be added back, and temporary polyfills (in particular TemporaryAIFunctionFactory) will be deleted.
* Fix StdioClientSessionTransport shutdown
StreamClientSessionTransport's ReadMessageAsync method does await CleanupAsync in its finally. CleanupAsync awaits _readTask. _readTask _is_ ReadMessageAsync. So it's waiting for itself to complete, which will then always timeout. We may want to refactor how this works more in the future, but for now, make sure it doesn't wait for itself.
* Fix dangling requests when server unexpectedly shuts down
If the client makes a request to the server and while waiting for the response the server shuts down, the client hangs. Make sure that when the client's message loops ends due to the server's output it's reading from ends, any pending requests are notified.
* Add net9.0 testing
* Avoid docker port conflicts from test suites running concurrently
* Changed the name of the ActivitySource and Metric to clarify that the semantic conventions have not been ratified yet.
* Update src/ModelContextProtocol/Diagnostics.cs
---------
Co-authored-by: Sam Spencer <samsp@microsoft.com>
Co-authored-by: Stephen Toub <stoub@microsoft.com>
* 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
* Move WriteJsonRpcMessageToBuffer to method
* Fix indentation in McpClient
* Make supposedly unreachable code less reachable
* Guard against multiple RunAsync calls
* Move RunAsync inside of Try in MapMcp
- 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.
* Add ModelContextProtocol.AspNetCore
- Remove IServerTransport and HttpListenerSseServerTransport
- Replace HttpListenerSseServerTransport usage in tests with ASP.NET Core.
Co-authored-by: Eirik Tsarpalis <eirik.tsarpalis@gmail.com>
Co-authored-by: Jeff Handley <jeffhandley@users.noreply.github.com>