Files
xAiService/Services/XAiMcpHttpTransport.cs
T

122 lines
4.1 KiB
C#

using System;
using System.Text;
using System.Net.Http;
using System.Text.Json;
using System.Threading;
using xAiModels.Models;
using xAiModels.Helpers;
using xAiModels.Constants;
using System.Threading.Tasks;
using System.Net.Http.Headers;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
namespace xAiService.Services
{
public class XAiMcpHttpTransport
{
//
private readonly IHttpClientFactory httpClientFactory;
private readonly ILogger<XAiMcpHttpTransport> logger;
public XAiMcpHttpTransport(
IHttpClientFactory httpClientFactory,
ILogger<XAiMcpHttpTransport> logger
)
{
//
this.logger = logger;
this.httpClientFactory = httpClientFactory;
}
public async Task<XAiMcpJsonRpcResponse> SendAsync(
Uri endpoint,
Dictionary<string, string> headers,
XAiMcpJsonRpcRequest request,
CancellationToken cancellationToken = default
)
{
//
var client = httpClientFactory.CreateClient(XAiMcpConstants.XAiMcpClientName);
client.Timeout = Timeout.InfiniteTimeSpan;
//
using var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint);
//
// Add all Headers ...
foreach (var header in headers)
{
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
//
// Prepare For Accepting SSE and JSON-RPC ...
httpRequest.Headers.Accept.Clear();
httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream"));
//
var json = JsonSerializer.Serialize(request);
httpRequest.Content = new StringContent(json, Encoding.UTF8, "application/json");
headers.TryGetValue(XAiMcpConstants.XAiMcpSessionIdentifier, out var sessionId);
//
logger.LogDebug(
"MCP → {Method} | {Url} | Session={Session}",
request.Method,
endpoint,
sessionId
);
//
var response = await client
.SendAsync(
httpRequest,
HttpCompletionOption.ResponseHeadersRead,
cancellationToken
);
//
if (!response.IsSuccessStatusCode)
{
//
var errorBody = await response.Content.ReadAsStringAsync();
logger.LogError("MCP HTTP {Status} | {Body}", (int)response.StatusCode, errorBody);
//
throw new HttpRequestException(
$"MCP request failed: {response.StatusCode}. Body: {errorBody}");
}
//
// Content Type Detection ...
var contentType = response.Content.Headers.ContentType?.MediaType ?? "application/json";
if (contentType.Contains("text/event-stream"))
{
//
// SSE Answer ...
var stream = await response.Content.ReadAsStreamAsync();
await foreach (var data in XAiMcpSseReader.ReadAsync(stream, cancellationToken))
{
//
var parsed = JsonSerializer.Deserialize<XAiMcpJsonRpcResponse>(data);
if (parsed?.Id == request.Id || parsed?.Id is null)
{
return parsed;
}
}
//
throw new InvalidOperationException("SSE stream ended without matching response.");
}
else
{
//
// Simple JSON answer ...
var body = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<XAiMcpJsonRpcResponse>(body);
}
}
}
}