Skip to content

Allow add extra headers for remote server connection #149

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions Sources/MCP/Base/Transports/HTTPClientTransport.swift
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,13 @@ public actor HTTPClientTransport: Transport {
public let endpoint: URL
private let session: URLSession

/// The standard header for mcp remote server request
private let mcpRequestHeaders = ["Accept": "application/json, text/event-stream",
"Content-Type": "application/json"]

/// The extra headers for the remote server needed like bearer token etc.
private let headers: [String: String]

/// The session ID assigned by the server, used for maintaining state across requests
public private(set) var sessionID: String?
private let streaming: Bool
Expand Down Expand Up @@ -77,13 +84,15 @@ public actor HTTPClientTransport: Transport {
/// - logger: Optional logger instance for transport events
public init(
endpoint: URL,
headers: [String: String] = [:],
configuration: URLSessionConfiguration = .default,
streaming: Bool = true,
sseInitializationTimeout: TimeInterval = 10,
logger: Logger? = nil
) {
self.init(
endpoint: endpoint,
headers: headers,
session: URLSession(configuration: configuration),
streaming: streaming,
sseInitializationTimeout: sseInitializationTimeout,
Expand All @@ -93,12 +102,14 @@ public actor HTTPClientTransport: Transport {

internal init(
endpoint: URL,
headers: [String: String],
session: URLSession,
streaming: Bool = false,
sseInitializationTimeout: TimeInterval = 10,
logger: Logger? = nil
) {
self.endpoint = endpoint
self.headers = headers
self.session = session
self.streaming = streaming
self.sseInitializationTimeout = sseInitializationTimeout
Expand Down Expand Up @@ -202,8 +213,13 @@ public actor HTTPClientTransport: Transport {

var request = URLRequest(url: endpoint)
request.httpMethod = "POST"
request.addValue("application/json, text/event-stream", forHTTPHeaderField: "Accept")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
mcpRequestHeaders
.merging(headers) { mcpHeaderValue, _ in
mcpHeaderValue
}
.forEach { key, value in
request.addValue(value, forHTTPHeaderField: key)
}
request.httpBody = data

// Add session ID if available
Expand Down