Skip to content

HttpRequest connecting to the /sse endpoint hits (number of tools + 1) times while building a custom auth middleware #316

Open
@justinyoo

Description

@justinyoo

Describe the bug
A clear and concise description of what the bug is.

I was adding a middleware that checks the request header whether an API key exists or not. Here's the code that I wrote:

https://github.com/microsoft/mcp-dotnet-samples/blob/f2131feb5ae79fe4491e20dee4f17089ff5b2096/youtube-subtitles-extractor-containerapp/src/McpYouTubeSubtitlesExtractor.ContainerApp/Middlewares/ApiKeyValidationMiddleware.cs#L13-L40

When I added this middleware, I found a strange behaviour that:

  • The HttpRequest instance hits the middleware multiple times (actually number of tools + 1 times) while establishing connection.
  • It occurred the same through both MCP inspector and GitHub Copilot Agent mode.
  • The first hit has got the API key from the request header.
  • But the consecutive hits didn't recognised the header value, which is null.
  • Every time I hit the "List Tools" and each tool, it keeps returning null value from the request header.
  • It works on local machine anyway and a docker container, regardless of the error.
  • It doesn't work on Azure Container Apps when it's deployed because of this error.

To Reproduce
Steps to reproduce the behavior:

  1. Clone this repo: https://github.com/microsoft/mcp-dotnet-samples
  2. Go to the youtube-subtitles-extractor-containerapp directory.
  3. Follow the instruction to run the MCP server app either on local machine or local container.
  4. Connect to this MCP server to the MCP inspector or VS Code with the endpoint of http://0.0.0.0:5202/sse?code=abcde and see it hits 3 times (because this server has 2 tools) - the first one has the key but the rest doesn't have it.

Expected behavior
A clear and concise description of what you expected to happen.

  • It shouldn't hit multiple times while establishing connections.
  • If it has to hit multiple times, every request should preserve the request header and querystring.

Logs
If applicable, add logs to help explain your problem.

Additional context
Add any other context about the problem here.

If it's not the proper approach to add custom authentication logic, which will be the best one?

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions