Skip to content

Idempotent initialize for Stateless HTTP MCP Servers #219

Open

Description

@mynona

Feature Request: Idempotent initialize for Stateless HTTP MCP Servers

Problem

According to the MCP protocol, clients (including agents and LLMs) may call initialize multiple times for robustness, retries, or stateless HTTP operation. The protocol expects repeated initialize calls to always succeed and return the current server capabilities and info, not an error.

However, the MCP Swift SDK currently returns an error (Server is already initialized) on repeated initialize calls. This breaks compatibility with stateless HTTP clients, RESTful integrations, and robust agent implementations that expect idempotency.

This is a protocol-level requirement, not just a convenience: stateless HTTP deployments (including REST, serverless, and agent-facing APIs) must support idempotent initialize calls to be compliant and reliable.

Why This Is a Problem

  • Clients and agents expect to be able to call initialize on every request or retry, and always get a valid result.
  • Returning an error breaks protocol compliance and causes failures in real-world integrations.
  • Workarounds (like custom middleware) add complexity and risk misconfiguration.
  • The transport layer (e.g., StatelessHTTPServerTransport) should guarantee idempotency for initialize by default.

Current Workaround

  • We implemented MCPIdempotentInitializeMiddleware to intercept repeated initialize calls and synthesize a valid result, but this should not be necessary for stateless HTTP servers.

Proposed Solution

  • When using StatelessHTTPServerTransport, the SDK should automatically make repeated initialize calls idempotent:
    • If the server is already initialized, return the current initialize result (capabilities, info, etc.) instead of an error.
    • This should be the default behavior for stateless transports, with no middleware required.
  • Optionally, document that MCPIdempotentInitializeMiddleware is only needed for stateful transports.

Benefits

  • Ensures MCP protocol compliance for all stateless HTTP deployments.
  • Simplifies server implementation and reduces boilerplate.
  • Prevents subtle bugs and integration failures for agents and clients.

Summary

Please make repeated initialize calls idempotent by default when using StatelessHTTPServerTransport, so that custom middleware is not required and MCP servers are robust, compliant, and agent-friendly out of the box.

Activity

  1. mynona commented on Apr 19, 2026

    @mynona
    Author

    Connected bug
    #144

  2. mynona commented on Apr 25, 2026

    @mynona
    Author

    Besides this is the Middleware I use as workaround to overcome the problem. You see, I have to fully create a fake initialize response

    import MCP
    import Vapor
    
    /// Middleware to ensure idempotent, stateless handling of MCP "initialize" requests.
    ///
    /// # Why this middleware exists
    ///
    /// The MCP (Model Context Protocol) server, as implemented by the official Swift SDK, is designed for stateful, long-lived connections (e.g., WebSocket, persistent HTTP/2). In this model, the `initialize` method is only meant to be called once per session. If a client calls `initialize` more than once, the SDK returns a JSON-RPC error: `Server is already initialized`.
    ///
    /// However, for stateless HTTP deployments (such as serverless, RESTful, or ephemeral HTTP servers), clients may call `initialize` on every request, or may retry it for robustness. In these cases, the server must behave idempotently: repeated `initialize` calls should always succeed and return the same result, never an error.
    ///
    /// # The problem
    ///
    /// The MCP Swift SDK does not natively support stateless or idempotent `initialize` handling. It always returns an error for repeated calls, which breaks stateless HTTP clients and consumer agents that expect idempotency.
    ///
    /// # The solution
    ///
    /// This middleware intercepts all POST requests to `/mcp` with a JSON-RPC method of `initialize`. It lets the normal handler run, but inspects the response:
    ///
    /// - If the response is a JSON-RPC error with a message like `Server is already initialized`, the middleware synthesizes a valid `initialize` result using the current MCP server's capabilities and info.
    /// - This ensures that repeated `initialize` calls always return a valid, correct result, making the server robust and production-safe for stateless HTTP use.
    ///
    /// # How it works
    ///
    /// 1. Checks if the request is a POST to `/mcp` and the method is `initialize`.
    /// 2. Lets the normal MCP handler process the request.
    /// 3. If the response contains the `already initialized` error, the middleware builds a valid `initialize` result using the MCP server's current capabilities and info (name, version, etc.), and returns it as the response.
    /// 4. If not, the original response is returned unchanged.
    ///
    /// This approach is robust against SDK changes, does not require patching the SDK, and always reflects the live server state.
    struct MCPIdempotentInitializeMiddleware: AsyncMiddleware {
        let mcpService: MCPService
        let protocolVersion: String
        let instructions: String
        let serverTitle: String
    
        func respond(
            to request: Vapor.Request,
            chainingTo next: Vapor.AsyncResponder
        ) async throws -> Vapor.Response {
            // Only intercept POST /mcp with JSON body
            guard request.method == .POST, request.url.path == "/mcp" else {
                return try await next.respond(to: request)
            }
    
            // Parse JSON-RPC method
            guard let data = request.body.data,
                let json = try? JSONSerialization.jsonObject(with: data)
                    as? [String: Any],
                let method = json["method"] as? String,
                method == "initialize"
            else {
                return try await next.respond(to: request)
            }
    
            // Let the normal handler run and inspect the response body.
            // Note: the MCP SDK returns HTTP 200 for JSON-RPC errors, so we must
            // inspect the body regardless of the HTTP status code.
            let response = try await next.respond(to: request)
            if let responseData = response.body.data,
                let responseJson = try? JSONSerialization.jsonObject(
                    with: responseData
                ) as? [String: Any],
                let error = responseJson["error"] as? [String: Any],
                let message = error["message"] as? String,
                message.contains("already initialized")
                    || message.contains("Server is already initialized")
            {
                // Synthesize a valid initialize result using MCP server properties
                let id = responseJson["id"] ?? json["id"] ?? "null"
                let server = mcpService.server
                let capabilities = await server.capabilities
                let resultBody: [String: Any] = [
                    "jsonrpc": "2.0",
                    "id": id,
                    "result": [
                        "protocolVersion": protocolVersion,
                        "instructions": instructions,
                        "serverInfo": [
                            "name": server.name,
                            "title": serverTitle,
                            "version": server.version,
                        ],
                        "capabilities": [
                            "prompts": [
                                "listChanged": capabilities.prompts?.listChanged
                                    ?? false
                            ],
                            "resources": [
                                "listChanged": capabilities.resources?.listChanged
                                    ?? false
                            ],
                            "tools": [:],
                        ],
                    ],
                ]
                let newResponse = Vapor.Response(status: .ok)
                let jsonData = try JSONSerialization.data(
                    withJSONObject: resultBody
                )
                newResponse.body = .init(data: jsonData)
                newResponse.headers.replaceOrAdd(
                    name: .contentType,
                    value: "application/json"
                )
                return newResponse
            }
            return response
        }
    }
    
  3. added a commit that references this issue on Jul 12, 2026
    5630533
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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions