Skip to content

withMethodHandler resources/read #218

Done

Description

@mynona

Feature Request: Framework-Agnostic Request Context Injection for MCP Handlers

Problem

Currently, the MCP Swift SDK registers all method handlers (tools, resources, etc.) using:

@discardableResult
public func withMethodHandler<M: Method>(
    _ type: M.Type,
    handler: @escaping @Sendable (M.Parameters) async throws -> M.Result
) -> Self

This closure only receives the decoded MCP parameters (M.Parameters). There is no way to access the underlying HTTP request or any HTTP context (headers, authentication, route-local state, etc.).

Why This Is a Problem

  • Many real-world handlers (especially for resources/read, but also for tools) need access to HTTP request context to:

    • Reuse existing route logic
    • Access authentication/session data
    • Read headers, cookies, or other request-scoped information
    • Share logic/state between HTTP routes and MCP handlers
  • For tools, we can work around this by intercepting the HTTP request in our own route, enriching the MCP request, and passing both the MCP and HTTP request to our handler.

  • For resources, this is not possible: the SDK directly invokes the handler with only the MCP parameters, and there is no extension point to inject the HTTP request.

Current Workarounds

  • For resources, we are forced to use an HTTP client (e.g., URLSession) to call our own local endpoint from inside the handler, just to get the same data as the HTTP route. This is inefficient and not production-grade.
  • For tools, we must maintain a custom bridge layer, which is complex and fragile.

Proposed Solution

Add support for injecting a framework-agnostic HTTP request context into MCP handler closures.

Example API

Define a protocol in the SDK, e.g.:

public protocol RequestContext {
    var headers: [String: String] { get }
    var method: String { get }
    var path: String { get }
    var query: [String: String] { get }
    var body: Data? { get }
    // ...other common properties
}

Handler registration would then look like:

@discardableResult
public func withMethodHandler<M: Method>(
    _ type: M.Type,
    handler: @escaping @Sendable (M.Parameters, RequestContext) async throws -> M.Result
) -> Self
  • The SDK would provide a default implementation for each supported backend.
  • Vapor integration would wrap Vapor.Request as a RequestContext.
  • Other frameworks (Hummingbird, Kitura, etc.) would provide their own adapters.

Benefits

  • Keeps the SDK decoupled from any specific HTTP framework.
  • Enables code sharing between HTTP routes and MCP handlers.
  • Allows access to authentication, headers, and other request-scoped data.
  • Removes the need for inefficient HTTP self-calls and custom bridges.
  • Makes the SDK more flexible and production-ready for stateless HTTP deployments.

Summary

Please add a way to inject a framework-agnostic HTTP request context into MCP handler closures. This will enable robust, efficient, and maintainable MCP server implementations in Swift, and eliminate the need for current workarounds.

Activity

  1. added
    enhancement
    on Apr 19, 2026
  2. yehorsobko-mac commented on Apr 24, 2026

    @yehorsobko-mac
    Contributor

    Hello @mynona. Thanks for this request. I'm not sure withMethodHandler is the best place to have request context. What if there's a sort of delegate/callback/notifier in the Transport level? Will it help you in your work flow?

  3. mynona commented on Apr 24, 2026

    @mynona
    Author

    Hi,

    For tools (tools/call):

    • The MCPController and related code intercept the HTTP request before the tool handler is called.
    • This allows you to inject additional data (like a prefetched payload or context) into the tool call’s arguments.
    • As a result, the tool handler receives both the MCP parameters and any extra context you injected, making it possible to share logic and access request-scoped data.

    This works perfectly.

    For resources/read (and completions):

    • The SDK directly invokes the handler with only the decoded MCP parameters.
    • There is no interception or injection point to add context or pass the HTTP request.
    • The handler cannot access per-request data, headers, or authentication.

    Maybe resource / read, completions, etc. could follow the same pattern as tools?

  4. mynona commented on Apr 24, 2026

    @mynona
    Author

    By the way – great work with this repo / helped me a lot to set up a mcp quickly :-)

  5. yehorsobko-mac commented on Apr 24, 2026

    @yehorsobko-mac
    Contributor

    @mynona what if we inject http context into the call's task local environment? It will look like this:

    server.withMethodHandler(ReadResource.self) { params in                                                                                                                                      
          guard let http = Server.currentHandlerContext?.httpContext else { ... }                                                                                                                  
          let auth = http.header("Authorization")                                                                                                                                                  
          ...                                                                                                                                                                                      
      }  
    
  6. mynona commented on Apr 25, 2026

    @mynona
    Author

    Hi @yehorsobko-mac, Yes, this would definitely help.

    The proposal to inject a framework-agnostic HTTP request context into all MCP handler closures would directly solve the mentioned pain point.

    Thank you for considering such a change :-)

  7. yehorsobko-mac commented on Apr 29, 2026

    @yehorsobko-mac
    Contributor

    Hi @mynona there's an improvement merged that should help you, feel free to test it. If you need anything else, maybe you could create a PR into the SDK?

  8. mynona commented on Apr 30, 2026

    @mynona
    Author

    Hi @yehorsobko-mac , I can confirm that this solution works. Looking forward to the official release version. Thank you

  9. jeanmatthieu commented on Dec 5, 2026

    @jeanmatthieu
    Contributor

    Glad the HTTP context worked for you in #223! In rel/1.0.0 (#372, #416), we made this even cleaner by passing Server.HandlerContext explicitly as the second parameter of every handler registered with setHandler(for:) — read context.httpRequest directly (no task-local lookup needed). See docs/server.md#handler-context and docs/server.md#http-context. Closing as completed in 1.0.0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions