diff --git a/Sources/VGraphMCPHTTP/VGraphMCPHTTPServer.swift b/Sources/VGraphMCPHTTP/VGraphMCPHTTPServer.swift index a87e5ad..9b706b2 100644 --- a/Sources/VGraphMCPHTTP/VGraphMCPHTTPServer.swift +++ b/Sources/VGraphMCPHTTP/VGraphMCPHTTPServer.swift @@ -3,9 +3,7 @@ import Foundation import Logging -import MCP import VGraphMCPHTTPKit -import VGraphMCPTools @main struct VGraphMCPHTTPServer { @@ -15,54 +13,7 @@ struct VGraphMCPHTTPServer { let port = ProcessInfo.processInfo.environment["PORT"].flatMap(Int.init) ?? 8080 let host = "0.0.0.0" - - let server = Server( - name: "vgraph", - version: "1.0.0", - capabilities: .init( - tools: .init(listChanged: false) - ) - ) - - await server.withMethodHandler(ListTools.self) { _ in - .init(tools: VGraphTools.all.map(\.definition)) - } - - await server.withMethodHandler(CallTool.self) { params in - guard let tool = VGraphTools.all.first(where: { $0.definition.name == params.name }) - else { - return .init( - content: [ - .text( - text: "Unknown tool: \(params.name)", - annotations: nil, - _meta: nil) - ], - isError: true - ) - } - return await tool.handle(params) - } - - // Create stateless HTTP transport with cloud-safe validation - let transport = StatelessHTTPServerTransport( - validationPipeline: StandardValidationPipeline(validators: [ - OriginValidator.disabled, - AcceptHeaderValidator(mode: .jsonOnly), - ContentTypeValidator(), - ProtocolVersionValidator(), - ]), - logger: logger - ) - - try await server.start(transport: transport) - - let app = MCPHTTPApp( - transport: transport, - host: host, - port: port, - logger: logger - ) + let app = try await MCPHTTPApp.hosted(host: host, port: port, logger: logger) logger.info("Starting VGraph MCP HTTP server on \(host):\(port)") try await app.start() diff --git a/Sources/VGraphMCPHTTPKit/HostedServer.swift b/Sources/VGraphMCPHTTPKit/HostedServer.swift new file mode 100644 index 0000000..a204642 --- /dev/null +++ b/Sources/VGraphMCPHTTPKit/HostedServer.swift @@ -0,0 +1,63 @@ +import Logging +import MCP +import VGraphMCPTools + +extension MCPHTTPApp { + /// The endpoint Cloud Run serves: every VGraph tool behind the stateless transport. + public static func hosted(host: String, port: Int, logger: Logger) async throws -> MCPHTTPApp { + let server = Server( + name: "vgraph", + version: "1.0.0", + capabilities: .init(tools: .init(listChanged: false)) + ) + + await server.withMethodHandler(ListTools.self) { _ in + .init(tools: VGraphTools.all.map(\.definition)) + } + + await server.withMethodHandler(CallTool.self) { params in + guard let tool = VGraphTools.all.first(where: { $0.definition.name == params.name }) else { + return .init( + content: [.text(text: "Unknown tool: \(params.name)", annotations: nil, _meta: nil)], + isError: true + ) + } + return await tool.handle(params) + } + + let transport = StatelessHTTPServerTransport( + validationPipeline: StandardValidationPipeline(validators: [ + OriginValidator.disabled, + AcceptHeaderValidator(mode: .jsonOnly), + ContentTypeValidator(), + ProtocolVersionValidator(), + ]), + logger: logger + ) + try await server.start(transport: transport) + // After start, which installs the SDK's own handler. + await server.answerEveryInitialize() + return MCPHTTPApp(transport: transport, host: host, port: port, logger: logger) + } +} + +extension Server { + /// The SDK's own handler answers `initialize` once per Server, but over a + /// stateless transport every request may come from a different client, and a + /// client stops at a refused `initialize`. Nothing here keeps per-client state, + /// so each one is answered afresh. + func answerEveryInitialize() async { + let info = Server.Info(name: name, version: version, title: title) + let instructions = instructions + let capabilities = capabilities + withMethodHandler(Initialize.self) { params in + Initialize.Result( + protocolVersion: Version.supported.contains(params.protocolVersion) + ? params.protocolVersion : Version.latest, + capabilities: capabilities, + serverInfo: info, + instructions: instructions + ) + } + } +} diff --git a/Tests/VGraphMCPHTTPTests/InitializeTests.swift b/Tests/VGraphMCPHTTPTests/InitializeTests.swift new file mode 100644 index 0000000..1890666 --- /dev/null +++ b/Tests/VGraphMCPHTTPTests/InitializeTests.swift @@ -0,0 +1,44 @@ +import Foundation +import Logging +import MCP +import Testing + +@testable import VGraphMCPHTTPKit + +private struct InitializeReply: Decodable { + struct Result: Decodable { let protocolVersion: String } + struct Failure: Decodable { let message: String } + let result: Result? + let error: Failure? +} + +private func initialize(_ app: MCPHTTPApp, protocolVersion: String = "2025-06-18") async throws -> InitializeReply { + let body = + #"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"\#(protocolVersion)","# + + #""capabilities":{},"clientInfo":{"name":"test","version":"1"}}}"# + let response = await app.handleHTTPRequest( + NIOHTTPRequest( + method: "POST", uri: "/mcp", + headers: ["Content-Type": "application/json", "Accept": "application/json"], + body: Data(body.utf8))) + return try JSONDecoder().decode(InitializeReply.self, from: try #require(response.body)) +} + +@Suite("Hosted MCP endpoint — initialize") +struct InitializeTests { + @Test("Given a client has initialized, when a second client initializes, then it is accepted") + func secondClient() async throws { + let app = try await MCPHTTPApp.hosted(host: "127.0.0.1", port: 0, logger: Logger(label: "test")) + _ = try await initialize(app) + let second = try await initialize(app) + #expect(second.error?.message == nil) + #expect(second.result?.protocolVersion == "2025-06-18") + } + + @Test("Given a client asks for a protocol version the server lacks, when it initializes, then it is offered the latest") + func unknownVersion() async throws { + let app = try await MCPHTTPApp.hosted(host: "127.0.0.1", port: 0, logger: Logger(label: "test")) + let reply = try await initialize(app, protocolVersion: "1999-01-01") + #expect(reply.result?.protocolVersion == Version.latest) + } +}