Skip to content

Add WithMcpServer extension method for fluent MCP server endpoint configuration - #14618

Merged
David Fowler (davidfowl) merged 4 commits into
release/13.2from
copilot/add-extension-method-for-mcp-server
Feb 23, 2026
Merged

David Fowler (davidfowl) merged 4 commits into
release/13.2from
copilot/add-extension-method-for-mcp-server

Conversation

Copilot AI commented Feb 23, 2026 •

Copy link
Copy Markdown
Contributor

Description

Adds a WithMcpServer extension method for configuring MCP (Model Context Protocol) server endpoints on resources, following established Aspire API patterns.

Changes

  • New McpServerResourceBuilderExtensions class with WithMcpServer<T>() extension method in its own file (consistent with other domain-specific extensions)
  • endpointName is optional — when omitted, defaults to the first HTTPS endpoint, falling back to HTTP (same pattern as WithHttpHealthCheck)
  • path defaults to "/mcp" — can be customized or set to null for no path
  • Marked [Experimental("ASPIREMCP001")] since MCP support is still evolving
  • [EndpointName] attribute on the endpointName parameter for consistency with WithEndpoint, WithHttpEndpoint, etc.
  • Updated PostgresBuilderExtensions to use the new WithMcpServer instead of directly constructing McpServerEndpointAnnotation

Usage

// Default: uses https/http endpoint with /mcp path
var api = builder.AddProject<Projects.MyApi>("api")
    .WithMcpServer();

// Custom path and explicit endpoint
var api = builder.AddProject<Projects.MyApi>("api")
    .WithMcpServer("/sse", endpointName: "https");

Checklist

  • Is this feature complete?
    • Yes. Ready to ship.
    • No. Follow-up changes expected.
  • Are you including unit tests for the changes and scenario tests if relevant?
    • Yes
    • No
  • Did you add public API?
    • Yes — McpServerResourceBuilderExtensions.WithMcpServer<T>() (experimental)
    • No
  • Does the change make any security assumptions or guarantees?
    • Yes
    • No
  • Does the change require an update in our Aspire docs?
    • Yes
    • No

Copilot AI changed the title [WIP] Add extension method for MCP server integration Add WithMcpServer extension method for fluent MCP server endpoint configuration Feb 23, 2026
@davidfowl
David Fowler (davidfowl) force-pushed the copilot/add-extension-method-for-mcp-server branch from 5316735 to 727a7ce Compare February 23, 2026 05:50
@github-actions

github-actions Bot commented Feb 23, 2026 •

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/dotnet/aspire/main/eng/scripts/get-aspire-cli-pr.sh | bash -s -- 14618

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/dotnet/aspire/main/eng/scripts/get-aspire-cli-pr.ps1) } 14618"

@davidfowl
David Fowler (davidfowl) changed the base branch from main to release/13.2 February 23, 2026 05:50
- Move WithMcpServer from ResourceBuilderExtensions to new
  McpServerResourceBuilderExtensions class
- Make endpointName optional, defaulting to https then http fallback
  (consistent with WithHttpHealthCheck pattern)
- Add [Experimental("ASPIREMCP001")] and [EndpointName] attributes
- Update PostgresBuilderExtensions to use new extension method
- Add tests for default endpoint selection and fallback behavior

Co-authored-by: Copilot <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds a new experimental fluent API for annotating resources with an MCP (Model Context Protocol) server endpoint, and updates PostgreSQL’s MCP helper to use it.

Changes:

  • Introduces McpServerResourceBuilderExtensions.WithMcpServer<T>() to add McpServerEndpointAnnotation based on an optional endpoint name + optional path (default "/mcp").
  • Updates PostgreSQL WithPostgresMcp to call WithMcpServer("/sse", ...) instead of directly creating the annotation.
  • Adds unit tests covering default endpoint selection (https → http), default/custom/null path behavior, and fluent chaining.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.

File Description
tests/Aspire.Hosting.Tests/WithMcpServerTests.cs Adds test coverage for the new WithMcpServer extension behavior.
src/Aspire.Hosting/ResourceBuilderExtensions.cs No functional change (trailing whitespace/newline).
src/Aspire.Hosting/McpServerResourceBuilderExtensions.cs Adds the new experimental WithMcpServer extension method and its endpoint/path resolution behavior.
src/Aspire.Hosting.PostgreSQL/PostgresBuilderExtensions.cs Switches PostgreSQL MCP setup to use WithMcpServer, adding a warning suppression for the experimental API.
Comments suppressed due to low confidence (3)

src/Aspire.Hosting.PostgreSQL/PostgresBuilderExtensions.cs:5

  • #pragma warning disable ASPIREMCP001 is applied to the entire file, which can unintentionally suppress future experimental-API warnings in unrelated code. Consider scoping the suppression to the smallest region (e.g., around the single .WithMcpServer(...) call or within WithPostgresMcp) and restoring the warning afterward.
#pragma warning disable ASPIREMCP001

src/Aspire.Hosting/McpServerResourceBuilderExtensions.cs:106

  • WithMcpServer re-implements the same URL/path normalization logic that already exists in McpServerEndpointAnnotation.FromEndpoint. Duplicating this logic increases the chance the behaviors diverge over time; consider resolving the endpoint name first, then delegating to McpServerEndpointAnnotation.FromEndpoint(resolvedEndpointName, path) for the resolver portion.
        return builder.WithAnnotation(new McpServerEndpointAnnotation(async (resource, cancellationToken) =>
        {
            var endpoints = resource.GetEndpoints();
            EndpointReference? endpoint = null;

            if (endpointName is not null)
            {
                endpoint = endpoints.FirstOrDefault(e => string.Equals(e.EndpointName, endpointName, StringComparisons.EndpointAnnotationName));

                if (endpoint is null)
                {
                    throw new DistributedApplicationException(
                        $"Could not create MCP server for resource '{resource.Name}' as no endpoint was found with name '{endpointName}'.");
                }
            }
            else
            {
                foreach (var scheme in s_httpSchemes)
                {
                    endpoint = endpoints.FirstOrDefault(e => string.Equals(e.EndpointName, scheme, StringComparisons.EndpointAnnotationName));
                    if (endpoint is not null)
                    {
                        break;
                    }
                }

                if (endpoint is null)
                {
                    throw new DistributedApplicationException(
                        $"Could not create MCP server for resource '{resource.Name}' as no endpoint was found matching one of the specified names: {string.Join(", ", s_httpSchemes)}");
                }
            }

            if (!endpoint.Exists)
            {
                return null;
            }

            var baseUrl = await endpoint.GetValueAsync(cancellationToken).ConfigureAwait(false);
            if (string.IsNullOrEmpty(baseUrl))
            {
                return null;
            }

            if (string.IsNullOrEmpty(path))
            {
                return new Uri(baseUrl, UriKind.Absolute);
            }

            var normalizedPath = path;
            if (!normalizedPath.StartsWith("/", StringComparison.Ordinal))
            {
                normalizedPath = "/" + normalizedPath;
            }

            var combined = baseUrl.TrimEnd('/') + normalizedPath;
            return new Uri(combined, UriKind.Absolute);
        }));

src/Aspire.Hosting/McpServerResourceBuilderExtensions.cs:79

  • The error paths that throw DistributedApplicationException when (a) an explicit endpointName can’t be found or (b) no default http/https endpoint names exist aren’t covered by tests. Adding unit tests for these failures would lock down the intended behavior and prevent regressions in exception handling/messages.
                if (endpoint is null)
                {
                    throw new DistributedApplicationException(
                        $"Could not create MCP server for resource '{resource.Name}' as no endpoint was found with name '{endpointName}'.");
                }
            }
            else
            {
                foreach (var scheme in s_httpSchemes)
                {
                    endpoint = endpoints.FirstOrDefault(e => string.Equals(e.EndpointName, scheme, StringComparisons.EndpointAnnotationName));
                    if (endpoint is not null)
                    {
                        break;
                    }
                }

                if (endpoint is null)
                {
                    throw new DistributedApplicationException(
                        $"Could not create MCP server for resource '{resource.Name}' as no endpoint was found matching one of the specified names: {string.Join(", ", s_httpSchemes)}");
                }

@github-actions

github-actions Bot commented Feb 23, 2026 •

Copy link
Copy Markdown
Contributor

🎬 CLI E2E Test Recordings

The following terminal recordings are available for commit f39620d:

Test Recording
AddPackageInteractiveWhileAppHostRunningDetached ▶️ View Recording
AddPackageWhileAppHostRunningDetached ▶️ View Recording
AgentCommands_AllHelpOutputs_AreCorrect ▶️ View Recording
AgentInitCommand_MigratesDeprecatedConfig ▶️ View Recording
AspireUpdateRemovesAppHostPackageVersionFromDirectoryPackagesProps ▶️ View Recording
Banner_DisplayedOnFirstRun ▶️ View Recording
Banner_DisplayedWithExplicitFlag ▶️ View Recording
CreateAndDeployToDockerCompose ▶️ View Recording
CreateAndDeployToDockerComposeInteractive ▶️ View Recording
CreateAndPublishToKubernetes ▶️ View Recording
CreateAndRunAspireStarterProject ▶️ View Recording
CreateAndRunAspireStarterProjectWithBundle ▶️ View Recording
CreateAndRunJsReactProject ▶️ View Recording
CreateAndRunPythonReactProject ▶️ View Recording
CreateEmptyAppHostProject ▶️ View Recording
CreateStartAndStopAspireProject ▶️ View Recording
CreateStartWaitAndStopAspireProject ▶️ View Recording
CreateTypeScriptAppHostWithViteApp ▶️ View Recording
DoctorCommand_DetectsDeprecatedAgentConfig ▶️ View Recording
DoctorCommand_WithSslCertDir_ShowsTrusted ▶️ View Recording
DoctorCommand_WithoutSslCertDir_ShowsPartiallyTrusted ▶️ View Recording
LogsCommandShowsResourceLogs ▶️ View Recording
PsCommandListsRunningAppHost ▶️ View Recording
ResourcesCommandShowsRunningResources ▶️ View Recording
StagingChannel_ConfigureAndVerifySettings_ThenSwitchChannels ❌ Upload failed
StopAllAppHostsFromAppHostDirectory ❌ Upload failed
StopAllAppHostsFromUnrelatedDirectory ❌ Upload failed
StopNonInteractiveMultipleAppHostsShowsError ❌ Upload failed
StopNonInteractiveSingleAppHost ▶️ View Recording
StopWithNoRunningAppHostExitsSuccessfully ▶️ View Recording

📹 Recordings uploaded automatically from CI run #22295915375

@davidfowl
David Fowler (davidfowl) merged commit 2fceb30 into release/13.2 Feb 23, 2026
345 checks passed
@davidfowl
David Fowler (davidfowl) deleted the copilot/add-extension-method-for-mcp-server branch February 23, 2026 15:45
@dotnet-policy-service dotnet-policy-service Bot added this to the 13.2 milestone Feb 23, 2026
Copilot AI added a commit that referenced this pull request Mar 10, 2026
…onfiguration (#14618)

* Add WithMcpServer extension method to ResourceBuilderExtensions

Co-authored-by: davidfowl <[email protected]>

* Move WithMcpServer to dedicated class with improved API

- Move WithMcpServer from ResourceBuilderExtensions to new
  McpServerResourceBuilderExtensions class
- Make endpointName optional, defaulting to https then http fallback
  (consistent with WithHttpHealthCheck pattern)
- Add [Experimental("ASPIREMCP001")] and [EndpointName] attributes
- Update PostgresBuilderExtensions to use new extension method
- Add tests for default endpoint selection and fallback behavior

Co-authored-by: Copilot <[email protected]>

* Apply suggestions from code review

Co-authored-by: David Fowler <[email protected]>

* Update src/Aspire.Hosting/McpServerResourceBuilderExtensions.cs

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: davidfowl <[email protected]>
Co-authored-by: David Fowler <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: James Newton-King <[email protected]>
@github-actions github-actions Bot locked and limited conversation to collaborators Mar 26, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Adding custom mcp server is too manual

5 participants