Branchwell

Textley / app · textley.ai / Sources / Textley / TextleyMCPHTTPServer.swift

1import Foundation
2import MCP
3import NIOCore
4import NIOHTTP1
5import NIOPosix
6
7/// NIO supplies bounded HTTP parsing; the official MCP SDK handles JSON-RPC.
8final class TextleyMCPHTTPServer {
9 private let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
10 private var channel: Channel?
11
12 func start(port: Int, handler: @escaping @Sendable (HTTPRequest) async -> HTTPResponse) async throws -> Int {
13 let channel = try await ServerBootstrap(group: group)
14 .serverChannelOption(ChannelOptions.backlog, value: 32)
15 .serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
16 .childChannelInitializer { channel in
17 channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: false).flatMapThrowing {
18 try channel.pipeline.syncOperations.addHandler(IdleStateHandler(readTimeout: .seconds(10)))
19 try channel.pipeline.syncOperations.addHandler(TextleyMCPHTTPHandler(handler: handler))
20 }
21 }
22 .bind(host: "127.0.0.1", port: port).get()
23 self.channel = channel
24 return channel.localAddress?.port ?? port
25 }
26
27 func stop() async {
28 try? await channel?.close().get()
29 channel = nil
30 try? await group.shutdownGracefully()
31 }
32}
33
34private final class TextleyMCPHTTPHandler: ChannelInboundHandler {
35 typealias InboundIn = HTTPServerRequestPart
36 typealias OutboundOut = HTTPServerResponsePart
37 private let handler: @Sendable (HTTPRequest) async -> HTTPResponse
38 private var head: HTTPRequestHead?
39 private var body = Data()
40 private var processing = false
41
42 init(handler: @escaping @Sendable (HTTPRequest) async -> HTTPResponse) { self.handler = handler }
43
44 func channelRead(context: ChannelHandlerContext, data: NIOAny) {
45 guard !processing else { return }
46 switch unwrapInboundIn(data) {
47 case .head(let head):
48 guard head.headers.count <= 64 else { reject(context, code: 431); return }
49 // Ambiguous duplicate security headers are rejected before conversion to a dictionary.
50 for name in ["host", "authorization", "origin", "content-type", "mcp-protocol-version"] {
51 guard head.headers[name].count <= 1 else { reject(context, code: 400); return }
52 }
53 self.head = head
54 case .body(var buffer):
55 guard body.count + buffer.readableBytes <= 1048576 else { reject(context, code: 413); return }
56 if let bytes = buffer.readBytes(length: buffer.readableBytes) { body.append(contentsOf: bytes) }
57 case .end:
58 guard let head else { reject(context, code: 400); return }
59 processing = true
60 let request = HTTPRequest(method: head.method.rawValue,
61 headers: Dictionary(head.headers.map { ($0.name.lowercased(), $0.value) }, uniquingKeysWith: { first, _ in first }),
62 body: body, path: head.uri)
63 let channel = context.channel
64 Task {
65 let response = await handler(request)
66 Self.write(response, to: channel)
67 }
68 }
69 }
70
71 private func reject(_ context: ChannelHandlerContext, code: Int) {
72 processing = true
73 Self.write(.error(statusCode: code, .invalidRequest("Request rejected")), to: context.channel)
74 }
75
76 private static func write(_ response: HTTPResponse, to channel: Channel) {
77 channel.eventLoop.execute {
78 let data = response.bodyData ?? Data()
79 var headers = HTTPHeaders(response.headers.map { ($0.key, $0.value) })
80 headers.replaceOrAdd(name: "Content-Length", value: "\(data.count)")
81 headers.replaceOrAdd(name: "Connection", value: "close")
82 headers.replaceOrAdd(name: "Cache-Control", value: "no-store")
83 channel.write(HTTPServerResponsePart.head(.init(version: .http1_1,
84 status: .init(statusCode: response.statusCode), headers: headers)), promise: nil)
85 if !data.isEmpty {
86 var buffer = channel.allocator.buffer(capacity: data.count)
87 buffer.writeBytes(data)
88 channel.write(HTTPServerResponsePart.body(.byteBuffer(buffer)), promise: nil)
89 }
90 channel.writeAndFlush(HTTPServerResponsePart.end(nil)).whenComplete { _ in channel.close(promise: nil) }
91 }
92 }
93
94 func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
95 if event is IdleStateHandler.IdleStateEvent { context.close(promise: nil) }
96 else { context.fireUserInboundEventTriggered(event) }
97 }
98
99 func errorCaught(context: ChannelHandlerContext, error: Error) { context.close(promise: nil) }
100}