-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlatex.cs
More file actions
66 lines (60 loc) · 2.07 KB
/
latex.cs
File metadata and controls
66 lines (60 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#:package Smith@0.2.3
#:package ModelContextProtocol@0.3.0-preview.*
#:package Microsoft.Extensions.Http@9.*
#:package SixLabors.ImageSharp@3.1.*
using Smith;
using System.ComponentModel;
using ModelContextProtocol.Server;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using Microsoft.Extensions.Logging;
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddHttpClient();
builder.Logging.AddConsole(consoleLogOptions =>
{
// Configure all logs to go to stderr
consoleLogOptions.LogToStandardErrorThreshold = LogLevel.Trace;
});
builder.Services
.AddMcpServer()
.WithStdioServerTransport()
.WithToolsFromAssembly();
await builder.Build().RunAsync();
[McpServerToolType]
public class LaTeX(IHttpClientFactory httpFactory)
{
[McpServerTool, Description("Converts LaTeX equations into markdown-formatted images for display inline.")]
public async Task<string> LatexToImageMarkdown(
[Description("The LaTeX equation to render.")] string latex,
[Description("Use dark mode by inverting the colors in the output.")] bool darkMode)
{
var colors = darkMode ? @"\bg{black}\fg{white}" : @"\bg{white}\fg{black}";
var query = WebUtility.UrlEncode(@"\small\dpi{300}" + colors + latex);
var url = $"https://latex.codecogs.com/png.image?{query}";
using var client = httpFactory.CreateClient();
using var response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
using var image = Image.Load<Rgba32>(await response.Content.ReadAsStreamAsync());
using var ms = new MemoryStream();
image.SaveAsPng(ms);
var base64 = Convert.ToBase64String(ms.ToArray());
return
$"""

""";
}
else
{
return
$"""
```latex
{latex}
```
> {response.ReasonPhrase}
""";
}
}
}